forked from SamohvalovAndreyBPI2302/mtusi2026lab1
ЛР1 на 4: in-memory API, Docker, student-tests и конкурентная проверка.
Реализован контракт lab1 (X-User-Id), non-root образ, SIGTERM ≤10s, DEFENSE/REPORT.
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab1/internal/store"
|
||||
)
|
||||
|
||||
func parseJSON(r *http.Request, dst any) error {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct != "" && !strings.HasPrefix(strings.ToLower(ct), "application/json") {
|
||||
return fmt.Errorf("unsupported media type")
|
||||
}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return fmt.Errorf("malformed json")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func usernameOK(s string) bool {
|
||||
if len(s) < 3 || len(s) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func nonBlankRunes(s string) bool {
|
||||
for _, r := range s {
|
||||
if !unicode.IsSpace(r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func pageParams(r *http.Request, scope string) (int, *store.Bookmark, error) {
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, fmt.Errorf("invalid limit")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if cur := r.URL.Query().Get("cursor"); cur != "" {
|
||||
bm, err := unpackBookmark(cur)
|
||||
if err != nil || bm.Scope != scope {
|
||||
return 0, nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
return limit, bm, nil
|
||||
}
|
||||
return limit, nil, nil
|
||||
}
|
||||
|
||||
func packBookmark(b *store.Bookmark) string {
|
||||
raw := fmt.Sprintf("%s|%s|%s", b.Scope, b.CreatedAt.UTC().Format(time.RFC3339Nano), b.ID.String())
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func unpackBookmark(encoded string) (*store.Bookmark, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, fmt.Errorf("bad bookmark")
|
||||
}
|
||||
ts, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &store.Bookmark{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil
|
||||
}
|
||||
|
||||
func tsRFC3339(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
|
||||
func userWire(u *store.User) map[string]any {
|
||||
return map[string]any{
|
||||
"id": u.ID.String(),
|
||||
"username": u.Username,
|
||||
"display_name": u.DisplayName,
|
||||
"created_at": tsRFC3339(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func chatWire(c *store.Chat) map[string]any {
|
||||
members := make([]string, len(c.MemberIDs))
|
||||
for i, id := range c.MemberIDs {
|
||||
members[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": c.ID.String(),
|
||||
"title": c.Title,
|
||||
"member_ids": members,
|
||||
"created_at": tsRFC3339(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func messageWire(m *store.Message) map[string]any {
|
||||
return map[string]any{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"created_at": tsRFC3339(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func pageWire(items []map[string]any, next *store.Bookmark) map[string]any {
|
||||
var cursor any
|
||||
if next != nil {
|
||||
cursor = packBookmark(next)
|
||||
}
|
||||
return map[string]any{"items": items, "next_cursor": cursor}
|
||||
}
|
||||
|
||||
func (s *Service) writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func (s *Service) writeErr(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
rid := reqID(r)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": rid,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func displayNameOK(name string) bool {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return false
|
||||
}
|
||||
return utf8.RuneCountInString(name) <= 100
|
||||
}
|
||||
|
||||
func titleOK(title string) bool {
|
||||
title = strings.TrimSpace(title)
|
||||
if title == "" {
|
||||
return false
|
||||
}
|
||||
return utf8.RuneCountInString(title) <= 100
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab1/internal/store"
|
||||
)
|
||||
|
||||
// Service — HTTP-обработчики поверх in-memory store.
|
||||
type Service struct {
|
||||
DB *store.MemoryDB
|
||||
ready atomic.Bool
|
||||
draining atomic.Bool
|
||||
}
|
||||
|
||||
func New(db *store.MemoryDB) *Service {
|
||||
s := &Service{DB: db}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Service) SetReady(ok bool) { s.ready.Store(ok) }
|
||||
|
||||
func (s *Service) BeginDrain() {
|
||||
s.draining.Store(true)
|
||||
s.ready.Store(false)
|
||||
}
|
||||
|
||||
func (s *Service) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", s.live)
|
||||
mux.HandleFunc("GET /health/ready", s.readyProbe)
|
||||
mux.HandleFunc("POST /api/v1/users", s.registerUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", s.requireUser(s.whoAmI))
|
||||
mux.HandleFunc("POST /api/v1/chats", s.requireUser(s.openChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", s.requireUser(s.listChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.fetchChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.postMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.listMessages))
|
||||
return requestIdentity(accessLog(mux))
|
||||
}
|
||||
|
||||
func (s *Service) live(w http.ResponseWriter, r *http.Request) {
|
||||
s.writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Service) readyProbe(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.ready.Load() {
|
||||
s.writeErr(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down")
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Service) registerUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
if err := parseJSON(r, &body); err != nil {
|
||||
if err.Error() == "unsupported media type" {
|
||||
s.writeErr(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||
return
|
||||
}
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
if !usernameOK(body.Username) {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
display := strings.TrimSpace(body.DisplayName)
|
||||
if !displayNameOK(display) {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
u, err := s.DB.CreateUser(body.Username, display)
|
||||
if err == store.ErrConflict {
|
||||
s.writeErr(w, r, http.StatusConflict, "conflict", "username already taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusCreated, userWire(u))
|
||||
}
|
||||
|
||||
func (s *Service) whoAmI(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.DB.GetUser(actorID(r))
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, userWire(u))
|
||||
}
|
||||
|
||||
func (s *Service) openChat(w http.ResponseWriter, r *http.Request) {
|
||||
me := actorID(r)
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := parseJSON(r, &body); err != nil {
|
||||
if err.Error() == "unsupported media type" {
|
||||
s.writeErr(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||
return
|
||||
}
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
if !titleOK(body.Title) {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||
return
|
||||
}
|
||||
if len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||
return
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(body.MemberIDs))
|
||||
members := make([]uuid.UUID, 0, len(body.MemberIDs))
|
||||
selfIncluded := false
|
||||
for _, raw := range body.MemberIDs {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid member id")
|
||||
return
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "duplicate member id")
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == me {
|
||||
selfIncluded = true
|
||||
}
|
||||
members = append(members, id)
|
||||
}
|
||||
if !selfIncluded {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "caller must be a member")
|
||||
return
|
||||
}
|
||||
chat, err := s.DB.CreateChat(strings.TrimSpace(body.Title), members)
|
||||
if err == store.ErrNotFound {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "unknown member")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusCreated, chatWire(chat))
|
||||
}
|
||||
|
||||
func (s *Service) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
me := actorID(r)
|
||||
limit, after, err := pageParams(r, "chats:"+me.String())
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
items, next, err := s.DB.ListChats(me, limit, after)
|
||||
if err == store.ErrInvalidCursor {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
wire := make([]map[string]any, len(items))
|
||||
for i, c := range items {
|
||||
wire[i] = chatWire(c)
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, pageWire(wire, next))
|
||||
}
|
||||
|
||||
func (s *Service) fetchChat(w http.ResponseWriter, r *http.Request) {
|
||||
me := actorID(r)
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
chat, err := s.DB.GetChat(chatID, me)
|
||||
if err == store.ErrNotFound {
|
||||
s.writeErr(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, chatWire(chat))
|
||||
}
|
||||
|
||||
func (s *Service) postMessage(w http.ResponseWriter, r *http.Request) {
|
||||
me := actorID(r)
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := parseJSON(r, &body); err != nil {
|
||||
if err.Error() == "unsupported media type" {
|
||||
s.writeErr(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||
return
|
||||
}
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
if !nonBlankRunes(body.Text) {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(body.Text) > 4000 {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||
return
|
||||
}
|
||||
msg, err := s.DB.CreateMessage(chatID, me, body.Text)
|
||||
if err == store.ErrNotFound {
|
||||
s.writeErr(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusCreated, messageWire(msg))
|
||||
}
|
||||
|
||||
func (s *Service) listMessages(w http.ResponseWriter, r *http.Request) {
|
||||
me := actorID(r)
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
limit, after, err := pageParams(r, "chat:"+chatID.String())
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
items, next, err := s.DB.ListMessages(chatID, me, limit, after)
|
||||
if err == store.ErrNotFound {
|
||||
s.writeErr(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err == store.ErrInvalidCursor {
|
||||
s.writeErr(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeErr(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
wire := make([]map[string]any, len(items))
|
||||
for i, m := range items {
|
||||
wire[i] = messageWire(m)
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, pageWire(wire, next))
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
ctxUserID ctxKey = iota
|
||||
ctxReqID
|
||||
)
|
||||
|
||||
type responseTap struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (t *responseTap) WriteHeader(code int) {
|
||||
t.status = code
|
||||
t.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func requestIdentity(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rid := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
if rid == "" {
|
||||
rid = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", rid)
|
||||
ctx := context.WithValue(r.Context(), ctxReqID, rid)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func accessLog(next http.Handler) http.Handler {
|
||||
quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") ||
|
||||
strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false")
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
tap := &responseTap{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(tap, r)
|
||||
if quiet && strings.HasPrefix(r.URL.Path, "/api/") && tap.status < 400 {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") && tap.status == 200 {
|
||||
return
|
||||
}
|
||||
rid := tap.Header().Get("X-Request-Id")
|
||||
if rid == "" {
|
||||
rid, _ = r.Context().Value(ctxReqID).(string)
|
||||
}
|
||||
log.Printf("http method=%s path=%s status=%d request_id=%s ms=%d",
|
||||
r.Method, r.URL.Path, tap.status, rid, time.Since(start).Milliseconds())
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
raw := strings.TrimSpace(r.Header.Get("X-User-Id"))
|
||||
if raw == "" {
|
||||
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil || !s.DB.UserExists(id) {
|
||||
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
next(w, r.WithContext(context.WithValue(r.Context(), ctxUserID, id)))
|
||||
}
|
||||
}
|
||||
|
||||
func actorID(r *http.Request) uuid.UUID {
|
||||
v, _ := r.Context().Value(ctxUserID).(uuid.UUID)
|
||||
return v
|
||||
}
|
||||
|
||||
func reqID(r *http.Request) string {
|
||||
if v, ok := r.Context().Value(ctxReqID).(string); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
}
|
||||
portStr := getenv("APP_PORT", "8080")
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return cfg, fmt.Errorf("invalid APP_PORT: %q", portStr)
|
||||
}
|
||||
cfg.Port = port
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
|
||||
type chatRoom struct {
|
||||
meta Chat
|
||||
messages []*Message
|
||||
}
|
||||
|
||||
// MemoryDB — потокобезопасное хранилище в RAM одного процесса.
|
||||
type MemoryDB struct {
|
||||
mu sync.RWMutex
|
||||
users map[uuid.UUID]*User
|
||||
byName map[string]uuid.UUID
|
||||
rooms map[uuid.UUID]*chatRoom
|
||||
}
|
||||
|
||||
func New() *MemoryDB {
|
||||
return &MemoryDB{
|
||||
users: make(map[uuid.UUID]*User),
|
||||
byName: make(map[string]uuid.UUID),
|
||||
rooms: make(map[uuid.UUID]*chatRoom),
|
||||
}
|
||||
}
|
||||
|
||||
func (db *MemoryDB) CreateUser(username, displayName string) (*User, error) {
|
||||
db.mu.Lock()
|
||||
defer db.mu.Unlock()
|
||||
if _, taken := db.byName[username]; taken {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Millisecond),
|
||||
}
|
||||
db.users[u.ID] = u
|
||||
db.byName[username] = u.ID
|
||||
return copyUser(u), nil
|
||||
}
|
||||
|
||||
func (db *MemoryDB) GetUser(id uuid.UUID) (*User, error) {
|
||||
db.mu.RLock()
|
||||
defer db.mu.RUnlock()
|
||||
u, ok := db.users[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return copyUser(u), nil
|
||||
}
|
||||
|
||||
func (db *MemoryDB) UserExists(id uuid.UUID) bool {
|
||||
db.mu.RLock()
|
||||
defer db.mu.RUnlock()
|
||||
_, ok := db.users[id]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (db *MemoryDB) CreateChat(title string, members []uuid.UUID) (*Chat, error) {
|
||||
db.mu.Lock()
|
||||
defer db.mu.Unlock()
|
||||
for _, id := range members {
|
||||
if _, ok := db.users[id]; !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
c := Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), members...),
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Millisecond),
|
||||
}
|
||||
db.rooms[c.ID] = &chatRoom{meta: c}
|
||||
return copyChat(&c), nil
|
||||
}
|
||||
|
||||
func (db *MemoryDB) GetChat(chatID, viewer uuid.UUID) (*Chat, error) {
|
||||
db.mu.RLock()
|
||||
defer db.mu.RUnlock()
|
||||
room, ok := db.rooms[chatID]
|
||||
if !ok || !memberOf(&room.meta, viewer) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return copyChat(&room.meta), nil
|
||||
}
|
||||
|
||||
func (db *MemoryDB) ListChats(viewer uuid.UUID, limit int, after *Bookmark) ([]*Chat, *Bookmark, error) {
|
||||
if after != nil && after.Scope != chatListScope(viewer) {
|
||||
return nil, nil, ErrInvalidCursor
|
||||
}
|
||||
db.mu.RLock()
|
||||
defer db.mu.RUnlock()
|
||||
var mine []*Chat
|
||||
for _, room := range db.rooms {
|
||||
if memberOf(&room.meta, viewer) {
|
||||
mine = append(mine, copyChat(&room.meta))
|
||||
}
|
||||
}
|
||||
sort.Slice(mine, func(i, j int) bool {
|
||||
if !mine[i].CreatedAt.Equal(mine[j].CreatedAt) {
|
||||
return mine[i].CreatedAt.Before(mine[j].CreatedAt)
|
||||
}
|
||||
return uuidOrder(mine[i].ID, mine[j].ID)
|
||||
})
|
||||
return paginateChats(mine, limit, after, viewer)
|
||||
}
|
||||
|
||||
func (db *MemoryDB) CreateMessage(chatID, sender uuid.UUID, text string) (*Message, error) {
|
||||
db.mu.Lock()
|
||||
defer db.mu.Unlock()
|
||||
room, ok := db.rooms[chatID]
|
||||
if !ok || !memberOf(&room.meta, sender) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
m := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: sender,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Millisecond),
|
||||
}
|
||||
room.messages = append(room.messages, m)
|
||||
return copyMessage(m), nil
|
||||
}
|
||||
|
||||
func (db *MemoryDB) ListMessages(chatID, viewer uuid.UUID, limit int, after *Bookmark) ([]*Message, *Bookmark, error) {
|
||||
if after != nil && after.Scope != messageListScope(chatID) {
|
||||
return nil, nil, ErrInvalidCursor
|
||||
}
|
||||
db.mu.RLock()
|
||||
defer db.mu.RUnlock()
|
||||
room, ok := db.rooms[chatID]
|
||||
if !ok || !memberOf(&room.meta, viewer) {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
items := make([]*Message, len(room.messages))
|
||||
for i, m := range room.messages {
|
||||
items[i] = copyMessage(m)
|
||||
}
|
||||
sort.SliceStable(items, func(i, j int) bool {
|
||||
if !items[i].CreatedAt.Equal(items[j].CreatedAt) {
|
||||
return items[i].CreatedAt.Before(items[j].CreatedAt)
|
||||
}
|
||||
return uuidOrder(items[i].ID, items[j].ID)
|
||||
})
|
||||
return paginateMessages(items, limit, after, chatID)
|
||||
}
|
||||
|
||||
func paginateChats(all []*Chat, limit int, after *Bookmark, viewer uuid.UUID) ([]*Chat, *Bookmark, error) {
|
||||
start := findStart(all, after, func(c *Chat) (time.Time, uuid.UUID) {
|
||||
return c.CreatedAt, c.ID
|
||||
})
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
var next *Bookmark
|
||||
if end < len(all) && len(page) > 0 {
|
||||
last := page[len(page)-1]
|
||||
next = &Bookmark{Scope: chatListScope(viewer), CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
out := make([]*Chat, len(page))
|
||||
for i, c := range page {
|
||||
out[i] = c
|
||||
}
|
||||
return out, next, nil
|
||||
}
|
||||
|
||||
func paginateMessages(all []*Message, limit int, after *Bookmark, chatID uuid.UUID) ([]*Message, *Bookmark, error) {
|
||||
start := findStart(all, after, func(m *Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
var next *Bookmark
|
||||
if end < len(all) && len(page) > 0 {
|
||||
last := page[len(page)-1]
|
||||
next = &Bookmark{Scope: messageListScope(chatID), CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
out := make([]*Message, len(page))
|
||||
for i, m := range page {
|
||||
out[i] = m
|
||||
}
|
||||
return out, next, nil
|
||||
}
|
||||
|
||||
func findStart[T any](rows []T, after *Bookmark, pick func(T) (time.Time, uuid.UUID)) int {
|
||||
if after == nil {
|
||||
return 0
|
||||
}
|
||||
for i, row := range rows {
|
||||
ts, id := pick(row)
|
||||
if ts.After(after.CreatedAt) || (ts.Equal(after.CreatedAt) && uuidOrder(after.ID, id)) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return len(rows)
|
||||
}
|
||||
|
||||
func chatListScope(user uuid.UUID) string { return "chats:" + user.String() }
|
||||
func messageListScope(chat uuid.UUID) string { return "chat:" + chat.String() }
|
||||
|
||||
func memberOf(c *Chat, user uuid.UUID) bool {
|
||||
for _, id := range c.MemberIDs {
|
||||
if id == user {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func uuidOrder(a, b uuid.UUID) bool {
|
||||
for i := 0; i < 16; i++ {
|
||||
if a[i] != b[i] {
|
||||
return a[i] < b[i]
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func copyUser(u *User) *User {
|
||||
cp := *u
|
||||
return &cp
|
||||
}
|
||||
|
||||
func copyChat(c *Chat) *Chat {
|
||||
cp := *c
|
||||
cp.MemberIDs = append([]uuid.UUID(nil), c.MemberIDs...)
|
||||
return &cp
|
||||
}
|
||||
|
||||
func copyMessage(m *Message) *Message {
|
||||
cp := *m
|
||||
return &cp
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Bookmark — позиция keyset-пагинации (created_at, id) в рамках scope.
|
||||
type Bookmark struct {
|
||||
Scope string
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
Reference in New Issue
Block a user