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()
|
||||
}
|
||||
Reference in New Issue
Block a user