Skeleton contracts / contracts (pull_request) Blocked by required conditions
Реализован контракт lab1 (X-User-Id), non-root образ, SIGTERM ≤10s, DEFENSE/REPORT.
270 lines
8.1 KiB
Go
270 lines
8.1 KiB
Go
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))
|
|
} |