refactor: isolate attachment lifecycle

This commit is contained in:
2026-10-09 13:13:59 +03:00
parent ad36ab8a92
commit cc4ac1ddd7
33 changed files with 1672 additions and 982 deletions
+164
View File
@@ -0,0 +1,164 @@
package httpapi
import (
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
started := time.Now()
result := "client_error"
defer func() {
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
}()
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return invalidRequest()
}
filename, valid := attachmentFilename(query)
if !valid {
return invalidRequest()
}
uploaded, err := s.attachments.Upload(r.Context(), attachment.Upload{
ChatID: chatID, OwnerID: user.ID, Filename: filename,
ContentType: r.Header.Get("Content-Type"), ContentLength: r.ContentLength, Body: r.Body,
})
if err != nil {
if errors.Is(err, model.ErrCapacity) {
result = "capacity_rejected"
w.Header().Set("Retry-After", "1")
} else if errors.Is(err, model.ErrUnavailable) {
result = "dependency_error"
}
return attachmentError(err)
}
result = "success"
s.metrics.attachmentBytes.Add(float64(uploaded.SizeBytes))
writeJSON(w, http.StatusCreated, uploaded)
return nil
}
func attachmentFilename(query url.Values) (string, bool) {
if len(query) != 1 || len(query["filename"]) != 1 {
return "", false
}
filename := query["filename"][0]
length := utf8.RuneCountInString(filename)
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
return "", false
}
for _, char := range filename {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", false
}
}
return filename, true
}
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
attachmentID, apiErr := attachmentIDFromRequest(r)
if apiErr != nil {
return apiErr
}
value, err := s.attachments.Metadata(r.Context(), attachmentID, user.ID)
if err != nil {
return attachmentError(err)
}
writeJSON(w, http.StatusOK, value)
return nil
}
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil || !originalVariant(query) {
return invalidRequest()
}
attachmentID, apiErr := attachmentIDFromRequest(r)
if apiErr != nil {
return apiErr
}
content, err := s.attachments.Content(r.Context(), attachmentID, user.ID)
if err != nil {
return attachmentError(err)
}
defer func() { _ = content.Body.Close() }()
w.Header().Set("Content-Type", content.Attachment.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(content.Attachment.SizeBytes, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": content.Attachment.Filename}))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, content.Body); err != nil {
s.logger.Warn("attachment download interrupted", "attachment_id", content.Attachment.ID, "error", err)
}
return nil
}
func originalVariant(query url.Values) bool {
if len(query) == 0 {
return true
}
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
}
func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
attachmentID, valid := canonicalID(parts[3])
if !valid {
return "", invalidRequest()
}
return attachmentID, nil
}
func attachmentError(err error) *apiError {
switch {
case errors.Is(err, model.ErrNotFound):
return notFound()
case errors.Is(err, model.ErrInvalidInput):
return invalidRequest()
case errors.Is(err, model.ErrUnsupportedMedia):
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
case errors.Is(err, model.ErrPayloadTooLarge):
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
case errors.Is(err, model.ErrCapacity):
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
default:
return unavailable()
}
}
+111
View File
@@ -0,0 +1,111 @@
package httpapi
import (
"errors"
"io"
"net/http"
"strings"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
if err != nil || len(body) != 0 {
return invalidRequest()
}
username, passwordValue, ok := singleBasicAuth(r)
if !ok {
return unauthorized()
}
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
if errors.Is(err, model.ErrNotFound) {
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
return internalError()
}
return unauthorized()
}
if err != nil {
return unavailable()
}
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
if err != nil {
return internalError()
}
if !verified {
return unauthorized()
}
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User User `json:"user"`
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
return nil
}
func singleBasicAuth(r *http.Request) (string, string, bool) {
if len(r.Header.Values("Authorization")) != 1 {
return "", "", false
}
username, passwordValue, ok := r.BasicAuth()
return username, passwordValue, ok && username != ""
}
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodDelete {
return methodNotAllowed(w, http.MethodDelete)
}
_, token, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, model.ErrSessionNotFound) {
return unauthorized()
} else if err != nil {
return unavailable()
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
values := r.Header.Values("Authorization")
if len(values) != 1 {
return User{}, "", unauthorized()
}
scheme, token, found := strings.Cut(values[0], " ")
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
return User{}, "", unauthorized()
}
userID, err := s.sessions.UserID(r.Context(), token)
if errors.Is(err, model.ErrSessionNotFound) || errors.Is(err, model.ErrInvalidToken) {
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
user, err := s.userRepository.UserByID(r.Context(), userID)
if errors.Is(err, model.ErrNotFound) {
_ = s.sessions.Delete(r.Context(), token)
return User{}, "", unauthorized()
}
if err != nil {
return User{}, "", unavailable()
}
return user, token, nil
}
func authenticationChallenge(r *http.Request) string {
if r.URL.Path == "/api/v1/auth/sessions" {
return `Basic realm="messenger", charset="UTF-8"`
}
return `Bearer realm="messenger"`
}
+61
View File
@@ -0,0 +1,61 @@
package httpapi
import (
"encoding/json"
"net/http"
)
const (
errorCodeInvalidRequest = "invalid_request"
errorCodeUnauthorized = "unauthorized"
errorCodeNotFound = "not_found"
errorCodeInternal = "internal_error"
errorCodeUnsupportedMediaType = "unsupported_media_type"
errorCodePayloadTooLarge = "payload_too_large"
errorCodeUnavailable = "unavailable"
errorCodeConflict = "conflict"
errorCodeRateLimited = "rate_limited"
)
type apiError struct {
status int
code string
message string
}
func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError {
w.Header().Set("Allow", allowed)
return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"}
}
func invalidRequest() *apiError {
return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"}
}
func unauthorized() *apiError {
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
}
func notFound() *apiError {
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
}
func internalError() *apiError {
return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"}
}
func unavailable() *apiError {
return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"}
}
func writeError(w http.ResponseWriter, requestID string, err *apiError) {
writeJSON(w, err.status, map[string]any{"error": map[string]string{
"code": err.code, "message": err.message, "request_id": requestID,
}})
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
+302
View File
@@ -0,0 +1,302 @@
package httpapi
import (
"context"
"errors"
"net/http"
"regexp"
"strings"
"time"
"unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
if !s.ready.Load() {
return unavailable()
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.database.Ping(ctx); err != nil {
return unavailable()
}
if err := s.sessions.Ping(ctx); err != nil {
return unavailable()
}
if err := s.objects.Ping(ctx); err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
var input struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
return invalidRequest()
}
passwordHash, err := s.passwords.Hash(input.Password)
if err != nil {
return internalError()
}
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
if errors.Is(err, model.ErrConflict) {
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, user)
return nil
}
func validPassword(value string) bool {
length := utf8.RuneCountInString(value)
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
}
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, err := s.authenticate(r)
if err != nil {
return err
}
writeJSON(w, http.StatusOK, user)
return nil
}
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if r.Method == http.MethodGet {
return s.listChats(w, r, user)
}
var input struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
return invalidRequest()
}
members := make(map[string]struct{}, len(input.MemberIDs))
for i, memberID := range input.MemberIDs {
canonical, valid := canonicalID(memberID)
if !valid {
return invalidRequest()
}
if _, duplicate := members[canonical]; duplicate {
return invalidRequest()
}
members[canonical] = struct{}{}
input.MemberIDs[i] = canonical
}
if _, included := members[user.ID]; !included {
return invalidRequest()
}
chat, err := s.chatRepository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
if errors.Is(err, model.ErrInvalidMembers) {
return invalidRequest()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusCreated, chat)
return nil
}
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
limit, cursor, err := pageParams(r, "chat", user.ID)
if err != nil {
return err
}
items, hasNext, listErr := s.chatRepository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, model.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Chat{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
chat, err := s.chatRepository.ChatForUser(r.Context(), chatID, user.ID)
if errors.Is(err, model.ErrNotFound) {
return notFound()
}
if err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, chat)
return nil
}
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodPost && r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
if r.Method == http.MethodGet {
return s.listMessages(w, r, user, chatID)
}
key, valid := idempotencyKey(r)
if !valid {
return invalidRequest()
}
var input struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
return invalidRequest()
}
message, replay, err := s.messageRepository.CreateMessage(
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
)
if errors.Is(err, model.ErrNotFound) {
return notFound()
}
if errors.Is(err, model.ErrIdempotencyConflict) {
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
}
if err != nil {
return unavailable()
}
if replay {
s.metrics.replays.Inc()
}
writeJSON(w, http.StatusCreated, message)
return nil
}
func validMessage(text string, attachmentIDs []string) bool {
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 {
return false
}
return len(attachmentIDs) > 0 || strings.TrimSpace(text) != ""
}
func canonicalAttachmentIDs(attachmentIDs []string) bool {
if len(attachmentIDs) > 10 {
return false
}
seen := make(map[string]struct{}, len(attachmentIDs))
for index, attachmentID := range attachmentIDs {
canonical, valid := canonicalID(attachmentID)
if !valid {
return false
}
if _, duplicate := seen[canonical]; duplicate {
return false
}
seen[canonical] = struct{}{}
attachmentIDs[index] = canonical
}
return true
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
limit, cursor, err := pageParams(r, "message", chatID)
if err != nil {
return err
}
items, hasNext, listErr := s.messageRepository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
if errors.Is(listErr, model.ErrNotFound) {
return notFound()
}
if errors.Is(listErr, model.ErrInvalidCursor) {
return invalidRequest()
}
if listErr != nil {
return unavailable()
}
if items == nil {
items = []Message{}
}
var next *string
if hasNext {
last := items[len(items)-1]
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
next = &value
}
writeJSON(w, http.StatusOK, struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}{items, next})
return nil
}
func cursorPosition(cursor *pageCursor) *model.Position {
if cursor == nil {
return nil
}
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
}
@@ -0,0 +1,49 @@
package httpapi
import (
"context"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
type UserRepository interface {
CreateUser(context.Context, string, string, string) (model.User, error)
UserByID(context.Context, string) (model.User, error)
UserByUsername(context.Context, string) (model.UserCredentials, error)
}
type ChatRepository interface {
CreateChat(context.Context, string, []string, string) (model.Chat, error)
ChatForUser(context.Context, string, string) (model.Chat, error)
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
}
type MessageRepository interface {
CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error)
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
}
type AttachmentService interface {
Upload(context.Context, attachment.Upload) (model.Attachment, error)
Metadata(context.Context, string, string) (model.Attachment, error)
Content(context.Context, string, string) (attachment.Content, error)
}
type HealthChecker interface {
Ping(context.Context) error
}
type SessionStore interface {
HealthChecker
Create(context.Context, string, time.Duration) (string, time.Time, error)
UserID(context.Context, string) (string, error)
Delete(context.Context, string) error
}
type PasswordService interface {
Hash(string) (string, error)
Verify(string, string) (bool, error)
DummyHash() string
}
+114
View File
@@ -0,0 +1,114 @@
package httpapi
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type metrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
replays prometheus.Counter
attachmentUploads *prometheus.CounterVec
attachmentDuration prometheus.Histogram
attachmentBytes prometheus.Counter
handler http.Handler
}
func newMetrics() *metrics {
registry := prometheus.NewRegistry()
result := &metrics{
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_total",
Help: "Completed HTTP requests.",
}, []string{"method", "route", "status_class"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: prometheus.DefBuckets,
}, []string{"method", "route"}),
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "requests_in_flight",
Help: "HTTP requests currently being served.",
}),
replays: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "idempotency_replays_total",
Help: "Message requests served from an idempotency record.",
}),
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Name: "attachment_uploads_total",
Help: "Completed attachment uploads by result.",
}, []string{"result"}),
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: "messenger",
Name: "attachment_upload_duration_seconds",
Help: "Attachment upload duration in seconds.",
Buckets: prometheus.DefBuckets,
}),
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger",
Name: "attachment_upload_bytes_total",
Help: "Bytes accepted by successful attachment uploads.",
}),
}
registry.MustRegister(
result.requests,
result.duration,
result.inFlight,
result.replays,
result.attachmentUploads,
result.attachmentDuration,
result.attachmentBytes,
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
return result
}
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
route := routeTemplate(r.URL.Path)
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
}
func routeTemplate(path string) string {
switch path {
case "/health/live", "/health/ready", "/metrics", "/api/v1/users", "/api/v1/users/me",
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
return path
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
return "/api/v1/chats/{chat_id}/messages"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
return "/api/v1/chats/{chat_id}/attachments"
}
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
return "/api/v1/attachments/{attachment_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
return "/api/v1/attachments/{attachment_id}/content"
}
return "unknown"
}
+30
View File
@@ -0,0 +1,30 @@
package httpapi
import (
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
"github.com/google/uuid"
)
type User = model.User
type Chat = model.Chat
type Message = model.Message
type Attachment = model.Attachment
func newID() (string, error) {
id, err := uuid.NewRandom()
if err != nil {
return "", err
}
return id.String(), nil
}
func canonicalID(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
id, err := uuid.Parse(value)
if err != nil {
return "", false
}
return id.String(), true
}
+127
View File
@@ -0,0 +1,127 @@
package httpapi
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const maxRequestBytes = 1 << 20
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
}
return invalidRequest()
}
if !utf8.Valid(data) {
return invalidRequest()
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil || object == nil {
return invalidRequest()
}
normalized, err := json.Marshal(object)
if err != nil {
return invalidRequest()
}
decoder := json.NewDecoder(bytes.NewReader(normalized))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return invalidRequest()
}
return nil
}
func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
func idempotencyKey(r *http.Request) (string, bool) {
values := r.Header.Values("Idempotency-Key")
if len(values) != 1 || !idempotencyKeyPattern.MatchString(values[0]) {
return "", false
}
return values[0], true
}
type pageCursor struct {
Kind string `json:"kind"`
Resource string `json:"resource"`
Time time.Time `json:"time"`
ID string `json:"id"`
}
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, invalidRequest()
}
for key := range query {
if key != "limit" && key != "cursor" {
return 0, nil, invalidRequest()
}
if len(query[key]) != 1 {
return 0, nil, invalidRequest()
}
}
limit := 50
if value, present := query["limit"]; present {
parsed, err := strconv.Atoi(value[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, nil, invalidRequest()
}
limit = parsed
}
if value, present := query["cursor"]; present {
cursor, valid := decodeCursor(value[0], kind, resource)
if !valid {
return 0, nil, invalidRequest()
}
return limit, cursor, nil
}
return limit, nil, nil
}
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
data, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return nil, false
}
var cursor pageCursor
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
return nil, false
}
if cursor.Time.IsZero() {
return nil, false
}
if _, valid := canonicalID(cursor.ID); !valid {
return nil, false
}
return &cursor, true
}
+47
View File
@@ -0,0 +1,47 @@
package httpapi
import (
"net/http"
"strings"
)
type requestHandler func(http.ResponseWriter, *http.Request) *apiError
func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
var handler requestHandler
switch r.URL.Path {
case "/health/live":
handler = s.live
case "/health/ready":
handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users":
handler = s.users
case "/api/v1/users/me":
handler = s.me
case "/api/v1/auth/sessions":
handler = s.createSession
case "/api/v1/auth/sessions/current":
handler = s.revokeSession
case "/api/v1/chats":
handler = s.chats
default:
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
handler = s.chat
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
handler = s.messages
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
handler = s.uploadAttachment
} else if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
handler = s.attachmentMetadata
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
handler = s.attachmentContent
} else {
return notFound()
}
}
return handler(w, r)
}
+133
View File
@@ -0,0 +1,133 @@
package httpapi
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
)
type Dependencies struct {
Users UserRepository
Chats ChatRepository
Messages MessageRepository
Attachments AttachmentService
Sessions SessionStore
Passwords PasswordService
Database HealthChecker
Objects HealthChecker
}
type Config struct {
SessionTTL time.Duration
IdempotencyTTL time.Duration
RequestTTL time.Duration
InstanceID string
SwaggerPort string
}
type Server struct {
userRepository UserRepository
chatRepository ChatRepository
messageRepository MessageRepository
attachments AttachmentService
sessions SessionStore
passwords PasswordService
database HealthChecker
objects HealthChecker
sessionTTL time.Duration
idempotencyTTL time.Duration
requestTTL time.Duration
instanceID string
logger *slog.Logger
swaggerPort string
metrics *metrics
ready atomic.Bool
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func NewServer(
logger *slog.Logger,
dependencies Dependencies,
config Config,
) *Server {
s := &Server{
userRepository: dependencies.Users, chatRepository: dependencies.Chats,
messageRepository: dependencies.Messages,
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort, metrics: newMetrics(),
}
s.ready.Store(true)
return s
}
func (s *Server) SetReady(ready bool) {
s.ready.Store(ready)
}
func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve)
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", s.instanceID)
requestID, err := newID()
if err != nil {
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("X-Request-Id", requestID)
w.Header().Set("Cache-Control", "no-store")
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
started := time.Now()
s.metrics.inFlight.Inc()
defer func() {
s.metrics.inFlight.Dec()
if recovered := recover(); recovered != nil {
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
if wrapped.status == http.StatusOK {
writeError(wrapped, requestID, internalError())
}
}
s.metrics.observe(r, wrapped.status, started)
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
}()
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Idempotency-Key")
wrapped.WriteHeader(http.StatusNoContent)
return
}
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
defer cancel()
r = r.WithContext(ctx)
if apiErr := s.route(wrapped, r); apiErr != nil {
if apiErr.status == http.StatusUnauthorized {
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
}
writeError(wrapped, requestID, apiErr)
}
}
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
return false
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Instance-Id")
w.Header().Add("Vary", "Origin")
return true
}
+333
View File
@@ -0,0 +1,333 @@
package httpapi
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
var errDependency = errors.New("dependency unavailable")
type MessengerSuite struct {
suite.Suite
logger *slog.Logger
}
func TestMessengerSuite(t *testing.T) {
suite.Run(t, new(MessengerSuite))
}
func (s *MessengerSuite) SetupTest() {
s.logger = slog.New(slog.NewTextHandler(io.Discard, nil))
}
type messengerStoreStub struct {
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
}
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
func (messengerStoreStub) CreateUser(context.Context, string, string, string) (model.User, error) {
return model.User{}, nil
}
func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error) {
return s.userByID, s.userByIDErr
}
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
return s.credentials, s.credentialsErr
}
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
return nil, false, nil
}
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error) {
return s.message, s.messageReplay, s.messageErr
}
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
return nil, false, nil
}
type objectStoreStub struct {
pingErr error
}
func (s objectStoreStub) Ping(context.Context) error { return s.pingErr }
type attachmentServiceStub struct {
uploaded model.Attachment
err error
}
func (s attachmentServiceStub) Upload(context.Context, attachment.Upload) (model.Attachment, error) {
return s.uploaded, s.err
}
func (s attachmentServiceStub) Metadata(context.Context, string, string) (model.Attachment, error) {
return s.uploaded, s.err
}
func (s attachmentServiceStub) Content(context.Context, string, string) (attachment.Content, error) {
return attachment.Content{Attachment: s.uploaded, Body: io.NopCloser(strings.NewReader("content"))}, s.err
}
type sessionStub struct {
pingErr error
userID string
userIDErr error
}
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
return "token", time.Now().Add(time.Hour), nil
}
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
func (sessionStub) Delete(context.Context, string) error { return nil }
type passwordsStub struct {
verified bool
err error
}
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
func (passwordsStub) DummyHash() string { return "hash" }
func (s passwordsStub) Verify(string, string) (bool, error) {
return s.verified, s.err
}
func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
t := s.T()
tests := []struct {
name string
store messengerStoreStub
sessions sessionStub
objects objectStoreStub
}{
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
{name: "s3", objects: objectStoreStub{pingErr: errDependency}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{})
response := serveRequest(server, http.MethodGet, "/health/ready", "")
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
})
}
}
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
t := s.T()
tests := []struct {
name string
store messengerStoreStub
sessions sessionStub
}{
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
{name: "postgres", store: messengerStoreStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", "Bearer valid-token")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
})
}
}
func (s *MessengerSuite) TestAuthenticationChallenges() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
}
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
server = s.newTestServer(store, sessionStub{}, passwordsStub{verified: false})
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("user", "wrong-password")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
}
}
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveRequest(
server,
http.MethodGet,
"/api/v1/attachments/00000000-0000-0000-0000-000000000001/content?variant=invalid",
"",
)
s.Equal(http.StatusUnauthorized, response.Code)
s.Equal(`Bearer realm="messenger"`, response.Header().Get("WWW-Authenticate"))
}
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
request.ContentLength = -1
request.SetBasicAuth("user", "password")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
}
func (s *MessengerSuite) TestRegistrationRejectsWhitespacePassword() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
}
func (s *MessengerSuite) TestInstanceHeaderIsSetOnSuccessAndError() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
for _, response := range []*httptest.ResponseRecorder{
serveRequest(server, http.MethodGet, "/health/live", ""),
serveRequest(server, http.MethodGet, "/api/v1/users/me", ""),
} {
if value := response.Header().Get("X-Instance-Id"); value != "test-instance" {
t.Fatalf("X-Instance-Id = %q, want test-instance", value)
}
}
}
func (s *MessengerSuite) TestMessageCreationValidatesIdempotencyKey() {
t := s.T()
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
tests := []struct {
name string
key string
}{
{name: "missing"},
{name: "invalid", key: "invalid key"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"message"}`))
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
if tt.key != "" {
request.Header.Set("Idempotency-Key", tt.key)
}
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
})
}
}
func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() {
t := s.T()
store := messengerStoreStub{
userByID: model.User{ID: "user-id"},
messageErr: fmt.Errorf("create message: %w", model.ErrIdempotencyConflict),
}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"different"}`))
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "same-key")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusConflict {
t.Fatalf("status = %d, want %d", response.Code, http.StatusConflict)
}
}
func (s *MessengerSuite) TestAttachmentFilenameValidation() {
for _, filename := range []string{"", " ", "../photo.png", "dir\\photo.png", "photo\x00.png", "photo\n.png"} {
_, valid := attachmentFilename(map[string][]string{"filename": {filename}})
s.False(valid, filename)
}
filename, valid := attachmentFilename(map[string][]string{"filename": {"фото.png"}})
s.True(valid)
s.Equal("фото.png", filename)
}
func (s *MessengerSuite) TestUploadRejectsMalformedQuery() {
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png&junk=%GG",
strings.NewReader("image"),
)
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "image/png")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
s.Equal(http.StatusBadRequest, response.Code)
}
func (s *MessengerSuite) newTestServer(store messengerStoreStub, sessions SessionStore, passwords PasswordService) *Server {
return s.server(store, sessions, passwords, objectStoreStub{}, attachmentServiceStub{})
}
func (s *MessengerSuite) server(
store messengerStoreStub,
sessions SessionStore,
passwords PasswordService,
objects objectStoreStub,
attachments AttachmentService,
) *Server {
return NewServer(s.logger, Dependencies{
Users: store, Chats: store, Messages: store, Attachments: attachments,
Sessions: sessions, Passwords: passwords, Database: store, Objects: objects,
}, Config{
SessionTTL: time.Hour, IdempotencyTTL: 24 * time.Hour, RequestTTL: time.Second,
InstanceID: "test-instance", SwaggerPort: "8081",
})
}
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response
}