Перенес основы lab3 в lab4

This commit is contained in:
Daria0w0
2026-11-06 14:44:30 +03:00
parent ec540a1a72
commit 9197e151ba
59 changed files with 4761 additions and 3 deletions
+27
View File
@@ -0,0 +1,27 @@
package httpapi
import (
"context"
"net/http"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
)
type userContextKey struct{}
func (api *API) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := api.messenger.CurrentUser(r.Header.Get("X-User-Id"))
if err != nil {
writeAppError(w, err)
return
}
ctx := context.WithValue(r.Context(), userContextKey{}, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func userFromContext(ctx context.Context) model.User {
return ctx.Value(userContextKey{}).(model.User)
}
+169
View File
@@ -0,0 +1,169 @@
package httpapi
import (
"net/http"
"strconv"
"strings"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type createChatRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type createMessageRequest struct {
Text string `json:"text"`
}
func (api *API) chatRoutes(w http.ResponseWriter, r *http.Request) {
actor := userFromContext(r.Context())
if r.URL.Path == "/api/v1/chats" {
switch r.Method {
case http.MethodPost:
var body createChatRequest
if !readJSON(w, r, &body, "title", "member_ids") {
return
}
chat, err := api.messenger.CreateChat(
actor.ID, body.Title, body.MemberIDs,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, chat)
case http.MethodGet:
limit, cursor, ok := pageParams(w, r)
if !ok {
return
}
page, err := api.messenger.ListChats(actor.ID, limit, cursor)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, page)
default:
requireMethod(w, r, "GET, POST")
}
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
parts := strings.Split(path, "/")
if len(parts) == 1 && parts[0] != "" {
if !requireMethod(w, r, http.MethodGet) {
return
}
chat, err := api.messenger.GetChat(actor.ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, chat)
return
}
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
return
}
chat, err := api.messenger.GetChat(actor.ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
switch r.Method {
case http.MethodPost:
var body createMessageRequest
if !readJSON(w, r, &body, "text") {
return
}
message, err := api.messenger.CreateMessage(
actor.ID, chat.ID, body.Text,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, message)
case http.MethodGet:
limit, cursor, ok := pageParams(w, r)
if !ok {
return
}
page, err := api.messenger.ListMessages(
actor.ID, chat.ID, limit, cursor,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, page)
default:
requireMethod(w, r, "GET, POST")
}
}
func pageParams(
w http.ResponseWriter,
r *http.Request,
) (int, string, bool) {
invalid := func() (int, string, bool) {
writeAppError(w, service.ErrInvalidRequest)
return 0, "", false
}
query := r.URL.Query()
limit := 50
if values, exists := query["limit"]; exists {
if len(values) != 1 || values[0] == "" {
return invalid()
}
for _, char := range values[0] {
if char < '0' || char > '9' {
return invalid()
}
}
value, err := strconv.Atoi(values[0])
if err != nil || value < 1 || value > 100 {
return invalid()
}
limit = value
}
cursor := ""
if values, exists := query["cursor"]; exists {
if len(values) != 1 || values[0] == "" {
return invalid()
}
cursor = values[0]
}
return limit, cursor, true
}
+502
View File
@@ -0,0 +1,502 @@
package httpapi_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type chatTestClient struct {
base string
client *http.Client
}
func newChatTestClient(t *testing.T) *chatTestClient {
t.Helper()
server := httptest.NewServer(newAPI())
t.Cleanup(server.Close)
client := server.Client()
client.Timeout = 10 * time.Second
return &chatTestClient{
base: server.URL,
client: client,
}
}
func (c *chatTestClient) call(
method string,
path string,
actorID string,
body any,
wantStatus int,
result any,
) error {
var encoded []byte
var err error
if body != nil {
encoded, err = json.Marshal(body)
if err != nil {
return err
}
}
req, err := http.NewRequest(
method,
c.base+path,
bytes.NewReader(encoded),
)
if err != nil {
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if actorID != "" {
req.Header.Set("X-User-Id", actorID)
}
response, err := c.client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode != wantStatus {
return fmt.Errorf(
"%s %s: status=%d, want=%d, body=%s",
method, path, response.StatusCode, wantStatus, data,
)
}
requestID := response.Header.Get("X-Request-Id")
if requestID == "" {
return fmt.Errorf("%s %s: missing request ID", method, path)
}
if wantStatus >= 400 {
var problem struct {
Error struct {
Code string `json:"code"`
RequestID string `json:"request_id"`
} `json:"error"`
}
if err := json.Unmarshal(data, &problem); err != nil {
return err
}
if problem.Error.Code == "" ||
problem.Error.RequestID != requestID {
return fmt.Errorf("invalid error response: %s", data)
}
}
if result != nil {
return json.Unmarshal(data, result)
}
return nil
}
func mustCall(
t *testing.T,
c *chatTestClient,
method string,
path string,
actorID string,
body any,
status int,
result any,
) {
t.Helper()
if err := c.call(method, path, actorID, body, status, result); err != nil {
t.Fatal(err)
}
}
func createTestUser(
t *testing.T,
c *chatTestClient,
username string,
) model.User {
t.Helper()
var user model.User
mustCall(
t, c, http.MethodPost, "/api/v1/users", "",
map[string]any{
"username": username,
"display_name": username,
},
http.StatusCreated, &user,
)
return user
}
func createTestChat(
t *testing.T,
c *chatTestClient,
actorID string,
members []string,
) model.Chat {
t.Helper()
var chat model.Chat
mustCall(
t, c, http.MethodPost, "/api/v1/chats", actorID,
map[string]any{
"title": "Test chat",
"member_ids": members,
},
http.StatusCreated, &chat,
)
return chat
}
func readAllMessages(
t *testing.T,
c *chatTestClient,
actorID string,
chatID string,
limit int,
) ([]model.Message, int) {
t.Helper()
var messages []model.Message
cursor := ""
pages := 0
seenCursors := make(map[string]bool)
for {
path := fmt.Sprintf(
"/api/v1/chats/%s/messages?limit=%d",
chatID, limit,
)
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
var page service.Page[model.Message]
mustCall(
t, c, http.MethodGet, path, actorID,
nil, http.StatusOK, &page,
)
pages++
if page.Items == nil {
t.Fatal("items must be an array, not null")
}
if len(page.Items) > limit {
t.Fatal("page exceeds requested limit")
}
messages = append(messages, page.Items...)
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
if cursor == "" || seenCursors[cursor] || pages > 100 {
t.Fatal("invalid or repeating pagination cursor")
}
seenCursors[cursor] = true
}
return messages, pages
}
func TestChatAccessAndValidation(t *testing.T) {
c := newChatTestClient(t)
alice := createTestUser(t, c, "alice")
bob := createTestUser(t, c, "bob")
eve := createTestUser(t, c, "eve")
chat := createTestChat(
t, c, alice.ID, []string{alice.ID, bob.ID},
)
path := "/api/v1/chats/" + chat.ID
mustCall(
t, c, http.MethodGet, path, eve.ID,
nil, http.StatusNotFound, nil,
)
mustCall(
t, c, http.MethodGet, path+"/messages", eve.ID,
nil, http.StatusNotFound, nil,
)
mustCall(
t, c, http.MethodPost, path+"/messages", eve.ID,
map[string]any{"text": "not allowed"},
http.StatusNotFound, nil,
)
var hidden service.Page[model.Chat]
mustCall(
t, c, http.MethodGet, "/api/v1/chats", eve.ID,
nil, http.StatusOK, &hidden,
)
if len(hidden.Items) != 0 {
t.Fatal("outsider sees a private chat")
}
for _, text := range []string{"", " \t\n"} {
mustCall(
t, c, http.MethodPost, path+"/messages", alice.ID,
map[string]any{"text": text},
http.StatusBadRequest, nil,
)
}
mustCall(
t, c, http.MethodPost, path+"/messages", alice.ID,
map[string]any{
"text": "hello",
"sender_id": bob.ID,
},
http.StatusBadRequest, nil,
)
for _, members := range [][]string{
{alice.ID, alice.ID},
{bob.ID},
{alice.ID, "00000000-0000-4000-8000-000000000000"},
} {
mustCall(
t, c, http.MethodPost, "/api/v1/chats", alice.ID,
map[string]any{
"title": "Invalid chat",
"member_ids": members,
},
http.StatusBadRequest, nil,
)
}
var chats service.Page[model.Chat]
mustCall(
t, c, http.MethodGet, "/api/v1/chats", alice.ID,
nil, http.StatusOK, &chats,
)
if len(chats.Items) != 1 {
t.Fatalf("expected one chat, got %d", len(chats.Items))
}
messages, _ := readAllMessages(t, c, alice.ID, chat.ID, 10)
if len(messages) != 0 {
t.Fatal("rejected messages were saved")
}
}
func TestMessagePagination(t *testing.T) {
c := newChatTestClient(t)
alice := createTestUser(t, c, "alice")
chat := createTestChat(t, c, alice.ID, []string{alice.ID})
other := createTestChat(t, c, alice.ID, []string{alice.ID})
path := "/api/v1/chats/" + chat.ID + "/messages"
var sent []model.Message
for i := 0; i < 7; i++ {
var message model.Message
mustCall(
t, c, http.MethodPost, path, alice.ID,
map[string]any{"text": fmt.Sprintf("Сообщение %d 👋", i)},
http.StatusCreated, &message,
)
sent = append(sent, message)
}
got, pages := readAllMessages(t, c, alice.ID, chat.ID, 2)
if len(got) != len(sent) || pages != 4 {
t.Fatalf("got %d messages on %d pages", len(got), pages)
}
for i := range sent {
if got[i] != sent[i] {
t.Fatalf("message %d differs or is out of order", i)
}
}
var first service.Page[model.Message]
mustCall(
t, c, http.MethodGet, path+"?limit=2", alice.ID,
nil, http.StatusOK, &first,
)
if first.NextCursor == nil {
t.Fatal("expected next cursor")
}
cursor := url.QueryEscape(*first.NextCursor)
var next service.Page[model.Message]
mustCall(
t, c, http.MethodGet,
path+"?limit=3&cursor="+cursor, alice.ID,
nil, http.StatusOK, &next,
)
if len(next.Items) != 3 || next.Items[0].ID != sent[2].ID {
t.Fatal("changing page size lost or repeated a message")
}
mustCall(
t, c, http.MethodGet,
"/api/v1/chats/"+other.ID+"/messages?cursor="+cursor,
alice.ID, nil, http.StatusBadRequest, nil,
)
for _, query := range []string{
"limit=0",
"limit=101",
"limit=abc",
"cursor=invalid",
} {
mustCall(
t, c, http.MethodGet, path+"?"+query, alice.ID,
nil, http.StatusBadRequest, nil,
)
}
}
func TestConcurrentMessages100From10Clients(t *testing.T) {
c := newChatTestClient(t)
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
users := make([]model.User, clients)
memberIDs := make([]string, clients)
for i := range users {
users[i] = createTestUser(t, c, fmt.Sprintf("user_%02d", i))
memberIDs[i] = users[i].ID
}
chat := createTestChat(t, c, users[0].ID, memberIDs)
path := "/api/v1/chats/" + chat.ID + "/messages"
type outcome struct {
message model.Message
err error
}
results := make(chan outcome, total)
start := make(chan struct{})
var wg sync.WaitGroup
for clientIndex := 0; clientIndex < clients; clientIndex++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
<-start
for j := 0; j < messagesPerClient; j++ {
text := fmt.Sprintf("client-%d-message-%d", index, j)
var message model.Message
err := c.call(
http.MethodPost,
path,
users[index].ID,
map[string]any{"text": text},
http.StatusCreated,
&message,
)
if err == nil &&
(message.SenderID != users[index].ID ||
message.Text != text ||
message.ChatID != chat.ID) {
err = fmt.Errorf("incorrect message response")
}
results <- outcome{message: message, err: err}
}
}(clientIndex)
}
close(start)
wg.Wait()
close(results)
expected := make(map[string]model.Message, total)
for result := range results {
if result.err != nil {
t.Errorf("send failed: %v", result.err)
continue
}
if _, exists := expected[result.message.ID]; exists {
t.Errorf("duplicate response ID: %s", result.message.ID)
}
expected[result.message.ID] = result.message
}
if t.Failed() {
t.FailNow()
}
if len(expected) != total {
t.Fatalf("expected %d unique responses, got %d", total, len(expected))
}
history, pages := readAllMessages(
t, c, users[0].ID, chat.ID, 17,
)
if len(history) != total {
t.Fatalf("expected %d stored messages, got %d", total, len(history))
}
seen := make(map[string]bool, total)
for _, message := range history {
if seen[message.ID] {
t.Fatalf("duplicate history ID: %s", message.ID)
}
seen[message.ID] = true
want, exists := expected[message.ID]
if !exists || want != message {
t.Fatalf("missing or changed message: %s", message.ID)
}
}
t.Logf(
"clients=%d sent=%d unique_responses=%d stored=%d unique_stored=%d pages=%d",
clients, total, len(expected), len(history), len(seen), pages,
)
}
+87
View File
@@ -0,0 +1,87 @@
package httpapi
import (
"errors"
"log"
"net/http"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
type errorResponse struct {
Error errorDetails `json:"error"`
}
type errorDetails struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
func writeAppError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
writeError(w, http.StatusConflict, "conflict", "Idempotency key already used for another message")
case errors.Is(err, store.ErrUnavailable):
writeError(w, http.StatusServiceUnavailable, "unavailable", "Service temporarily unavailable")
case errors.Is(err, service.ErrInvalidRequest):
writeError(
w, http.StatusBadRequest,
"invalid_request", "Invalid request fields",
)
case errors.Is(err, service.ErrUnauthorized):
writeError(
w, http.StatusUnauthorized,
"unauthorized", "Valid X-User-Id is required",
)
case errors.Is(err, store.ErrUsernameTaken):
writeError(
w, http.StatusConflict,
"conflict", "Username already exists",
)
case errors.Is(err, store.ErrInvalidMembers):
writeError(
w, http.StatusBadRequest,
"invalid_request", "Invalid chat members",
)
case errors.Is(err, store.ErrNotFound):
writeError(
w, http.StatusNotFound,
"not_found", "Resource not found",
)
default:
log.Printf(
"internal error request_id=%s: %v",
w.Header().Get("X-Request-Id"),
err,
)
writeError(
w, http.StatusInternalServerError,
"internal_error", "Internal server error",
)
}
}
func writeError(
w http.ResponseWriter,
status int,
code string,
message string,
) {
writeJSON(w, status, errorResponse{
Error: errorDetails{
Code: code,
Message: message,
RequestID: w.Header().Get("X-Request-Id"),
},
})
}
+23
View File
@@ -0,0 +1,23 @@
package httpapi
import "net/http"
func handleHealth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
writeError(
w,
http.StatusMethodNotAllowed,
"invalid_request",
"Method not allowed",
)
return
}
writeJSON(w, http.StatusOK, struct {
Status string `json:"status"`
}{
Status: "ok",
})
}
+48
View File
@@ -0,0 +1,48 @@
package httpapi_test
import (
"net/http"
"sync/atomic"
"testing"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
func TestInstanceIDOnResponses(t *testing.T) {
var stopping atomic.Bool
handler, err := httpapi.NewPostgresHandler(&store.PostgresStore{}, &stopping, 3600)
if err != nil {
t.Fatal(err)
}
var instanceID string
for _, tc := range []struct {
path string
stopping bool
status int
}{
{"/health/live", false, http.StatusOK},
{"/missing", false, http.StatusNotFound},
{"/api/v1/chats", false, http.StatusUnauthorized},
{"/health/ready", true, http.StatusServiceUnavailable},
{"/health/live", true, http.StatusOK},
} {
stopping.Store(tc.stopping)
response := request(handler, http.MethodGet, tc.path, "", "")
if response.Code != tc.status {
t.Fatalf("%s: status=%d, want %d", tc.path, response.Code, tc.status)
}
got := response.Header().Get("X-Instance-Id")
if got == "" {
t.Fatal("missing X-Instance-Id")
}
if instanceID != "" && got != instanceID {
t.Fatalf("instance changed: %q -> %q", instanceID, got)
}
instanceID = got
}
response := request(newAPI(), http.MethodGet, "/health/live", "", "")
if got := response.Header().Get("X-Instance-Id"); got != instanceID {
t.Fatalf("different handlers in one process: %q != %q", got, instanceID)
}
}
+100
View File
@@ -0,0 +1,100 @@
package httpapi
import (
"bytes"
"encoding/json"
"io"
"log"
"mime"
"net/http"
"slices"
"unicode/utf8"
)
const maxJSONBody = 1 << 20 // 1 MiB
func readJSON(
w http.ResponseWriter,
r *http.Request,
dst any,
requiredFields ...string,
) bool {
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
writeError(
w,
http.StatusUnsupportedMediaType,
"unsupported_media_type",
"Content-Type must be application/json",
)
return false
}
defer r.Body.Close()
body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONBody+1))
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "Cannot read body")
return false
}
if len(body) > maxJSONBody {
writeError(
w,
http.StatusRequestEntityTooLarge,
"payload_too_large",
"JSON body is too large",
)
return false
}
invalid := func() bool {
writeError(
w,
http.StatusBadRequest,
"invalid_request",
"Invalid JSON body",
)
return false
}
if !utf8.Valid(body) {
return invalid()
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(body, &fields); err != nil || fields == nil {
return invalid()
}
for name := range fields {
if !slices.Contains(requiredFields, name) {
return invalid()
}
}
for _, name := range requiredFields {
value, exists := fields[name]
if !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
return invalid()
}
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(dst); err != nil {
return invalid()
}
return true
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(body); err != nil {
log.Printf("cannot write JSON response: %v", err)
}
}
+99
View File
@@ -0,0 +1,99 @@
package httpapi_test
import (
"encoding/json"
"fmt"
"net/http"
"testing"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
func TestJSONFieldNamesAreCaseSensitive(t *testing.T) {
handler := newAPI()
t.Run("registration", func(t *testing.T) {
for _, body := range []string{
`{"username":"alice","display_name":"Original","Display_Name":"Changed"}`,
`{"Display_Name":"Changed","username":"alice","display_name":"Original"}`,
`{"username":"alice","display_name":"Original","Username":"bob"}`,
`{"username":"alice","Display_Name":"Changed"}`,
} {
checkError(t, request(handler, http.MethodPost, "/api/v1/users", body, ""),
http.StatusBadRequest, "invalid_request")
}
})
created := request(handler, http.MethodPost, "/api/v1/users",
`{"username":"alice","display_name":"Original"}`, "")
if created.Code != http.StatusCreated {
t.Fatalf("valid registration: %d %s", created.Code, created.Body.String())
}
var user model.User
if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil {
t.Fatal(err)
}
if user.DisplayName != "Original" {
t.Fatalf("display name changed: %q", user.DisplayName)
}
t.Run("chat", func(t *testing.T) {
for _, body := range []string{
fmt.Sprintf(`{"title":"Original","Title":"Changed","member_ids":[%q]}`, user.ID),
fmt.Sprintf(`{"Title":"Changed","title":"Original","member_ids":[%q]}`, user.ID),
fmt.Sprintf(`{"title":"Original","member_ids":[%q],"Member_Ids":[]}`, user.ID),
fmt.Sprintf(`{"Title":"Changed","member_ids":[%q]}`, user.ID),
} {
checkError(t, request(handler, http.MethodPost, "/api/v1/chats", body, user.ID),
http.StatusBadRequest, "invalid_request")
}
response := request(handler, http.MethodGet, "/api/v1/chats", "", user.ID)
var page service.Page[model.Chat]
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
t.Fatal(err)
}
if response.Code != http.StatusOK || len(page.Items) != 0 {
t.Fatalf("rejected chats were saved: %d %s", response.Code, response.Body.String())
}
})
created = request(handler, http.MethodPost, "/api/v1/chats",
fmt.Sprintf(`{"title":"Original","member_ids":[%q]}`, user.ID), user.ID)
if created.Code != http.StatusCreated {
t.Fatalf("valid chat: %d %s", created.Code, created.Body.String())
}
var chat model.Chat
if err := json.Unmarshal(created.Body.Bytes(), &chat); err != nil {
t.Fatal(err)
}
path := "/api/v1/chats/" + chat.ID + "/messages"
t.Run("message", func(t *testing.T) {
for _, body := range []string{
`{"text":"Original","Text":"Changed"}`,
`{"Text":"Changed","text":"Original"}`,
`{"text":"Original","TEXT":"Changed"}`,
`{"Text":"Changed"}`,
} {
checkError(t, request(handler, http.MethodPost, path, body, user.ID),
http.StatusBadRequest, "invalid_request")
}
response := request(handler, http.MethodGet, path, "", user.ID)
var page service.Page[model.Message]
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
t.Fatal(err)
}
if response.Code != http.StatusOK || len(page.Items) != 0 {
t.Fatalf("rejected messages were saved: %d %s", response.Code, response.Body.String())
}
response = request(handler, http.MethodPost, path, `{"text":"Original"}`, user.ID)
var message model.Message
if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil {
t.Fatal(err)
}
if response.Code != http.StatusCreated || message.Text != "Original" {
t.Fatalf("valid message: %d %s", response.Code, response.Body.String())
}
})
}
+102
View File
@@ -0,0 +1,102 @@
package httpapi
import (
"crypto/rand"
"encoding/hex"
"log"
"net/http"
"time"
)
var processInstanceID = rand.Text()
func withInstanceID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", processInstanceID)
next.ServeHTTP(w, r)
})
}
func withRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var randomBytes [16]byte
if _, err := rand.Read(randomBytes[:]); err != nil {
panic("cannot generate request ID")
}
requestID := hex.EncodeToString(randomBytes[:])
w.Header().Set("X-Request-Id", requestID)
next.ServeHTTP(w, r)
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(status int) {
if w.status != 0 {
return
}
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(body []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(body)
}
func (w *statusWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func withAccessLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
writer := &statusWriter{ResponseWriter: w}
defer func() {
if recovered := recover(); recovered != nil {
log.Printf(
"handler panic request_id=%s",
writer.Header().Get("X-Request-Id"),
)
if writer.status == 0 {
writeError(
writer,
http.StatusInternalServerError,
"internal_error",
"Internal server error",
)
} else {
panic(http.ErrAbortHandler)
}
}
status := writer.status
if status == 0 {
status = http.StatusOK
}
log.Printf(
"request_id=%s method=%s path=%q status=%d duration_ms=%d",
writer.Header().Get("X-Request-Id"),
r.Method,
r.URL.Path,
status,
time.Since(started).Milliseconds(),
)
}()
next.ServeHTTP(writer, r)
})
}
+80
View File
@@ -0,0 +1,80 @@
package httpapi
import (
"context"
"net/http"
"strings"
"sync/atomic"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (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)}
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/") {
token, err := bearerToken(r)
if err != nil {
sessionError(w, err, false)
return
}
user, err := sessions.CurrentUser(r.Context(), token)
if err != nil {
sessionError(w, err, false)
return
}
ctx := context.WithValue(r.Context(), userContextKey{}, user)
chats.chatRoutes(w, r.WithContext(ctx))
return
}
switch r.URL.Path {
case "/api/v1/auth/sessions":
loginSession(w, r, sessions)
case "/api/v1/auth/sessions/current":
currentSession(w, r, sessions, true)
case "/api/v1/users/me":
currentSession(w, r, sessions, false)
case "/health/live":
handleHealth(w, r)
case "/health/ready":
if !requireMethod(w, r, http.MethodGet) {
return
}
if err := db.Ping(r.Context()); err != nil {
writeAppError(w, err)
return
}
handleHealth(w, r)
case "/api/v1/users":
if !requireMethod(w, r, http.MethodPost) {
return
}
var body struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if !readJSON(w, r, &body, "username", "display_name", "password") {
return
}
user, err := registration.Register(r.Context(), body.Username, body.DisplayName, body.Password)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, user)
default:
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
}
})))), nil
}
+119
View File
@@ -0,0 +1,119 @@
package httpapi
import (
"net/http"
"strings"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type persistentAPI struct{ messenger *service.PersistentMessenger }
func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
actor := userFromContext(r.Context())
if r.URL.Path == "/api/v1/chats" {
switch r.Method {
case http.MethodPost:
var body createChatRequest
if !readJSON(w, r, &body, "title", "member_ids") {
return
}
chat, err := api.messenger.CreateChat(r.Context(),
actor.ID, body.Title, body.MemberIDs,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, chat)
case http.MethodGet:
limit, cursor, ok := pageParams(w, r)
if !ok {
return
}
page, err := api.messenger.ListChats(r.Context(), actor.ID, limit, cursor)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, page)
default:
requireMethod(w, r, "GET, POST")
}
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
parts := strings.Split(path, "/")
if len(parts) == 1 && parts[0] != "" {
if !requireMethod(w, r, http.MethodGet) {
return
}
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, chat)
return
}
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
return
}
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
switch r.Method {
case http.MethodPost:
var body createMessageRequest
if !readJSON(w, r, &body, "text") {
return
}
message, err := api.messenger.CreateMessage(r.Context(),
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"),
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, message)
case http.MethodGet:
limit, cursor, ok := pageParams(w, r)
if !ok {
return
}
page, err := api.messenger.ListMessages(r.Context(),
actor.ID, chat.ID, limit, cursor,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, page)
default:
requireMethod(w, r, "GET, POST")
}
}
+90
View File
@@ -0,0 +1,90 @@
package httpapi
import (
"net/http"
"strings"
"sync/atomic"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type API struct {
messenger *service.Messenger
}
func NewHandler(
messenger *service.Messenger,
stoppingFlags ...*atomic.Bool,
) http.Handler {
api := &API{messenger: messenger}
var stopping *atomic.Bool
if len(stoppingFlags) > 0 {
stopping = stoppingFlags[0]
}
if stopping == nil {
stopping = &atomic.Bool{}
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stopping.Load() && r.URL.Path != "/health/live" {
writeError(
w,
http.StatusServiceUnavailable,
"unavailable",
"Server is shutting down",
)
return
}
api.route(w, r)
})
return withInstanceID(withRequestID(withAccessLog(handler)))
}
func (api *API) route(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/chats" ||
strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
api.authenticate(http.HandlerFunc(api.chatRoutes)).ServeHTTP(w, r)
return
}
switch r.URL.Path {
case "/health/live", "/health/ready":
handleHealth(w, r)
case "/api/v1/users":
if !requireMethod(w, r, http.MethodPost) {
return
}
api.createUser(w, r)
case "/api/v1/users/me":
if !requireMethod(w, r, http.MethodGet) {
return
}
api.authenticate(http.HandlerFunc(api.currentUser)).ServeHTTP(w, r)
default:
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
}
}
func requireMethod(w http.ResponseWriter, r *http.Request, method string) bool {
if r.Method == method {
return true
}
w.Header().Set("Allow", method)
writeError(
w,
http.StatusMethodNotAllowed,
"invalid_request",
"Method not allowed",
)
return false
}
+87
View File
@@ -0,0 +1,87 @@
package httpapi
import (
"errors"
"io"
"net/http"
"strings"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
func sessionError(w http.ResponseWriter, err error, basic bool) {
if errors.Is(err, service.ErrUnauthorized) {
challenge := `Bearer realm="messenger"`
if basic {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
w.Header().Set("WWW-Authenticate", challenge)
writeError(w, http.StatusUnauthorized, "unauthorized", "Invalid credentials")
return
}
writeAppError(w, err)
}
func loginSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions) {
if !requireMethod(w, r, http.MethodPost) {
return
}
username, secret, ok := r.BasicAuth()
if !ok || len(r.Header.Values("Authorization")) != 1 {
sessionError(w, service.ErrUnauthorized, true)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
if err != nil || len(body) != 0 {
writeAppError(w, service.ErrInvalidRequest)
return
}
result, err := sessions.Login(r.Context(), username, secret)
if err != nil {
sessionError(w, err, true)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusCreated, result)
}
func bearerToken(r *http.Request) (string, error) {
if len(r.Header.Values("Authorization")) != 1 {
return "", service.ErrUnauthorized
}
fields := strings.Fields(r.Header.Get("Authorization"))
if len(fields) != 2 || !strings.EqualFold(fields[0], "Bearer") {
return "", service.ErrUnauthorized
}
return fields[1], nil
}
func currentSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions, logout bool) {
method := http.MethodGet
if logout {
method = http.MethodDelete
}
if !requireMethod(w, r, method) {
return
}
token, err := bearerToken(r)
if err != nil {
sessionError(w, err, false)
return
}
if logout {
if err := sessions.Logout(r.Context(), token); err != nil {
sessionError(w, err, false)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
user, err := sessions.CurrentUser(r.Context(), token)
if err != nil {
sessionError(w, err, false)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, user)
}
+29
View File
@@ -0,0 +1,29 @@
package httpapi
import "net/http"
type createUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
func (api *API) createUser(w http.ResponseWriter, r *http.Request) {
var body createUserRequest
if !readJSON(w, r, &body, "username", "display_name") {
return
}
user, err := api.messenger.RegisterUser(body.Username, body.DisplayName)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, user)
}
func (api *API) currentUser(w http.ResponseWriter, r *http.Request) {
user := userFromContext(r.Context())
writeJSON(w, http.StatusOK, user)
}
+171
View File
@@ -0,0 +1,171 @@
package httpapi_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
)
func newAPI() http.Handler {
return httpapi.NewHandler(
service.NewMessenger(store.NewMemoryStore()),
)
}
func request(
handler http.Handler,
method string,
path string,
body string,
userID string,
) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if userID != "" {
req.Header.Set("X-User-Id", userID)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, req)
return response
}
func checkError(
t *testing.T,
response *httptest.ResponseRecorder,
status int,
code string,
) {
t.Helper()
if response.Code != status {
t.Fatalf(
"status: got %d, want %d; body=%s",
response.Code, status, response.Body.String(),
)
}
var body struct {
Error struct {
Code string `json:"code"`
RequestID string `json:"request_id"`
} `json:"error"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode error response: %v", err)
}
if body.Error.Code != code {
t.Errorf("error code: got %q, want %q", body.Error.Code, code)
}
id := response.Header().Get("X-Request-Id")
if id == "" || body.Error.RequestID != id {
t.Error("missing or mismatched request ID")
}
}
func TestUserHTTPFlow(t *testing.T) {
handler := newAPI()
body := `{"username":"alice","display_name":"Алиса 👋"}`
created := request(handler, http.MethodPost, "/api/v1/users", body, "")
if created.Code != http.StatusCreated {
t.Fatalf("registration: %d %s", created.Code, created.Body.String())
}
if created.Header().Get("X-Request-Id") == "" {
t.Fatal("registration response has no request ID")
}
var user model.User
if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil {
t.Fatal(err)
}
if user.ID == "" || user.CreatedAt.IsZero() ||
user.Username != "alice" || user.DisplayName != "Алиса 👋" {
t.Fatalf("invalid user: %+v", user)
}
me := request(handler, http.MethodGet, "/api/v1/users/me", "", user.ID)
if me.Code != http.StatusOK {
t.Fatalf("current user: %d %s", me.Code, me.Body.String())
}
var current model.User
if err := json.Unmarshal(me.Body.Bytes(), &current); err != nil {
t.Fatal(err)
}
if current != user {
t.Fatalf("current user differs: %+v", current)
}
duplicate := request(handler, http.MethodPost, "/api/v1/users", body, "")
checkError(t, duplicate, http.StatusConflict, "conflict")
for _, id := range []string{
"",
"invalid",
"00000000-0000-4000-8000-000000000000",
} {
response := request(
handler, http.MethodGet, "/api/v1/users/me", "", id,
)
checkError(t, response, http.StatusUnauthorized, "unauthorized")
}
}
func TestRegistrationInvalidJSON(t *testing.T) {
cases := []string{
``,
`{`,
`null`,
`[]`,
`{}`,
`{"username":"alice"}`,
`{"username":null,"display_name":"Alice"}`,
`{"username":123,"display_name":"Alice"}`,
`{"username":"alice","display_name":"Alice","extra":true}`,
`{"username":"alice","display_name":"Alice"} {}`,
`{"username":"Alice","display_name":"Alice"}`,
`{"username":"alice","display_name":" "}`,
}
for _, body := range cases {
t.Run(body, func(t *testing.T) {
response := request(
newAPI(), http.MethodPost, "/api/v1/users", body, "",
)
checkError(t, response, http.StatusBadRequest, "invalid_request")
})
}
}
func TestRegistrationContentType(t *testing.T) {
req := httptest.NewRequest(
http.MethodPost,
"/api/v1/users",
strings.NewReader(`{"username":"alice","display_name":"Alice"}`),
)
req.Header.Set("Content-Type", "text/plain")
response := httptest.NewRecorder()
newAPI().ServeHTTP(response, req)
checkError(
t, response,
http.StatusUnsupportedMediaType, "unsupported_media_type",
)
}