chore(solution): port lab3 sources

This commit is contained in:
2026-11-20 03:05:34 +03:00
parent ec540a1a72
commit 083d0d80cc
44 changed files with 2745 additions and 1 deletions
+53
View File
@@ -0,0 +1,53 @@
package handler
import (
"encoding/base64"
"errors"
"net/http"
"strings"
"unicode/utf8"
"messenger/internal/domain"
)
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
username, password, ok := basicCredentials(r)
if !ok {
h.failLogin(w, r, domain.ErrUnauthorized)
return
}
session, err := h.auth.Login(r.Context(), username, password)
if err != nil {
h.failLogin(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toSessionResponse(session))
}
func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, domain.ErrUnauthorized) {
w.Header().Set(headerWWWAuthenticate, basicChallenge)
}
h.fail(w, r, err)
}
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
if err := h.auth.Logout(r.Context(), current(r).token); err != nil {
h.fail(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func basicCredentials(r *http.Request) (string, string, bool) {
encoded, ok := authCredentials(r, "Basic")
if !ok {
return "", "", false
}
raw, err := base64.StdEncoding.DecodeString(encoded)
if err != nil || !utf8.Valid(raw) {
return "", "", false
}
username, password, ok := strings.Cut(string(raw), ":")
return username, password, ok
}
+102
View File
@@ -0,0 +1,102 @@
package handler_test
import (
"net/http"
"strings"
"testing"
"time"
)
const (
deadDatabaseURL = "postgres://messenger:x@127.0.0.1:1/messenger?sslmode=disable"
deadRedisURL = "redis://127.0.0.1:1/0"
)
func TestSessionExpiry(t *testing.T) {
dbURL, redisURL := testURLs(t)
srv := newStack(t, dbURL, redisURL, 2*time.Second)
alice := createUser(t, srv, "alice")
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusOK {
t.Fatalf("fresh session: got %d, want 200", status)
}
time.Sleep(3 * time.Second)
resp := request(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, "")
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expired session: got %d, want 401", resp.StatusCode)
}
if got := resp.Header.Get("WWW-Authenticate"); !strings.HasPrefix(got, "Bearer") {
t.Errorf("WWW-Authenticate = %q, want Bearer challenge", got)
}
}
func TestLogout(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
resp := request(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, "")
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("logout: got %d, want 204", resp.StatusCode)
}
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusUnauthorized {
t.Errorf("revoked token on /users/me: got %d, want 401", status)
}
if status, _ := do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, ""); status != http.StatusUnauthorized {
t.Errorf("repeated logout: got %d, want 401", status)
}
}
func TestWrongPassword(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
for name, password := range map[string]string{"wrong password": "Wrong-password-123", "unknown user": alice.Password} {
username := alice.Username
if name == "unknown user" {
username = "nobody_" + alice.Username[:10]
}
resp := login(t, srv, username, password)
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("%s: got %d, want 401", name, resp.StatusCode)
}
if got := resp.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
t.Errorf("%s: WWW-Authenticate = %q", name, got)
}
}
}
func TestRedisUnavailable(t *testing.T) {
dbURL, _ := testURLs(t)
srv := newStack(t, dbURL, deadRedisURL, time.Hour)
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", "some-token-from-before-the-outage", ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
t.Errorf("bearer request: got %d %q, want 503 unavailable", status, errorCode(body))
}
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", "", ""); status != http.StatusUnauthorized {
t.Errorf("anonymous request: got %d, want 401", status)
}
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
t.Errorf("ready: got %d, want 503", status)
}
}
func TestDatabaseUnavailable(t *testing.T) {
dbURL, redisURL := testURLs(t)
healthy := newStack(t, dbURL, redisURL, time.Hour)
alice := createUser(t, healthy, "alice")
srv := newStack(t, deadDatabaseURL, redisURL, time.Hour)
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
t.Errorf("valid session: got %d %q, want 503 unavailable", status, errorCode(body))
}
if status, _ := do(t, srv, http.MethodPost, "/api/v1/users", "",
`{"username":"db_down_user","display_name":"X","password":"long-enough-pass"}`); status != http.StatusServiceUnavailable {
t.Errorf("register: got %d, want 503", status)
}
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
t.Errorf("ready: got %d, want 503", status)
}
}
+104
View File
@@ -0,0 +1,104 @@
package handler
import (
"net/http"
"strconv"
"uuid"
"github.com/go-chi/chi/v5"
"messenger/internal/domain"
"messenger/internal/service"
)
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
var req createChatRequest
if err := decodeJSON(w, r, &req); err != nil {
h.fail(w, r, err)
return
}
if req.Title == nil || req.MemberIDs == nil {
h.fail(w, r, badRequest("title and member_ids are required"))
return
}
memberIDs := make([]uuid.UUID, len(*req.MemberIDs))
for i, s := range *req.MemberIDs {
id, ok := parseUUID(s)
if !ok {
h.fail(w, r, badRequest("member_ids must contain UUIDs"))
return
}
memberIDs[i] = id
}
chat, err := h.chats.Create(r.Context(), actor(r), *req.Title, memberIDs)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toChatResponse(chat))
}
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
limit, cursor, err := pageParams(r)
if err != nil {
h.fail(w, r, err)
return
}
page, err := h.chats.List(r.Context(), actor(r), cursor, limit)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toPageResponse(page, toChatResponse))
}
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
chatID, err := chatIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
chat, err := h.chats.Get(r.Context(), actor(r), chatID)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toChatResponse(chat))
}
func chatIDParam(r *http.Request) (uuid.UUID, error) {
id, ok := parseUUID(chi.URLParam(r, "chat_id"))
if !ok {
return uuid.UUID{}, badRequest("chat_id must be a UUID")
}
return id, nil
}
func parseUUID(s string) (uuid.UUID, bool) {
if len(s) != 36 {
return uuid.UUID{}, false
}
id, err := uuid.Parse(s)
return id, err == nil
}
func pageParams(r *http.Request) (int, *domain.Cursor, error) {
q := r.URL.Query()
limit := service.DefaultLimit
if q.Has("limit") {
n, err := strconv.Atoi(q.Get("limit"))
if err != nil {
return 0, nil, badRequest("limit must be an integer")
}
limit = n
}
var cursor *domain.Cursor
if q.Has("cursor") {
c, ok := decodeCursor(q.Get("cursor"))
if !ok {
return 0, nil, badRequest("invalid cursor")
}
cursor = &c
}
return limit, cursor, nil
}
+34
View File
@@ -0,0 +1,34 @@
package handler
import (
"encoding/base64"
"strconv"
"strings"
"time"
"uuid"
"messenger/internal/domain"
)
func encodeCursor(c domain.Cursor) string {
raw := c.Scope.String() + "." + strconv.FormatInt(c.CreatedAt.UnixMicro(), 10) + "." + c.ID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func decodeCursor(s string) (domain.Cursor, bool) {
raw, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return domain.Cursor{}, false
}
parts := strings.Split(string(raw), ".")
if len(parts) != 3 {
return domain.Cursor{}, false
}
scope, err1 := uuid.Parse(parts[0])
micros, err2 := strconv.ParseInt(parts[1], 10, 64)
id, err3 := uuid.Parse(parts[2])
if err1 != nil || err2 != nil || err3 != nil {
return domain.Cursor{}, false
}
return domain.Cursor{Scope: scope, CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, true
}
+128
View File
@@ -0,0 +1,128 @@
package handler
import (
"time"
"messenger/internal/domain"
)
type createUserRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
type createChatRequest struct {
Title *string `json:"title"`
MemberIDs *[]string `json:"member_ids"`
}
type createMessageRequest struct {
Text *string `json:"text"`
}
type userResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
type chatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
type messageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
type pageResponse[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type sessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User userResponse `json:"user"`
}
type healthResponse struct {
Status string `json:"status"`
}
type errorBody struct {
Error errorDetails `json:"error"`
}
type errorDetails struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
const timeLayout = "2006-01-02T15:04:05.000000Z"
func formatTime(t time.Time) string { return t.UTC().Format(timeLayout) }
func toUserResponse(u domain.User) userResponse {
return userResponse{
ID: u.ID.String(),
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: formatTime(u.CreatedAt),
}
}
func toSessionResponse(s domain.Session) sessionResponse {
return sessionResponse{
Token: s.Token,
TokenType: "Bearer",
ExpiresAt: formatTime(s.ExpiresAt),
User: toUserResponse(s.User),
}
}
func toChatResponse(c domain.Chat) chatResponse {
members := make([]string, len(c.MemberIDs))
for i, id := range c.MemberIDs {
members[i] = id.String()
}
return chatResponse{
ID: c.ID.String(),
Title: c.Title,
MemberIDs: members,
CreatedAt: formatTime(c.CreatedAt),
}
}
func toMessageResponse(m domain.Message) messageResponse {
return messageResponse{
ID: m.ID.String(),
ChatID: m.ChatID.String(),
SenderID: m.SenderID.String(),
Text: m.Text,
CreatedAt: formatTime(m.CreatedAt),
}
}
func toPageResponse[D, R any](p domain.Page[D], conv func(D) R) pageResponse[R] {
items := make([]R, len(p.Items))
for i, it := range p.Items {
items[i] = conv(it)
}
resp := pageResponse[R]{Items: items}
if p.Next != nil {
s := encodeCursor(*p.Next)
resp.NextCursor = &s
}
return resp
}
+55
View File
@@ -0,0 +1,55 @@
package handler
import (
"errors"
"net/http"
"messenger/internal/domain"
)
type apiError struct {
status int
code string
message string
}
func (e *apiError) Error() string { return e.message }
func badRequest(msg string) *apiError {
return &apiError{http.StatusBadRequest, "invalid_request", msg}
}
func writeError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, errorBody{Error: errorDetails{
Code: code,
Message: message,
RequestID: w.Header().Get(headerRequestID),
}})
}
func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
var ae *apiError
switch {
case errors.As(err, &ae):
writeError(w, ae.status, ae.code, ae.message)
case errors.Is(err, domain.ErrInvalidInput):
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
case errors.Is(err, domain.ErrUnauthorized):
if w.Header().Get(headerWWWAuthenticate) == "" {
w.Header().Set(headerWWWAuthenticate, bearerChallenge)
}
writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required")
case errors.Is(err, domain.ErrNotFound):
writeError(w, http.StatusNotFound, "not_found", "resource not found")
case errors.Is(err, domain.ErrConflict):
writeError(w, http.StatusConflict, "conflict", err.Error())
case errors.Is(err, domain.ErrUnavailable):
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable")
default:
h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
writeError(w, http.StatusInternalServerError, "internal_error", "internal server error")
}
}
+39
View File
@@ -0,0 +1,39 @@
package handler
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"messenger/internal/service"
)
type Pinger func(ctx context.Context) error
type Handler struct {
users *service.UserService
auth *service.AuthService
chats *service.ChatService
messages *service.MessageService
deps []Pinger
log *slog.Logger
draining atomic.Bool
}
func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService,
messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler {
return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log}
}
func (h *Handler) StartDraining() {
h.draining.Store(true)
}
func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) {
writeError(w, http.StatusNotFound, "not_found", "resource not found")
}
func (h *Handler) MethodNotAllowed(w http.ResponseWriter, _ *http.Request) {
writeError(w, http.StatusMethodNotAllowed, "invalid_request", "method not allowed")
}
+324
View File
@@ -0,0 +1,324 @@
package handler_test
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
"uuid"
"messenger/internal/handler"
"messenger/internal/repository/postgres"
"messenger/internal/repository/redis"
"messenger/internal/router"
"messenger/internal/service"
)
func testURLs(t *testing.T) (string, string) {
t.Helper()
dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL")
if dbURL == "" || redisURL == "" {
t.Skip("TEST_DATABASE_URL and TEST_REDIS_URL are required")
}
return dbURL, redisURL
}
func newServer(t *testing.T) *httptest.Server {
t.Helper()
dbURL, redisURL := testURLs(t)
return newStack(t, dbURL, redisURL, time.Hour)
}
func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest.Server {
t.Helper()
pool, err := postgres.NewPool(context.Background(), dbURL)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
store := postgres.New(pool)
client, err := redis.NewClient(redisURL)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { client.Close() })
sessions := redis.NewSessionStore(client)
users := service.NewUserService(store)
auth := service.NewAuthService(store, sessions, ttl)
chats := service.NewChatService(store)
messages := service.NewMessageService(chats, store)
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
srv := httptest.NewServer(router.New(h, "test"))
t.Cleanup(srv.Close)
return srv
}
type testUser struct {
ID string
Username string
Password string
Token string
}
func request(t *testing.T, srv *httptest.Server, method, path, token, body string) *http.Response {
t.Helper()
req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
req.Header.Set("Idempotency-Key", uuid.New().String())
}
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
func do(t *testing.T, srv *httptest.Server, method, path, token, body string) (int, map[string]any) {
t.Helper()
resp := request(t, srv, method, path, token, body)
defer resp.Body.Close()
var out map[string]any
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
t.Fatalf("%s %s: invalid JSON response: %v", method, path, err)
}
return resp.StatusCode, out
}
func errorCode(body map[string]any) string {
e, _ := body["error"].(map[string]any)
code, _ := e["code"].(string)
return code
}
func basic(username, password string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
}
func login(t *testing.T, srv *httptest.Server, username, password string) *http.Response {
t.Helper()
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", basic(username, password))
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
func createUser(t *testing.T, srv *httptest.Server, label string) testUser {
t.Helper()
u := testUser{
Username: label + "_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12],
Password: "Test-password-" + label,
}
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":"Test","password":%q}`, u.Username, u.Password))
if status != http.StatusCreated {
t.Fatalf("create user %s: status %d", u.Username, status)
}
u.ID = body["id"].(string)
resp := login(t, srv, u.Username, u.Password)
defer resp.Body.Close()
var session map[string]any
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil || resp.StatusCode != http.StatusCreated {
t.Fatalf("login %s: status %d", u.Username, resp.StatusCode)
}
u.Token = session["token"].(string)
return u
}
func createChat(t *testing.T, srv *httptest.Server, owner testUser, members ...testUser) string {
t.Helper()
ids := make([]string, len(members))
for i, m := range members {
ids[i] = m.ID
}
raw, _ := json.Marshal(ids)
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner.Token,
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, raw))
if status != http.StatusCreated {
t.Fatalf("create chat: status %d", status)
}
return body["id"].(string)
}
func TestInvalidJSON(t *testing.T) {
srv := newServer(t)
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x","password":"long-enough-pass"}`} {
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body)
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp))
}
}
}
func TestForeignChat(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
bob := createUser(t, srv, "bob")
eve := createUser(t, srv, "eve")
chat := createChat(t, srv, alice, alice, bob)
cases := []struct{ method, path, body string }{
{http.MethodGet, "/api/v1/chats/" + chat, ""},
{http.MethodGet, "/api/v1/chats/" + chat + "/messages", ""},
{http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`},
}
for _, c := range cases {
status, resp := do(t, srv, c.method, c.path, eve.Token, c.body)
if status != http.StatusNotFound || errorCode(resp) != "not_found" {
t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status)
}
}
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve.Token, "")
if status != http.StatusOK || len(resp["items"].([]any)) != 0 {
t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"])
}
}
func TestEmptyMessage(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
chat := createChat(t, srv, alice, alice)
for _, text := range []string{"", " ", "\n\t"} {
body, _ := json.Marshal(map[string]string{"text": text})
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, string(body))
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
t.Errorf("text %q: got %d, want 400", text, status)
}
}
}
func TestDuplicateUsername(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":"Other","password":"another-password"}`, alice.Username))
if status != http.StatusConflict || errorCode(resp) != "conflict" {
t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp))
}
}
func TestPaginationMultiplePages(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
chat := createChat(t, srv, alice, alice)
const total, limit = 7, 3
for i := range total {
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, fmt.Sprintf(`{"text":"msg %d"}`, i))
if status != http.StatusCreated {
t.Fatalf("send message %d: status %d", i, status)
}
}
seen := map[string]bool{}
pages := 0
prevCreatedAt := ""
cursor := ""
for {
path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit)
if cursor != "" {
path += "&cursor=" + cursor
}
status, resp := do(t, srv, http.MethodGet, path, alice.Token, "")
if status != http.StatusOK {
t.Fatalf("page %d: status %d", pages+1, status)
}
pages++
for _, it := range resp["items"].([]any) {
m := it.(map[string]any)
id, createdAt := m["id"].(string), m["created_at"].(string)
if seen[id] {
t.Errorf("message %s returned twice", id)
}
if createdAt < prevCreatedAt {
t.Errorf("messages out of order: %s after %s", createdAt, prevCreatedAt)
}
seen[id] = true
prevCreatedAt = createdAt
}
next, ok := resp["next_cursor"].(string)
if !ok {
break
}
cursor = next
}
if len(seen) != total {
t.Errorf("got %d messages, want %d", len(seen), total)
}
if want := (total + limit - 1) / limit; pages != want {
t.Errorf("got %d pages, want %d", pages, want)
}
}
func TestConcurrentMessages(t *testing.T) {
srv := newServer(t)
const clients, perClient = 10, 10
users := make([]testUser, clients)
for i := range users {
users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i))
}
chat := createChat(t, srv, users[0], users...)
var wg sync.WaitGroup
errs := make(chan error, clients*perClient)
for c, user := range users {
wg.Go(func() {
for i := range perClient {
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user.Token,
fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i))
if status != http.StatusCreated {
errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status)
}
}
})
}
wg.Wait()
close(errs)
for err := range errs {
t.Error(err)
}
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0].Token, "")
if status != http.StatusOK {
t.Fatalf("read history: status %d", status)
}
items := resp["items"].([]any)
ids := map[string]bool{}
for _, it := range items {
ids[it.(map[string]any)["id"].(string)] = true
}
if len(items) != clients*perClient || len(ids) != clients*perClient {
t.Errorf("got %d messages (%d unique), want %d", len(items), len(ids), clients*perClient)
}
if resp["next_cursor"] != nil {
t.Errorf("next_cursor = %v, want null", resp["next_cursor"])
}
}
+32
View File
@@ -0,0 +1,32 @@
package handler
import (
"context"
"fmt"
"net/http"
"time"
"messenger/internal/domain"
)
const readyTimeout = time.Second
func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
}
func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
if h.draining.Load() {
h.fail(w, r, fmt.Errorf("%w: draining", domain.ErrUnavailable))
return
}
ctx, cancel := context.WithTimeout(r.Context(), readyTimeout)
defer cancel()
for _, dep := range h.deps {
if err := dep(ctx); err != nil {
h.fail(w, r, fmt.Errorf("%w: %v", domain.ErrUnavailable, err))
return
}
}
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
}
+86
View File
@@ -0,0 +1,86 @@
package handler
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"reflect"
"strings"
"unicode/utf8"
)
const maxBodyBytes = 1 << 20
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mt != "application/json" {
return &apiError{http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json"}
}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, "payload_too_large", "request body is too large"}
}
return badRequest("failed to read request body")
}
if !utf8.Valid(raw) {
return badRequest("request body must be valid UTF-8")
}
if err := checkKeys(raw, dst); err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return badRequest("request body must be a valid JSON object matching the schema")
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return badRequest("request body must contain a single JSON object")
}
return nil
}
func checkKeys(raw []byte, dst any) error {
allowed := jsonFields(dst)
dec := json.NewDecoder(bytes.NewReader(raw))
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
return badRequest("request body must be a JSON object")
}
for dec.More() {
tok, err := dec.Token()
if err != nil {
return badRequest("request body must be a valid JSON object matching the schema")
}
key, _ := tok.(string)
if !allowed[key] {
return badRequest("request body contains unknown field")
}
var value json.RawMessage
if err := dec.Decode(&value); err != nil {
return badRequest("request body must be a valid JSON object matching the schema")
}
}
return nil
}
func jsonFields(dst any) map[string]bool {
t := reflect.TypeOf(dst).Elem()
fields := make(map[string]bool, t.NumField())
for i := range t.NumField() {
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
fields[name] = true
}
return fields
}
+57
View File
@@ -0,0 +1,57 @@
package handler
import (
"net/http"
"regexp"
)
const headerIdempotencyKey = "Idempotency-Key"
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
chatID, err := chatIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
key := r.Header.Get(headerIdempotencyKey)
if !idempotencyKeyRe.MatchString(key) {
h.fail(w, r, badRequest("Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}"))
return
}
var req createMessageRequest
if err := decodeJSON(w, r, &req); err != nil {
h.fail(w, r, err)
return
}
if req.Text == nil {
h.fail(w, r, badRequest("text is required"))
return
}
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toMessageResponse(msg))
}
func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) {
chatID, err := chatIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
limit, cursor, err := pageParams(r)
if err != nil {
h.fail(w, r, err)
return
}
page, err := h.messages.History(r.Context(), actor(r), chatID, cursor, limit)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toPageResponse(page, toMessageResponse))
}
+122
View File
@@ -0,0 +1,122 @@
package handler
import (
"context"
"errors"
"net/http"
"runtime/debug"
"strings"
"time"
"uuid"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"messenger/internal/domain"
)
const (
headerRequestID = "X-Request-Id"
headerInstanceID = "X-Instance-Id"
headerWWWAuthenticate = "WWW-Authenticate"
bearerChallenge = `Bearer realm="messenger"`
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
)
func InstanceID(id string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headerInstanceID, id)
next.ServeHTTP(w, r)
})
}
}
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headerRequestID, uuid.New().String())
next.ServeHTTP(w, r)
})
}
func (h *Handler) AccessLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
route := r.URL.Path
if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" {
route = rc.RoutePattern()
}
h.log.Info("request",
"request_id", w.Header().Get(headerRequestID),
"method", r.Method,
"route", route,
"status", ww.Status(),
"duration_ms", time.Since(start).Milliseconds(),
)
})
}
func (h *Handler) Recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
rec := recover()
if rec == nil {
return
}
if rec == http.ErrAbortHandler {
panic(rec)
}
h.log.Error("panic", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "panic", rec, "stack", string(debug.Stack()))
writeError(w, http.StatusInternalServerError, "internal_error", "internal server error")
}()
next.ServeHTTP(w, r)
})
}
type ctxKey struct{}
type principal struct {
user domain.User
token string
}
func (h *Handler) Authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := authCredentials(r, "Bearer")
if !ok || token == "" {
h.fail(w, r, domain.ErrUnauthorized)
return
}
user, err := h.auth.Authenticate(r.Context(), token)
if err != nil {
h.fail(w, r, err)
return
}
ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token})
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func authCredentials(r *http.Request, scheme string) (string, bool) {
gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ")
if !ok || !strings.EqualFold(gotScheme, scheme) {
return "", false
}
return credentials, true
}
func current(r *http.Request) principal {
p, ok := r.Context().Value(ctxKey{}).(principal)
if !ok {
panic(errors.New("handler: actor requested on unauthenticated route"))
}
return p
}
func actor(r *http.Request) domain.User {
return current(r).user
}
+25
View File
@@ -0,0 +1,25 @@
package handler
import "net/http"
func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) {
var req createUserRequest
if err := decodeJSON(w, r, &req); err != nil {
h.fail(w, r, err)
return
}
if req.Username == nil || req.DisplayName == nil || req.Password == nil {
h.fail(w, r, badRequest("username, display_name and password are required strings"))
return
}
user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName, *req.Password)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toUserResponse(user))
}
func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, toUserResponse(actor(r)))
}