Выполнение lab4 на 4

This commit is contained in:
Daria0w0
2026-11-06 17:35:48 +03:00
parent 9197e151ba
commit 879463c947
89 changed files with 5551 additions and 108 deletions
+92
View File
@@ -0,0 +1,92 @@
package httpapi
import (
"context"
"io"
"log"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
func createAttachment(w http.ResponseWriter, r *http.Request, attachments *service.Attachments, chatID string) {
if !requireMethod(w, r, http.MethodPost) {
return
}
if attachments == nil {
writeAppError(w, store.ErrUnavailable)
return
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil || len(query["filename"]) != 1 {
writeAppError(w, service.ErrInvalidRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second)
defer cancel()
a, err := attachments.Create(ctx, userFromContext(ctx).ID, chatID, query.Get("filename"), r.Header.Get("Content-Type"), r.Body, r.ContentLength)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, a)
}
func attachmentRoutes(w http.ResponseWriter, r *http.Request, attachments *service.Attachments) {
if !requireMethod(w, r, http.MethodGet) {
return
}
if attachments == nil {
writeAppError(w, store.ErrUnavailable)
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/attachments/"), "/")
if parts[0] == "" || len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") {
writeAppError(w, store.ErrNotFound)
return
}
a, err := attachments.Get(r.Context(), userFromContext(r.Context()).ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
if len(parts) == 1 {
writeJSON(w, http.StatusOK, a)
return
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
writeAppError(w, service.ErrInvalidRequest)
return
}
if len(query["variant"]) > 1 {
writeAppError(w, service.ErrInvalidRequest)
return
}
if variant := query.Get("variant"); variant != "" && variant != "original" {
writeAppError(w, store.ErrNotFound)
return
}
original, err := attachments.Open(r.Context(), a)
if err != nil {
writeAppError(w, err)
return
}
defer original.Body.Close()
w.Header().Set("Content-Type", a.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
if _, err := io.CopyBuffer(w, original.Body, make([]byte, 32*1024)); err != nil {
log.Print("attachment download stream interrupted")
// Headers may already be sent: abort rather than append a JSON error to bytes.
panic(http.ErrAbortHandler)
}
}
+2 -1
View File
@@ -14,7 +14,8 @@ type createChatRequest struct {
}
type createMessageRequest struct {
Text string `json:"text"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (api *API) chatRoutes(w http.ResponseWriter, r *http.Request) {
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"sync"
"testing"
"time"
@@ -340,7 +341,7 @@ func TestMessagePagination(t *testing.T) {
}
for i := range sent {
if got[i] != sent[i] {
if !reflect.DeepEqual(got[i], sent[i]) {
t.Fatalf("message %d differs or is out of order", i)
}
}
@@ -490,7 +491,7 @@ func TestConcurrentMessages100From10Clients(t *testing.T) {
seen[message.ID] = true
want, exists := expected[message.ID]
if !exists || want != message {
if !exists || !reflect.DeepEqual(want, message) {
t.Fatalf("missing or changed message: %s", message.ID)
}
}
+15
View File
@@ -1,12 +1,15 @@
package httpapi
import (
"context"
"errors"
"log"
"net/http"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/objectstore"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/upload"
)
type errorResponse struct {
@@ -21,6 +24,18 @@ type errorDetails struct {
func writeAppError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrAttachmentNotReady):
writeError(w, http.StatusConflict, "conflict", "Attachment is not ready")
case errors.Is(err, upload.ErrTooLarge):
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "Attachment limit exceeded")
case errors.Is(err, upload.ErrMediaType):
writeError(w, http.StatusUnsupportedMediaType, "unsupported_media_type", "Valid PNG or JPEG required")
case errors.Is(err, upload.ErrFilename), errors.Is(err, upload.ErrInterrupted):
writeError(w, http.StatusBadRequest, "invalid_request", "Invalid attachment request")
case errors.Is(err, objectstore.ErrNotFound):
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
case errors.Is(err, objectstore.ErrUnavailable), errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled):
writeError(w, http.StatusServiceUnavailable, "unavailable", "Service temporarily unavailable")
case errors.Is(err, store.ErrIdempotencyConflict):
writeError(w, http.StatusConflict, "conflict", "Idempotency key already used for another message")
+6 -2
View File
@@ -19,6 +19,10 @@ func readJSON(
dst any,
requiredFields ...string,
) bool {
return readJSONFields(w, r, dst, requiredFields, nil)
}
func readJSONFields(w http.ResponseWriter, r *http.Request, dst any, requiredFields, optionalFields []string) bool {
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
writeError(
@@ -67,8 +71,8 @@ func readJSON(
return invalid()
}
for name := range fields {
if !slices.Contains(requiredFields, name) {
for name, value := range fields {
if (!slices.Contains(requiredFields, name) && !slices.Contains(optionalFields, name)) || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
return invalid()
}
}
+15 -2
View File
@@ -10,19 +10,22 @@ import (
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (http.Handler, error) {
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64, attachmentServices ...*service.Attachments) (http.Handler, error) {
registration := service.NewRegistration(db)
sessions, err := service.NewSessions(db, registration, ttl)
if err != nil {
return nil, err
}
chats := &persistentAPI{messenger: service.NewPersistentMessenger(db)}
if len(attachmentServices) > 0 {
chats.attachments = attachmentServices[0]
}
return withInstanceID(withRequestID(withAccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stopping.Load() && r.URL.Path != "/health/live" {
writeAppError(w, store.ErrUnavailable)
return
}
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") || strings.HasPrefix(r.URL.Path, "/api/v1/attachments/") {
token, err := bearerToken(r)
if err != nil {
sessionError(w, err, false)
@@ -34,6 +37,10 @@ func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int6
return
}
ctx := context.WithValue(r.Context(), userContextKey{}, user)
if strings.HasPrefix(r.URL.Path, "/api/v1/attachments/") {
attachmentRoutes(w, r.WithContext(ctx), chats.attachments)
return
}
chats.chatRoutes(w, r.WithContext(ctx))
return
}
@@ -54,6 +61,12 @@ func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int6
writeAppError(w, err)
return
}
if chats.attachments != nil {
if err := chats.attachments.Ready(r.Context()); err != nil {
writeAppError(w, err)
return
}
}
handleHealth(w, r)
case "/api/v1/users":
if !requireMethod(w, r, http.MethodPost) {
+10 -3
View File
@@ -8,7 +8,10 @@ import (
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type persistentAPI struct{ messenger *service.PersistentMessenger }
type persistentAPI struct {
messenger *service.PersistentMessenger
attachments *service.Attachments
}
func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
actor := userFromContext(r.Context())
@@ -53,6 +56,10 @@ func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
parts := strings.Split(path, "/")
if len(parts) == 2 && parts[0] != "" && parts[1] == "attachments" {
createAttachment(w, r, api.attachments, parts[0])
return
}
if len(parts) == 1 && parts[0] != "" {
if !requireMethod(w, r, http.MethodGet) {
@@ -83,12 +90,12 @@ func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
var body createMessageRequest
if !readJSON(w, r, &body, "text") {
if !readJSONFields(w, r, &body, []string{"text"}, []string{"attachment_ids"}) {
return
}
message, err := api.messenger.CreateMessage(r.Context(),
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"),
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"), body.AttachmentIDs...,
)
if err != nil {
writeAppError(w, err)