Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
// Package app is the composition root: it builds every module with its
|
||||
// in-memory stores and mounts them on one HTTP engine. Both the server
|
||||
// binary and the integration tests start from here.
|
||||
package app
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/chat"
|
||||
chatstore "messenger/internal/chat/store"
|
||||
"messenger/internal/health"
|
||||
"messenger/internal/platform/httpx"
|
||||
"messenger/internal/user"
|
||||
userstore "messenger/internal/user/store"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
Engine *gin.Engine
|
||||
Health *health.Handler
|
||||
}
|
||||
|
||||
func New(log *slog.Logger, maxBodyBytes int64) *App {
|
||||
users := user.NewService(userstore.NewInMemUsers())
|
||||
chats := chat.NewService(chatstore.NewInMemChats(), chatstore.NewInMemMessages(), users)
|
||||
|
||||
engine := httpx.NewEngine(log, maxBodyBytes)
|
||||
probes := health.New()
|
||||
probes.Register(engine)
|
||||
|
||||
public := engine.Group("/api/v1")
|
||||
protected := public.Group("", auth.RequireUser(users))
|
||||
user.NewHandler(users).Register(public, protected)
|
||||
chat.NewHandler(chats).Register(protected)
|
||||
|
||||
return &App{Engine: engine, Health: probes}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/app"
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/pagination"
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
// errorBody mirrors the contract error envelope.
|
||||
type errorBody struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
status int
|
||||
requestID string
|
||||
raw []byte
|
||||
}
|
||||
|
||||
// tester drives the assembled application in-process.
|
||||
type tester struct {
|
||||
t *testing.T
|
||||
a *app.App
|
||||
}
|
||||
|
||||
func newTester(t *testing.T) *tester {
|
||||
t.Helper()
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
return &tester{t: t, a: app.New(log, 64*1024)}
|
||||
}
|
||||
|
||||
// do sends one request. A string body is sent verbatim, anything else is
|
||||
// JSON-encoded; both get a JSON content type. Every response is checked for
|
||||
// X-Request-Id, and error bodies for the contract envelope.
|
||||
func (ts *tester) do(method, path, actor string, body any, headers map[string]string) response {
|
||||
ts.t.Helper()
|
||||
req := httptest.NewRequest(method, path, encode(ts.t, body))
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actor != "" {
|
||||
req.Header.Set("X-User-Id", actor)
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
ts.a.Engine.ServeHTTP(rec, req)
|
||||
|
||||
res := response{status: rec.Code, requestID: rec.Header().Get("X-Request-Id"), raw: rec.Body.Bytes()}
|
||||
if res.requestID == "" {
|
||||
ts.t.Fatalf("%s %s: missing X-Request-Id", method, path)
|
||||
}
|
||||
if res.status >= 400 {
|
||||
var eb errorBody
|
||||
if err := json.Unmarshal(res.raw, &eb); err != nil {
|
||||
ts.t.Fatalf("%s %s: error body is not the contract envelope: %v: %s", method, path, err, res.raw)
|
||||
}
|
||||
if eb.Error.RequestID != res.requestID || eb.Error.Code == "" || eb.Error.Message == "" {
|
||||
ts.t.Fatalf("%s %s: bad error envelope: %s", method, path, res.raw)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func encode(t *testing.T, body any) io.Reader {
|
||||
t.Helper()
|
||||
switch b := body.(type) {
|
||||
case nil:
|
||||
return nil
|
||||
case string:
|
||||
return strings.NewReader(b)
|
||||
default:
|
||||
raw, err := json.Marshal(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return bytes.NewReader(raw)
|
||||
}
|
||||
}
|
||||
|
||||
// expect asserts the status and, for errors, the contract code.
|
||||
func (ts *tester) expect(res response, status int, code string) {
|
||||
ts.t.Helper()
|
||||
if res.status != status {
|
||||
ts.t.Fatalf("status = %d, want %d; body %s", res.status, status, res.raw)
|
||||
}
|
||||
if code != "" {
|
||||
var eb errorBody
|
||||
_ = json.Unmarshal(res.raw, &eb)
|
||||
if eb.Error.Code != code {
|
||||
ts.t.Fatalf("code = %q, want %q; body %s", eb.Error.Code, code, res.raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// decode parses a success body into a typed DTO and rejects unknown fields,
|
||||
// which enforces the additionalProperties=false rule of the contract.
|
||||
func decode[T any](t *testing.T, res response) T {
|
||||
t.Helper()
|
||||
var out T
|
||||
dec := json.NewDecoder(bytes.NewReader(res.raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&out); err != nil {
|
||||
t.Fatalf("body does not match %T: %v: %s", out, err, res.raw)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (ts *tester) user(username, display string) user.Response {
|
||||
ts.t.Helper()
|
||||
res := ts.do(http.MethodPost, "/api/v1/users", "", map[string]string{"username": username, "display_name": display}, nil)
|
||||
ts.expect(res, http.StatusCreated, "")
|
||||
return decode[user.Response](ts.t, res)
|
||||
}
|
||||
|
||||
func (ts *tester) chat(actor, title string, members ...string) chat.ChatResponse {
|
||||
ts.t.Helper()
|
||||
res := ts.do(http.MethodPost, "/api/v1/chats", actor, map[string]any{"title": title, "member_ids": members}, nil)
|
||||
ts.expect(res, http.StatusCreated, "")
|
||||
return decode[chat.ChatResponse](ts.t, res)
|
||||
}
|
||||
|
||||
func (ts *tester) message(actor, chatID, text string) chat.MessageResponse {
|
||||
ts.t.Helper()
|
||||
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor, map[string]string{"text": text}, nil)
|
||||
ts.expect(res, http.StatusCreated, "")
|
||||
return decode[chat.MessageResponse](ts.t, res)
|
||||
}
|
||||
|
||||
func (ts *tester) chats(actor, query string) pagination.PageResponse[chat.ChatResponse] {
|
||||
ts.t.Helper()
|
||||
res := ts.do(http.MethodGet, "/api/v1/chats"+query, actor, nil, nil)
|
||||
ts.expect(res, http.StatusOK, "")
|
||||
return decode[pagination.PageResponse[chat.ChatResponse]](ts.t, res)
|
||||
}
|
||||
|
||||
func (ts *tester) history(actor, chatID, query string) pagination.PageResponse[chat.MessageResponse] {
|
||||
ts.t.Helper()
|
||||
res := ts.do(http.MethodGet, "/api/v1/chats/"+chatID+"/messages"+query, actor, nil, nil)
|
||||
ts.expect(res, http.StatusOK, "")
|
||||
return decode[pagination.PageResponse[chat.MessageResponse]](ts.t, res)
|
||||
}
|
||||
|
||||
func cursorQuery(limit int, cursor *string) string {
|
||||
q := fmt.Sprintf("?limit=%d", limit)
|
||||
if cursor != nil {
|
||||
q += "&cursor=" + url.QueryEscape(*cursor)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func TestHealthEndpoints(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
for _, path := range []string{"/health/live", "/health/ready"} {
|
||||
res := ts.do(http.MethodGet, path, "", nil, nil)
|
||||
ts.expect(res, http.StatusOK, "")
|
||||
if strings.TrimSpace(string(res.raw)) != `{"status":"ok"}` {
|
||||
t.Fatalf("%s body = %s", path, res.raw)
|
||||
}
|
||||
}
|
||||
ts.a.Health.SetReady(false)
|
||||
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
|
||||
ts.expect(ts.do(http.MethodGet, "/health/live", "", nil, nil), http.StatusOK, "")
|
||||
}
|
||||
|
||||
func TestRegisterUserShapeAndConflicts(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice := ts.user("alice", "Алиса")
|
||||
if alice.ID == "" || alice.Username != "alice" || alice.DisplayName != "Алиса" {
|
||||
t.Fatalf("user = %+v", alice)
|
||||
}
|
||||
if !strings.HasSuffix(alice.CreatedAt, "Z") || len(alice.CreatedAt) != len("2026-09-01T12:00:00.000Z") {
|
||||
t.Fatalf("created_at = %q", alice.CreatedAt)
|
||||
}
|
||||
post := func(body any) response { return ts.do(http.MethodPost, "/api/v1/users", "", body, nil) }
|
||||
ts.expect(post(map[string]string{"username": "alice", "display_name": "Other"}), http.StatusConflict, "conflict")
|
||||
ts.expect(post(map[string]string{"username": "Alice", "display_name": "x"}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(map[string]string{"username": "bob", "display_name": " "}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(map[string]any{"username": "bob", "display_name": "x", "password": "no"}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(`{"username":`), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(map[string]any{"username": 5, "display_name": "x"}), http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestCurrentUserRequiresIdentity(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice := ts.user("alice", "Алиса")
|
||||
me := func(actor string) response { return ts.do(http.MethodGet, "/api/v1/users/me", actor, nil, nil) }
|
||||
ts.expect(me(""), http.StatusUnauthorized, "unauthorized")
|
||||
ts.expect(me("garbage"), http.StatusUnauthorized, "unauthorized")
|
||||
ts.expect(me("11111111-1111-4111-8111-111111111111"), http.StatusUnauthorized, "unauthorized")
|
||||
res := me(alice.ID)
|
||||
ts.expect(res, http.StatusOK, "")
|
||||
if got := decode[user.Response](t, res); got != alice {
|
||||
t.Fatalf("me = %+v, want %+v", got, alice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCreationRules(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice, bob := ts.user("alice", "A"), ts.user("bob", "B")
|
||||
created := ts.chat(alice.ID, "Проект по ВНП", alice.ID, bob.ID)
|
||||
if created.Title != "Проект по ВНП" || len(created.MemberIDs) != 2 || created.MemberIDs[0] != alice.ID || created.MemberIDs[1] != bob.ID {
|
||||
t.Fatalf("chat = %+v", created)
|
||||
}
|
||||
unknown := "22222222-2222-4222-8222-222222222222"
|
||||
invalid := map[string]any{
|
||||
"creator missing": map[string]any{"title": "t", "member_ids": []string{bob.ID}},
|
||||
"duplicate": map[string]any{"title": "t", "member_ids": []string{alice.ID, alice.ID}},
|
||||
"unknown member": map[string]any{"title": "t", "member_ids": []string{alice.ID, unknown}},
|
||||
"malformed uuid": map[string]any{"title": "t", "member_ids": []string{alice.ID, "not-a-uuid"}},
|
||||
"empty members": map[string]any{"title": "t", "member_ids": []string{}},
|
||||
"blank title": map[string]any{"title": "", "member_ids": []string{alice.ID}},
|
||||
"long title": map[string]any{"title": strings.Repeat("я", 101), "member_ids": []string{alice.ID}},
|
||||
"missing members": map[string]any{"title": "t"},
|
||||
"extra field": map[string]any{"title": "t", "member_ids": []string{alice.ID}, "owner": alice.ID},
|
||||
}
|
||||
for name, body := range invalid {
|
||||
res := ts.do(http.MethodPost, "/api/v1/chats", alice.ID, body, nil)
|
||||
if res.status != http.StatusBadRequest {
|
||||
t.Errorf("%s: status = %d, want 400; body %s", name, res.status, res.raw)
|
||||
}
|
||||
}
|
||||
ts.expect(ts.do(http.MethodPost, "/api/v1/chats", "", map[string]any{"title": "t", "member_ids": []string{alice.ID}}, nil), http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
|
||||
func TestChatVisibilityAndListing(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
|
||||
created := ts.chat(alice.ID, "Контрактный тест", alice.ID, bob.ID)
|
||||
path := "/api/v1/chats/" + created.ID
|
||||
|
||||
res := ts.do(http.MethodGet, path, bob.ID, nil, nil)
|
||||
ts.expect(res, http.StatusOK, "")
|
||||
if got := decode[chat.ChatResponse](t, res); got.ID != created.ID || len(got.MemberIDs) != 2 {
|
||||
t.Fatalf("GET chat = %+v", got)
|
||||
}
|
||||
ts.expect(ts.do(http.MethodGet, path, eve.ID, nil, nil), http.StatusNotFound, "not_found")
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/33333333-3333-4333-8333-333333333333", alice.ID, nil, nil), http.StatusNotFound, "not_found")
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/not-a-uuid", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(ts.do(http.MethodGet, path, "", nil, nil), http.StatusUnauthorized, "unauthorized")
|
||||
|
||||
listed := ts.chats(bob.ID, "?limit=100")
|
||||
if len(listed.Items) != 1 || listed.Items[0].ID != created.ID || listed.NextCursor != nil {
|
||||
t.Fatalf("bob list = %+v", listed)
|
||||
}
|
||||
hidden := ts.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil)
|
||||
ts.expect(hidden, http.StatusOK, "")
|
||||
if !strings.Contains(string(hidden.raw), `"items":[]`) || !strings.Contains(string(hidden.raw), `"next_cursor":null`) {
|
||||
t.Fatalf("empty list must serialize items as [] and next_cursor as null: %s", hidden.raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatListPagination(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice := ts.user("alice", "A")
|
||||
var expected []string
|
||||
for i := 0; i < 5; i++ {
|
||||
expected = append(expected, ts.chat(alice.ID, fmt.Sprintf("chat %d", i), alice.ID).ID)
|
||||
}
|
||||
var walked []string
|
||||
var cursor *string
|
||||
for pages := 0; pages < 10; pages++ {
|
||||
page := ts.chats(alice.ID, cursorQuery(2, cursor))
|
||||
for _, c := range page.Items {
|
||||
walked = append(walked, c.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = page.NextCursor
|
||||
}
|
||||
if strings.Join(walked, ",") != strings.Join(expected, ",") {
|
||||
t.Fatalf("walked %v, want %v", walked, expected)
|
||||
}
|
||||
|
||||
bob := ts.user("bob", "B")
|
||||
foreign := ts.chats(alice.ID, "?limit=1").NextCursor
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/chats"+cursorQuery(50, foreign), bob.ID, nil, nil), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?cursor=", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?limit=abc", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestMessagesEndToEnd(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
|
||||
room := ts.chat(alice.ID, "Контрактный тест", alice.ID, bob.ID)
|
||||
path := "/api/v1/chats/" + room.ID + "/messages"
|
||||
|
||||
first := ts.message(alice.ID, room.ID, "Привет, мир 👋")
|
||||
second := ts.message(bob.ID, room.ID, "Сообщение Боба")
|
||||
if first.SenderID != alice.ID || second.SenderID != bob.ID {
|
||||
t.Fatalf("sender must come from X-User-Id: %+v %+v", first, second)
|
||||
}
|
||||
if first.ChatID != room.ID || first.Text != "Привет, мир 👋" {
|
||||
t.Fatalf("message = %+v", first)
|
||||
}
|
||||
|
||||
page1 := ts.history(bob.ID, room.ID, "?limit=1")
|
||||
if len(page1.Items) != 1 || page1.NextCursor == nil || page1.Items[0] != first {
|
||||
t.Fatalf("page1 = %+v", page1)
|
||||
}
|
||||
page2 := ts.history(alice.ID, room.ID, cursorQuery(1, page1.NextCursor))
|
||||
if len(page2.Items) != 1 || page2.NextCursor != nil || page2.Items[0] != second {
|
||||
t.Fatalf("page2 = %+v", page2)
|
||||
}
|
||||
|
||||
post := func(actor string, body any) response { return ts.do(http.MethodPost, path, actor, body, nil) }
|
||||
ts.expect(post(alice.ID, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(alice.ID, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(alice.ID, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(alice.ID, map[string]string{"text": "x", "sender_id": bob.ID}), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(alice.ID, `{"text":`), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(post(eve.ID, map[string]string{"text": "чужое"}), http.StatusNotFound, "not_found")
|
||||
ts.expect(post(eve.ID, map[string]string{"text": ""}), http.StatusNotFound, "not_found")
|
||||
ts.expect(post("", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
|
||||
ts.expect(post(alice.ID, map[string]string{"text": strings.Repeat("я", 4000)}), http.StatusCreated, "")
|
||||
|
||||
get := func(actor, query string) response { return ts.do(http.MethodGet, path+query, actor, nil, nil) }
|
||||
ts.expect(get(eve.ID, ""), http.StatusNotFound, "not_found")
|
||||
ts.expect(get(alice.ID, "?limit=0"), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(get(alice.ID, "?limit=101"), http.StatusBadRequest, "invalid_request")
|
||||
ts.expect(get(alice.ID, "?cursor=garbage"), http.StatusBadRequest, "invalid_request")
|
||||
|
||||
other := ts.chat(alice.ID, "другой", alice.ID)
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+other.ID+"/messages"+cursorQuery(50, page1.NextCursor), alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestMessageHistoryWalkAcrossPages(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
alice := ts.user("alice", "A")
|
||||
room := ts.chat(alice.ID, "t", alice.ID)
|
||||
var expected []string
|
||||
for i := 0; i < 23; i++ {
|
||||
expected = append(expected, ts.message(alice.ID, room.ID, fmt.Sprintf("m%d", i)).ID)
|
||||
}
|
||||
var walked []string
|
||||
var cursor *string
|
||||
for {
|
||||
page := ts.history(alice.ID, room.ID, cursorQuery(5, cursor))
|
||||
for _, m := range page.Items {
|
||||
walked = append(walked, m.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = page.NextCursor
|
||||
}
|
||||
if strings.Join(walked, ",") != strings.Join(expected, ",") {
|
||||
t.Fatalf("walk mismatch:\n%v\n%v", walked, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentSendsProduceExactlyUniqueMessages(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
const clients, perClient = 10, 10
|
||||
members := make([]string, 0, clients)
|
||||
for i := 0; i < clients; i++ {
|
||||
members = append(members, ts.user(fmt.Sprintf("client_%d", i), "C").ID)
|
||||
}
|
||||
room := ts.chat(members[0], "нагрузка", members...)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for n, actor := range members {
|
||||
wg.Add(1)
|
||||
go func(n int, actor string) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perClient; i++ {
|
||||
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", actor, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, nil)
|
||||
if res.status != http.StatusCreated {
|
||||
t.Errorf("client %d: status %d body %s", n, res.status, res.raw)
|
||||
}
|
||||
}
|
||||
}(n, actor)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
page := ts.history(members[0], room.ID, "?limit=100")
|
||||
if len(page.Items) != clients*perClient || page.NextCursor != nil {
|
||||
t.Fatalf("got %d messages, next=%v; want %d and null", len(page.Items), page.NextCursor, clients*perClient)
|
||||
}
|
||||
ids := make([]string, 0, len(page.Items))
|
||||
unique := make(map[string]struct{}, len(page.Items))
|
||||
for _, m := range page.Items {
|
||||
ids = append(ids, m.ID)
|
||||
unique[m.ID] = struct{}{}
|
||||
}
|
||||
if !sort.StringsAreSorted(ids) {
|
||||
t.Fatal("history is not ordered by id")
|
||||
}
|
||||
if len(unique) != clients*perClient {
|
||||
t.Fatalf("%d unique ids, want %d", len(unique), clients*perClient)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownRouteAndMethodAreContractErrors(t *testing.T) {
|
||||
ts := newTester(t)
|
||||
ts.expect(ts.do(http.MethodGet, "/api/v1/nothing", "", nil, nil), http.StatusNotFound, "not_found")
|
||||
ts.expect(ts.do(http.MethodDelete, "/api/v1/users", "", nil, nil), http.StatusMethodNotAllowed, "invalid_request")
|
||||
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", "{}", map[string]string{"Content-Type": "text/plain"}), http.StatusUnsupportedMediaType, "unsupported_media_type")
|
||||
big := map[string]string{"username": "big", "display_name": strings.Repeat("x", 70*1024)}
|
||||
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", big, nil), http.StatusRequestEntityTooLarge, "payload_too_large")
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Package auth identifies the caller. In this lab the identity is the
|
||||
// X-User-Id header naming a registered user: identification, not
|
||||
// authentication, by design of the assignment.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
type UserLookup interface {
|
||||
Exists(ctx context.Context, id uuid.UUID) (bool, error)
|
||||
}
|
||||
|
||||
// RequireUser answers 401 unless X-User-Id names a registered user, and
|
||||
// records that user for the handlers behind it.
|
||||
func RequireUser(users UserLookup) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
raw := c.GetHeader("X-User-Id")
|
||||
if raw == "" {
|
||||
httpx.Error(c, apperr.Unauthorized("X-User-Id header is required"))
|
||||
return
|
||||
}
|
||||
id, err := ident.Parse(raw)
|
||||
if err != nil {
|
||||
httpx.Error(c, apperr.Unauthorized("X-User-Id must be the UUID of a registered user"))
|
||||
return
|
||||
}
|
||||
ok, err := users.Exists(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
httpx.Error(c, apperr.Unauthorized("X-User-Id must be the UUID of a registered user"))
|
||||
return
|
||||
}
|
||||
httpx.SetUserID(c, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// UserHandler is a handler that needs the identified caller.
|
||||
type UserHandler func(c *gin.Context, actor uuid.UUID)
|
||||
|
||||
// WithUser adapts a UserHandler to gin. Reaching it without RequireUser in
|
||||
// front is a wiring mistake, so it is reported as an internal error rather
|
||||
// than blamed on the client with a 401.
|
||||
func WithUser(h UserHandler) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
actor, ok := httpx.UserID(c)
|
||||
if !ok {
|
||||
httpx.Error(c, errors.New("route is missing the RequireUser middleware"))
|
||||
return
|
||||
}
|
||||
h(c, actor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/platform/httpx"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
type lookup map[uuid.UUID]struct{}
|
||||
|
||||
func (l lookup) Exists(_ context.Context, id uuid.UUID) (bool, error) {
|
||||
_, ok := l[id]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func echoActor(c *gin.Context, actor uuid.UUID) {
|
||||
httpx.JSON(c, http.StatusOK, map[string]string{"id": actor.String()})
|
||||
}
|
||||
|
||||
func newEngine(users lookup, guarded bool) *gin.Engine {
|
||||
e := httpx.NewEngine(slog.New(slog.NewTextHandler(io.Discard, nil)), 1024)
|
||||
if guarded {
|
||||
e.GET("/me", auth.RequireUser(users), auth.WithUser(echoActor))
|
||||
} else {
|
||||
e.GET("/me", auth.WithUser(echoActor))
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func call(e *gin.Engine, header string) (*httptest.ResponseRecorder, string) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/me", nil)
|
||||
if header != "" {
|
||||
req.Header.Set("X-User-Id", header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
var body struct {
|
||||
ID string `json:"id"`
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
if body.ID != "" {
|
||||
return rec, body.ID
|
||||
}
|
||||
return rec, body.Error.Code
|
||||
}
|
||||
|
||||
func TestKnownUserReachesHandlerWithItsID(t *testing.T) {
|
||||
alice := ident.New()
|
||||
rec, got := call(newEngine(lookup{alice: {}}, true), alice.String())
|
||||
if rec.Code != http.StatusOK || got != alice.String() {
|
||||
t.Fatalf("status %d, handler saw %q, want %s", rec.Code, got, alice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) {
|
||||
alice := ident.New()
|
||||
e := newEngine(lookup{alice: {}}, true)
|
||||
for name, header := range map[string]string{
|
||||
"missing": "",
|
||||
"malformed": "not-a-uuid",
|
||||
"braces": "{" + alice.String() + "}",
|
||||
"unknown": ident.New().String(),
|
||||
} {
|
||||
rec, code := call(e, header)
|
||||
if rec.Code != http.StatusUnauthorized || code != "unauthorized" {
|
||||
t.Errorf("%s: status = %d code = %q, want 401 unauthorized", name, rec.Code, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithUserWithoutMiddlewareIsAWiringError(t *testing.T) {
|
||||
alice := ident.New()
|
||||
rec, code := call(newEngine(lookup{alice: {}}, false), alice.String())
|
||||
if rec.Code != http.StatusInternalServerError || code != "internal_error" {
|
||||
t.Fatalf("status = %d code = %q, want 500 internal_error", rec.Code, code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Package chat is the chats module. Entities mirror future table rows and
|
||||
// carry no behaviour; membership is a query rather than a field, and
|
||||
// ChatWithMembers is the projection the API renders. Both entities derive
|
||||
// CreatedAt from their UUIDv7 id, so the history order (created_at, id) is
|
||||
// plain id order.
|
||||
package chat
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxTitleCodePoints = 100
|
||||
MaxMembers = 100
|
||||
)
|
||||
|
||||
// ErrNotFound covers both a missing chat and a chat the caller is not a
|
||||
// member of, so outsiders cannot probe for existence.
|
||||
var ErrNotFound = apperr.NotFound("chat not found")
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatWithMembers struct {
|
||||
Chat
|
||||
MemberIDs []uuid.UUID
|
||||
}
|
||||
|
||||
func NewChat(id uuid.UUID, title string) (Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return Chat{}, apperr.Invalid("title must not be blank")
|
||||
}
|
||||
if utf8.RuneCountInString(title) > MaxTitleCodePoints {
|
||||
return Chat{}, apperr.Invalid(fmt.Sprintf("title must be at most %d characters", MaxTitleCodePoints))
|
||||
}
|
||||
return Chat{ID: id, Title: title, CreatedAt: ident.TimeOf(id)}, nil
|
||||
}
|
||||
|
||||
// ValidateMembers checks the member list of a new chat and returns its own
|
||||
// copy in the original order.
|
||||
func ValidateMembers(memberIDs []uuid.UUID, creator uuid.UUID) ([]uuid.UUID, error) {
|
||||
if len(memberIDs) == 0 {
|
||||
return nil, apperr.Invalid("member_ids must not be empty")
|
||||
}
|
||||
if len(memberIDs) > MaxMembers {
|
||||
return nil, apperr.Invalid(fmt.Sprintf("member_ids must have at most %d entries", MaxMembers))
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
for _, m := range memberIDs {
|
||||
if m == uuid.Nil {
|
||||
return nil, apperr.Invalid("member_ids must not contain the nil uuid")
|
||||
}
|
||||
if _, dup := seen[m]; dup {
|
||||
return nil, apperr.Invalid("member_ids must be unique")
|
||||
}
|
||||
seen[m] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[creator]; !ok {
|
||||
return nil, apperr.Invalid("member_ids must include the creator")
|
||||
}
|
||||
return append([]uuid.UUID(nil), memberIDs...), nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func TestNewChatDerivesCreatedAtFromID(t *testing.T) {
|
||||
id := ident.New()
|
||||
c, err := chat.NewChat(id, "Проект")
|
||||
if err != nil {
|
||||
t.Fatalf("NewChat error: %v", err)
|
||||
}
|
||||
if c.ID != id || c.Title != "Проект" || !c.CreatedAt.Equal(ident.TimeOf(id)) {
|
||||
t.Fatalf("unexpected chat %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewChatValidatesTitle(t *testing.T) {
|
||||
for _, title := range []string{"", " ", strings.Repeat("я", 101)} {
|
||||
_, err := chat.NewChat(ident.New(), title)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("title %q must be rejected as invalid, got %v", title, err)
|
||||
}
|
||||
}
|
||||
if _, err := chat.NewChat(ident.New(), strings.Repeat("я", 100)); err != nil {
|
||||
t.Errorf("100 code points must be accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMembersCopiesAndKeepsOrder(t *testing.T) {
|
||||
alice, bob := ident.New(), ident.New()
|
||||
input := []uuid.UUID{bob, alice}
|
||||
members, err := chat.ValidateMembers(input, alice)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateMembers error: %v", err)
|
||||
}
|
||||
if len(members) != 2 || members[0] != bob || members[1] != alice {
|
||||
t.Fatalf("order must be preserved, got %v", members)
|
||||
}
|
||||
input[0] = ident.New()
|
||||
if members[0] != bob {
|
||||
t.Fatal("result must not alias the input slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMembersRejectsInvalidLists(t *testing.T) {
|
||||
alice, bob := ident.New(), ident.New()
|
||||
cases := map[string][]uuid.UUID{
|
||||
"empty": {},
|
||||
"nil": nil,
|
||||
"missing creator": {bob},
|
||||
"duplicate": {alice, bob, bob},
|
||||
"duplicate self": {alice, alice},
|
||||
"too many": append([]uuid.UUID{alice}, many(100)...),
|
||||
"nil uuid member": {alice, uuid.Nil},
|
||||
}
|
||||
for name, members := range cases {
|
||||
_, err := chat.ValidateMembers(members, alice)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("%s: want invalid, got %v", name, err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "member_ids") {
|
||||
t.Errorf("%s: message must name the field: %v", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := chat.ValidateMembers(append([]uuid.UUID{alice}, many(99)...), alice); err != nil {
|
||||
t.Errorf("100 members must be accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func many(n int) []uuid.UUID {
|
||||
out := make([]uuid.UUID, n)
|
||||
for i := range out {
|
||||
out[i] = ident.New()
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
chats *Service
|
||||
}
|
||||
|
||||
func NewHandler(chats *Service) *Handler {
|
||||
return &Handler{chats: chats}
|
||||
}
|
||||
|
||||
// Register mounts the chat endpoints on a router guarded by RequireUser.
|
||||
func (h *Handler) Register(protected gin.IRouter) {
|
||||
protected.POST("/chats", auth.WithUser(h.create))
|
||||
protected.GET("/chats", auth.WithUser(h.list))
|
||||
protected.GET("/chats/:chat_id", auth.WithUser(h.get))
|
||||
protected.POST("/chats/:chat_id/messages", auth.WithUser(h.send))
|
||||
protected.GET("/chats/:chat_id/messages", auth.WithUser(h.history))
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
func toChatResponse(c ChatWithMembers) ChatResponse {
|
||||
members := make([]string, 0, len(c.MemberIDs))
|
||||
for _, m := range c.MemberIDs {
|
||||
members = append(members, m.String())
|
||||
}
|
||||
return ChatResponse{
|
||||
ID: c.ID.String(),
|
||||
Title: c.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: httpx.Timestamp(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toMessageResponse(m Message) MessageResponse {
|
||||
return MessageResponse{
|
||||
ID: m.ID.String(),
|
||||
ChatID: m.ChatID.String(),
|
||||
SenderID: m.SenderID.String(),
|
||||
Text: m.Text,
|
||||
CreatedAt: httpx.Timestamp(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) create(c *gin.Context, actor uuid.UUID) {
|
||||
var req createChatRequest
|
||||
if err := httpx.DecodeJSON(c, &req); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
members := make([]uuid.UUID, 0, len(req.MemberIDs))
|
||||
for _, raw := range req.MemberIDs {
|
||||
id, err := ident.Parse(raw)
|
||||
if err != nil {
|
||||
httpx.Error(c, apperr.Invalid("member_ids must contain valid UUIDs"))
|
||||
return
|
||||
}
|
||||
members = append(members, id)
|
||||
}
|
||||
chat, err := h.chats.Create(c.Request.Context(), actor, req.Title, members)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusCreated, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *Handler) list(c *gin.Context, actor uuid.UUID) {
|
||||
limit, after, err := listing(c, actor)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
page, err := h.chats.List(c.Request.Context(), actor, after, limit)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, actor, toChatResponse))
|
||||
}
|
||||
|
||||
func (h *Handler) get(c *gin.Context, actor uuid.UUID) {
|
||||
chatID, err := chatParam(c)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.Get(c.Request.Context(), actor, chatID)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *Handler) send(c *gin.Context, actor uuid.UUID) {
|
||||
chatID, err := chatParam(c)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
var req createMessageRequest
|
||||
if err := httpx.DecodeJSON(c, &req); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
message, err := h.chats.Send(c.Request.Context(), actor, chatID, req.Text)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusCreated, toMessageResponse(message))
|
||||
}
|
||||
|
||||
func (h *Handler) history(c *gin.Context, actor uuid.UUID) {
|
||||
chatID, err := chatParam(c)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
limit, after, err := listing(c, chatID)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
page, err := h.chats.History(c.Request.Context(), actor, chatID, after, limit)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, chatID, toMessageResponse))
|
||||
}
|
||||
|
||||
func chatParam(c *gin.Context) (uuid.UUID, error) {
|
||||
id, err := ident.Parse(c.Param("chat_id"))
|
||||
if err != nil {
|
||||
return uuid.Nil, apperr.Invalid("chat_id must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// listing parses limit and cursor; the cursor must belong to scope, and a
|
||||
// present but empty cursor is rejected like a malformed one.
|
||||
func listing(c *gin.Context, scope uuid.UUID) (int, *uuid.UUID, error) {
|
||||
limit, err := pagination.ParseLimit(c.Query("limit"))
|
||||
if err != nil {
|
||||
return 0, nil, apperr.Wrap(apperr.KindInvalid, err.Error(), err)
|
||||
}
|
||||
token, present := c.GetQuery("cursor")
|
||||
if !present {
|
||||
return limit, nil, nil
|
||||
}
|
||||
last, err := pagination.DecodeCursor(token, scope)
|
||||
if err != nil {
|
||||
return 0, nil, apperr.Wrap(apperr.KindInvalid, "cursor is invalid for this resource", err)
|
||||
}
|
||||
return limit, &last, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
const MaxTextCodePoints = 4000
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// NewMessage keeps the text verbatim; only blank or oversized text is rejected.
|
||||
func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return Message{}, apperr.Invalid("text must not be blank")
|
||||
}
|
||||
if utf8.RuneCountInString(text) > MaxTextCodePoints {
|
||||
return Message{}, apperr.Invalid(fmt.Sprintf("text must be at most %d characters", MaxTextCodePoints))
|
||||
}
|
||||
return Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: ident.TimeOf(id),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func TestNewMessageDerivesCreatedAt(t *testing.T) {
|
||||
id, chatID, alice := ident.New(), ident.New(), ident.New()
|
||||
m, err := chat.NewMessage(id, chatID, alice, "Привет, мир 👋")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMessage error: %v", err)
|
||||
}
|
||||
if m.ID != id || m.ChatID != chatID || m.SenderID != alice || m.Text != "Привет, мир 👋" {
|
||||
t.Fatalf("unexpected message %+v", m)
|
||||
}
|
||||
if !m.CreatedAt.Equal(ident.TimeOf(id)) {
|
||||
t.Fatalf("CreatedAt = %v, want %v", m.CreatedAt, ident.TimeOf(id))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageValidatesTextByCodePoints(t *testing.T) {
|
||||
chatID, alice := ident.New(), ident.New()
|
||||
if _, err := chat.NewMessage(ident.New(), chatID, alice, strings.Repeat("я", 4000)); err != nil {
|
||||
t.Errorf("4000 code points must be accepted: %v", err)
|
||||
}
|
||||
for _, text := range []string{"", " ", "\n\t ", strings.Repeat("я", 4001)} {
|
||||
_, err := chat.NewMessage(ident.New(), chatID, alice, text)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("text %q must be rejected as invalid, got %v", text, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageKeepsSurroundingWhitespace(t *testing.T) {
|
||||
m, err := chat.NewMessage(ident.New(), ident.New(), ident.New(), " hi ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Text != " hi " {
|
||||
t.Fatalf("text must be stored verbatim, got %q", m.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ChatRepository stores chats and their membership. Membership is answered
|
||||
// by queries; the projection with members is assembled by the store in one
|
||||
// query, never by loading a member list into the entity.
|
||||
type ChatRepository interface {
|
||||
// Create stores the chat row and its members atomically.
|
||||
Create(ctx context.Context, chat Chat, memberIDs []uuid.UUID) error
|
||||
// GetForMember returns the chat with members, or ErrNotFound when the
|
||||
// chat does not exist or the user is not a member.
|
||||
GetForMember(ctx context.Context, chatID, userID uuid.UUID) (ChatWithMembers, error)
|
||||
IsMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
// ListByMember returns up to limit chats of the user ordered by
|
||||
// (created_at, id), strictly after the chat identified by after when set.
|
||||
ListByMember(ctx context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]ChatWithMembers, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
Append(ctx context.Context, message Message) error
|
||||
// ListByChat returns up to limit messages ordered by (created_at, id),
|
||||
// strictly after the message identified by after when set. An unknown
|
||||
// chat yields an empty history.
|
||||
ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]Message, error)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
// UserLookup is what this module needs from the users module: one batched
|
||||
// existence check. It is declared here, on the consumer side, so this
|
||||
// package never imports the users package and tests substitute a map.
|
||||
type UserLookup interface {
|
||||
ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
chats ChatRepository
|
||||
messages MessageRepository
|
||||
users UserLookup
|
||||
}
|
||||
|
||||
func NewService(chats ChatRepository, messages MessageRepository, users UserLookup) *Service {
|
||||
return &Service{chats: chats, messages: messages, users: users}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, creator uuid.UUID, title string, memberIDs []uuid.UUID) (ChatWithMembers, error) {
|
||||
chat, err := NewChat(ident.New(), title)
|
||||
if err != nil {
|
||||
return ChatWithMembers{}, err
|
||||
}
|
||||
members, err := ValidateMembers(memberIDs, creator)
|
||||
if err != nil {
|
||||
return ChatWithMembers{}, err
|
||||
}
|
||||
found, err := s.users.ExistingIDs(ctx, members)
|
||||
if err != nil {
|
||||
return ChatWithMembers{}, fmt.Errorf("check members: %w", err)
|
||||
}
|
||||
if len(found) != len(members) {
|
||||
return ChatWithMembers{}, apperr.Invalid("member_ids must reference registered users")
|
||||
}
|
||||
if err := s.chats.Create(ctx, chat, members); err != nil {
|
||||
return ChatWithMembers{}, err
|
||||
}
|
||||
return ChatWithMembers{Chat: chat, MemberIDs: members}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, actor, chatID uuid.UUID) (ChatWithMembers, error) {
|
||||
return s.chats.GetForMember(ctx, chatID, actor)
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, actor uuid.UUID, after *uuid.UUID, limit int) (pagination.Page[ChatWithMembers], error) {
|
||||
items, err := s.chats.ListByMember(ctx, actor, after, limit+1)
|
||||
if err != nil {
|
||||
return pagination.Page[ChatWithMembers]{}, err
|
||||
}
|
||||
return pagination.Cut(items, limit, func(c ChatWithMembers) uuid.UUID { return c.ID }), nil
|
||||
}
|
||||
|
||||
func (s *Service) Send(ctx context.Context, actor, chatID uuid.UUID, text string) (Message, error) {
|
||||
if err := s.requireMember(ctx, actor, chatID); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
message, err := NewMessage(ident.New(), chatID, actor, text)
|
||||
if err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
if err := s.messages.Append(ctx, message); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *Service) History(ctx context.Context, actor, chatID uuid.UUID, after *uuid.UUID, limit int) (pagination.Page[Message], error) {
|
||||
if err := s.requireMember(ctx, actor, chatID); err != nil {
|
||||
return pagination.Page[Message]{}, err
|
||||
}
|
||||
items, err := s.messages.ListByChat(ctx, chatID, after, limit+1)
|
||||
if err != nil {
|
||||
return pagination.Page[Message]{}, err
|
||||
}
|
||||
return pagination.Cut(items, limit, func(m Message) uuid.UUID { return m.ID }), nil
|
||||
}
|
||||
|
||||
// requireMember runs before any field validation, so an outsider gets the
|
||||
// same answer for a foreign chat as for a missing one.
|
||||
func (s *Service) requireMember(ctx context.Context, actor, chatID uuid.UUID) error {
|
||||
ok, err := s.chats.IsMember(ctx, chatID, actor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
// knownUsers doubles chat.UserLookup and counts calls to prove that member
|
||||
// checks are batched.
|
||||
type knownUsers struct {
|
||||
ids map[uuid.UUID]struct{}
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (k *knownUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
k.calls.Add(1)
|
||||
out := make([]uuid.UUID, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, ok := k.ids[id]; ok {
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
svc *chat.Service
|
||||
users *knownUsers
|
||||
alice, bob uuid.UUID
|
||||
eve uuid.UUID
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newFixture() fixture {
|
||||
alice, bob, eve := ident.New(), ident.New(), ident.New()
|
||||
users := &knownUsers{ids: map[uuid.UUID]struct{}{alice: {}, bob: {}, eve: {}}}
|
||||
return fixture{
|
||||
svc: chat.NewService(store.NewInMemChats(), store.NewInMemMessages(), users),
|
||||
users: users,
|
||||
alice: alice,
|
||||
bob: bob,
|
||||
eve: eve,
|
||||
ctx: context.Background(),
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatChecksMembersInOneCall(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "Проект", []uuid.UUID{f.alice, f.bob, f.eve})
|
||||
if err != nil {
|
||||
t.Fatalf("Create error: %v", err)
|
||||
}
|
||||
if c.Title != "Проект" || len(c.MemberIDs) != 3 {
|
||||
t.Fatalf("unexpected chat %+v", c)
|
||||
}
|
||||
if got := f.users.calls.Load(); got != 1 {
|
||||
t.Fatalf("member existence must be checked with one batch call, got %d", got)
|
||||
}
|
||||
got, err := f.svc.Get(f.ctx, f.bob, c.ID)
|
||||
if err != nil || got.ID != c.ID || len(got.MemberIDs) != 3 {
|
||||
t.Fatalf("member Get = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRejectsUnknownMember(t *testing.T) {
|
||||
f := newFixture()
|
||||
_, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, ident.New()})
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatalf("kind = %v, want KindInvalid (%v)", apperr.KindOf(err), err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "member_ids") {
|
||||
t.Fatalf("message must name the field: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRejectsInvalidInputBeforeAnyLookup(t *testing.T) {
|
||||
f := newFixture()
|
||||
cases := map[string]struct {
|
||||
title string
|
||||
members []uuid.UUID
|
||||
}{
|
||||
"blank title": {" ", []uuid.UUID{f.alice}},
|
||||
"missing creator": {"t", []uuid.UUID{f.bob}},
|
||||
"duplicate": {"t", []uuid.UUID{f.alice, f.alice}},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
_, err := f.svc.Create(f.ctx, f.alice, tc.title, tc.members)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("%s: kind = %v, want KindInvalid (%v)", name, apperr.KindOf(err), err)
|
||||
}
|
||||
}
|
||||
if got := f.users.calls.Load(); got != 0 {
|
||||
t.Fatalf("invalid input must be rejected before any user lookup, got %d calls", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHidesForeignAndUnknownChatsAlike(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
_, foreign := f.svc.Get(f.ctx, f.eve, c.ID)
|
||||
_, unknown := f.svc.Get(f.ctx, f.eve, ident.New())
|
||||
if !errors.Is(foreign, chat.ErrNotFound) || !errors.Is(unknown, chat.ErrNotFound) {
|
||||
t.Fatalf("foreign = %v, unknown = %v; want both ErrNotFound", foreign, unknown)
|
||||
}
|
||||
if apperr.KindOf(foreign) != apperr.KindNotFound {
|
||||
t.Fatalf("ErrNotFound must carry KindNotFound, got %v", apperr.KindOf(foreign))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPagesOnlyOwnChats(t *testing.T) {
|
||||
f := newFixture()
|
||||
var mine []uuid.UUID
|
||||
for i := 0; i < 3; i++ {
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mine = append(mine, c.ID)
|
||||
if _, err := f.svc.Create(f.ctx, f.eve, "t", []uuid.UUID{f.eve}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
page, err := f.svc.List(f.ctx, f.alice, nil, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 2 || page.Next == nil || *page.Next != mine[1] {
|
||||
t.Fatalf("first page = %+v", page)
|
||||
}
|
||||
if len(page.Items[0].MemberIDs) != 2 {
|
||||
t.Fatalf("listed chats must carry their members: %+v", page.Items[0])
|
||||
}
|
||||
rest, err := f.svc.List(f.ctx, f.alice, page.Next, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest.Items) != 1 || rest.Items[0].ID != mine[2] || rest.Next != nil {
|
||||
t.Fatalf("second page = %+v", rest)
|
||||
}
|
||||
all, err := f.svc.List(f.ctx, f.bob, nil, 100)
|
||||
if err != nil || len(all.Items) != 3 || all.Next != nil {
|
||||
t.Fatalf("bob page = %+v, %v", all, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendChecksAccessBeforeValidation(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
_, err := f.svc.Send(f.ctx, f.eve, c.ID, " ")
|
||||
if !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider with blank text: err = %v, want ErrNotFound", err)
|
||||
}
|
||||
_, err = f.svc.Send(f.ctx, f.bob, c.ID, " ")
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatalf("member with blank text: kind = %v, want KindInvalid", apperr.KindOf(err))
|
||||
}
|
||||
msg, err := f.svc.Send(f.ctx, f.bob, c.ID, "Привет 👋")
|
||||
if err != nil || msg.SenderID != f.bob || msg.ChatID != c.ID || msg.Text != "Привет 👋" {
|
||||
t.Fatalf("Send = %+v, %v", msg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryPagesAndHidesForeignChat(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
first, _ := f.svc.Send(f.ctx, f.alice, c.ID, "1")
|
||||
second, _ := f.svc.Send(f.ctx, f.bob, c.ID, "2")
|
||||
|
||||
page, err := f.svc.History(f.ctx, f.bob, c.ID, nil, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != first.ID || page.Next == nil || *page.Next != first.ID {
|
||||
t.Fatalf("first page = %+v", page)
|
||||
}
|
||||
rest, err := f.svc.History(f.ctx, f.alice, c.ID, page.Next, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest.Items) != 1 || rest.Items[0].ID != second.ID || rest.Next != nil {
|
||||
t.Fatalf("second page = %+v", rest)
|
||||
}
|
||||
if _, err := f.svc.History(f.ctx, f.eve, c.ID, nil, 10); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider history: err = %v, want ErrNotFound", err)
|
||||
}
|
||||
empty, err := f.svc.History(f.ctx, f.alice, c.ID, &second.ID, 10)
|
||||
if err != nil || empty.Items == nil || len(empty.Items) != 0 || empty.Next != nil {
|
||||
t.Fatalf("page after last = %+v, %v; want empty non-nil items", empty, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Package store holds the repository implementations of the chats module.
|
||||
// inmem.go is the in-process one: state lives only in this process and
|
||||
// disappears with it by design of the lab.
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
// InMemChats keeps chat rows, a per-chat member list and set, and a
|
||||
// per-member index of chat ids ordered by (created_at, id), which for UUIDv7
|
||||
// ids is plain id order. One read-write mutex guards all four maps.
|
||||
type InMemChats struct {
|
||||
mu sync.RWMutex
|
||||
rows map[uuid.UUID]chat.Chat
|
||||
members map[uuid.UUID][]uuid.UUID
|
||||
memberOf map[uuid.UUID]map[uuid.UUID]struct{}
|
||||
byMember map[uuid.UUID][]uuid.UUID
|
||||
}
|
||||
|
||||
var _ chat.ChatRepository = (*InMemChats)(nil)
|
||||
|
||||
func NewInMemChats() *InMemChats {
|
||||
return &InMemChats{
|
||||
rows: make(map[uuid.UUID]chat.Chat),
|
||||
members: make(map[uuid.UUID][]uuid.UUID),
|
||||
memberOf: make(map[uuid.UUID]map[uuid.UUID]struct{}),
|
||||
byMember: make(map[uuid.UUID][]uuid.UUID),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *InMemChats) Create(_ context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
|
||||
members := append([]uuid.UUID(nil), memberIDs...)
|
||||
set := make(map[uuid.UUID]struct{}, len(members))
|
||||
for _, m := range members {
|
||||
set[m] = struct{}{}
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.rows[c.ID] = c
|
||||
r.members[c.ID] = members
|
||||
r.memberOf[c.ID] = set
|
||||
for _, m := range members {
|
||||
r.byMember[m] = insertSorted(r.byMember[m], c.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) GetForMember(_ context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if _, ok := r.memberOf[chatID][userID]; !ok {
|
||||
return chat.ChatWithMembers{}, chat.ErrNotFound
|
||||
}
|
||||
return r.projection(chatID), nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) IsMember(_ context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
_, ok := r.memberOf[chatID][userID]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) ListByMember(_ context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
ids := r.byMember[userID]
|
||||
start := firstAfter(ids, after)
|
||||
end := min(start+limit, len(ids))
|
||||
out := make([]chat.ChatWithMembers, 0, end-start)
|
||||
for _, id := range ids[start:end] {
|
||||
out = append(out, r.projection(id))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// projection copies the member list so callers never alias the store.
|
||||
func (r *InMemChats) projection(chatID uuid.UUID) chat.ChatWithMembers {
|
||||
return chat.ChatWithMembers{
|
||||
Chat: r.rows[chatID],
|
||||
MemberIDs: append([]uuid.UUID(nil), r.members[chatID]...),
|
||||
}
|
||||
}
|
||||
|
||||
// InMemMessages keeps one ordered history per chat. The outer lock only
|
||||
// guards the map of histories; each history has its own lock, so writers to
|
||||
// different chats never contend.
|
||||
type InMemMessages struct {
|
||||
mu sync.RWMutex
|
||||
byChat map[uuid.UUID]*history
|
||||
}
|
||||
|
||||
type history struct {
|
||||
mu sync.RWMutex
|
||||
items []chat.Message
|
||||
}
|
||||
|
||||
var _ chat.MessageRepository = (*InMemMessages)(nil)
|
||||
|
||||
func NewInMemMessages() *InMemMessages {
|
||||
return &InMemMessages{byChat: make(map[uuid.UUID]*history)}
|
||||
}
|
||||
|
||||
// Append inserts at the sorted position; ids are monotonic, so the usual
|
||||
// case is an append at the tail.
|
||||
func (r *InMemMessages) Append(_ context.Context, m chat.Message) error {
|
||||
h := r.historyFor(m.ChatID, true)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
n := len(h.items)
|
||||
if n == 0 || less(h.items[n-1].ID, m.ID) {
|
||||
h.items = append(h.items, m)
|
||||
return nil
|
||||
}
|
||||
i := sort.Search(n, func(k int) bool { return !less(h.items[k].ID, m.ID) })
|
||||
h.items = append(h.items, chat.Message{})
|
||||
copy(h.items[i+1:], h.items[i:])
|
||||
h.items[i] = m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemMessages) ListByChat(_ context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]chat.Message, error) {
|
||||
h := r.historyFor(chatID, false)
|
||||
if h == nil {
|
||||
return []chat.Message{}, nil
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
start := 0
|
||||
if after != nil {
|
||||
start = sort.Search(len(h.items), func(k int) bool { return less(*after, h.items[k].ID) })
|
||||
}
|
||||
end := min(start+limit, len(h.items))
|
||||
out := make([]chat.Message, end-start)
|
||||
copy(out, h.items[start:end])
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *InMemMessages) historyFor(chatID uuid.UUID, create bool) *history {
|
||||
r.mu.RLock()
|
||||
h := r.byChat[chatID]
|
||||
r.mu.RUnlock()
|
||||
if h != nil || !create {
|
||||
return h
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if h = r.byChat[chatID]; h == nil {
|
||||
h = &history{}
|
||||
r.byChat[chatID] = h
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// less orders ids lexicographically, which for UUIDv7 is creation order.
|
||||
func less(a, b uuid.UUID) bool {
|
||||
return bytes.Compare(a[:], b[:]) < 0
|
||||
}
|
||||
|
||||
func insertSorted(ids []uuid.UUID, id uuid.UUID) []uuid.UUID {
|
||||
n := len(ids)
|
||||
if n == 0 || less(ids[n-1], id) {
|
||||
return append(ids, id)
|
||||
}
|
||||
i := sort.Search(n, func(k int) bool { return !less(ids[k], id) })
|
||||
ids = append(ids, uuid.Nil)
|
||||
copy(ids[i+1:], ids[i:])
|
||||
ids[i] = id
|
||||
return ids
|
||||
}
|
||||
|
||||
// firstAfter returns the index of the first id strictly greater than after,
|
||||
// or len(ids) when there is none; nil after means the start.
|
||||
func firstAfter(ids []uuid.UUID, after *uuid.UUID) int {
|
||||
if after == nil {
|
||||
return 0
|
||||
}
|
||||
return sort.Search(len(ids), func(k int) bool { return less(*after, ids[k]) })
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func mustChat(t *testing.T) chat.Chat {
|
||||
t.Helper()
|
||||
c, err := chat.NewChat(ident.New(), "title")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func mustMessage(t *testing.T, chatID uuid.UUID) chat.Message {
|
||||
t.Helper()
|
||||
m, err := chat.NewMessage(ident.New(), chatID, ident.New(), "text")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestChatCreateThenGetForMember(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
alice, bob := ident.New(), ident.New()
|
||||
c := mustChat(t)
|
||||
if err := repo.Create(ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := repo.GetForMember(ctx, c.ID, bob)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Chat != c || len(got.MemberIDs) != 2 || got.MemberIDs[0] != alice || got.MemberIDs[1] != bob {
|
||||
t.Fatalf("GetForMember = %+v", got)
|
||||
}
|
||||
got.MemberIDs[0] = ident.New()
|
||||
again, _ := repo.GetForMember(ctx, c.ID, alice)
|
||||
if again.MemberIDs[0] != alice {
|
||||
t.Fatal("GetForMember must return a copy of the member list")
|
||||
}
|
||||
if _, err := repo.GetForMember(ctx, c.ID, ident.New()); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider must get ErrNotFound, got %v", err)
|
||||
}
|
||||
for who, want := range map[uuid.UUID]bool{alice: true, bob: true, ident.New(): false} {
|
||||
ok, err := repo.IsMember(ctx, c.ID, who)
|
||||
if err != nil || ok != want {
|
||||
t.Fatalf("IsMember(%s) = %v, %v; want %v", who, ok, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatUnknownID(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
if _, err := repo.GetForMember(ctx, ident.New(), ident.New()); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("GetForMember err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if ok, err := repo.IsMember(ctx, ident.New(), ident.New()); err != nil || ok {
|
||||
t.Fatalf("IsMember on unknown chat = %v, %v; want false, nil", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByMemberFiltersOrdersAndPages(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
alice, bob := ident.New(), ident.New()
|
||||
var mine []chat.Chat
|
||||
for i := 0; i < 5; i++ {
|
||||
mine = append(mine, mustChat(t))
|
||||
// A chat without alice must never show up in her listing.
|
||||
if err := repo.Create(ctx, mustChat(t), []uuid.UUID{bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Insert the oldest chat last to prove the store sorts, not appends.
|
||||
for _, c := range mine[1:] {
|
||||
if err := repo.Create(ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := repo.Create(ctx, mine[0], []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
page, err := repo.ListByMember(ctx, alice, nil, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) != 3 || page[0].ID != mine[0].ID || page[2].ID != mine[2].ID {
|
||||
t.Fatalf("first page mismatch: %v", page)
|
||||
}
|
||||
if len(page[0].MemberIDs) != 2 {
|
||||
t.Fatalf("listing must carry members: %+v", page[0])
|
||||
}
|
||||
last := page[2].ID
|
||||
rest, err := repo.ListByMember(ctx, alice, &last, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest) != 2 || rest[0].ID != mine[3].ID || rest[1].ID != mine[4].ID {
|
||||
t.Fatalf("second page mismatch: %v", rest)
|
||||
}
|
||||
none, err := repo.ListByMember(ctx, ident.New(), nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if none == nil || len(none) != 0 {
|
||||
t.Fatalf("unknown member must get an empty non-nil slice, got %#v", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByChatUnknownChatIsEmpty(t *testing.T) {
|
||||
got, err := store.NewInMemMessages().ListByChat(context.Background(), ident.New(), nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("want empty non-nil slice, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendOutOfOrderIsSortedByID(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
first, second, third := mustMessage(t, chatID), mustMessage(t, chatID), mustMessage(t, chatID)
|
||||
for _, m := range []chat.Message{third, first, second} {
|
||||
if err := repo.Append(ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 3 || got[0].ID != first.ID || got[1].ID != second.ID || got[2].ID != third.ID {
|
||||
t.Fatalf("history must be ordered by id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagingWalksWholeHistoryWithoutGapsOrDuplicates(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
const total = 250
|
||||
var expected []uuid.UUID
|
||||
for i := 0; i < total; i++ {
|
||||
m := mustMessage(t, chatID)
|
||||
expected = append(expected, m.ID)
|
||||
if err := repo.Append(ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, limit := range []int{1, 7, 100} {
|
||||
var seen []uuid.UUID
|
||||
var after *uuid.UUID
|
||||
for {
|
||||
page, err := repo.ListByChat(ctx, chatID, after, limit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
if len(page) > limit {
|
||||
t.Fatalf("limit %d: page has %d items", limit, len(page))
|
||||
}
|
||||
for _, m := range page {
|
||||
seen = append(seen, m.ID)
|
||||
}
|
||||
last := page[len(page)-1].ID
|
||||
after = &last
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Fatalf("limit %d: walked %d messages, want %d", limit, len(seen), total)
|
||||
}
|
||||
for i := range seen {
|
||||
if seen[i] != expected[i] {
|
||||
t.Fatalf("limit %d: position %d has %s, want %s", limit, i, seen[i], expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAfterUnknownIDStartsAtNextGreater(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
a := mustMessage(t, chatID)
|
||||
gap := ident.New() // never stored, but sorts between a and b
|
||||
b := mustMessage(t, chatID)
|
||||
_ = repo.Append(ctx, a)
|
||||
_ = repo.Append(ctx, b)
|
||||
got, _ := repo.ListByChat(ctx, chatID, &gap, 10)
|
||||
if len(got) != 1 || got[0].ID != b.ID {
|
||||
t.Fatalf("want only b after the gap id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByChatReturnsCopy(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
_ = repo.Append(ctx, mustMessage(t, chatID))
|
||||
page, _ := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
page[0].Text = "mutated"
|
||||
again, _ := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
if again[0].Text != "text" {
|
||||
t.Fatal("ListByChat must not expose internal storage")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentAppendsKeepEveryMessageOrdered(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
const clients, perClient = 10, 10
|
||||
var wg sync.WaitGroup
|
||||
for c := 0; c < clients; c++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perClient; i++ {
|
||||
if err := repo.Append(ctx, mustMessage(t, chatID)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
got, err := repo.ListByChat(ctx, chatID, nil, clients*perClient+1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != clients*perClient {
|
||||
t.Fatalf("stored %d messages, want %d", len(got), clients*perClient)
|
||||
}
|
||||
unique := make(map[uuid.UUID]struct{}, len(got))
|
||||
for i, m := range got {
|
||||
unique[m.ID] = struct{}{}
|
||||
if i > 0 && bytes.Compare(got[i-1].ID[:], m.ID[:]) >= 0 {
|
||||
t.Fatalf("history out of order at %d", i)
|
||||
}
|
||||
}
|
||||
if len(unique) != clients*perClient {
|
||||
t.Fatalf("%d unique ids, want %d", len(unique), clients*perClient)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package health serves the probes. Liveness only proves the process
|
||||
// answers; readiness is switched off during shutdown so an orchestrator stops
|
||||
// routing new traffic before the listener closes.
|
||||
package health
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
type status struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func New() *Handler {
|
||||
h := &Handler{}
|
||||
h.ready.Store(true)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Handler) SetReady(ready bool) {
|
||||
h.ready.Store(ready)
|
||||
}
|
||||
|
||||
func (h *Handler) IsReady() bool {
|
||||
return h.ready.Load()
|
||||
}
|
||||
|
||||
func (h *Handler) Register(r gin.IRouter) {
|
||||
r.GET("/health/live", h.live)
|
||||
r.GET("/health/ready", h.readyz)
|
||||
}
|
||||
|
||||
func (h *Handler) live(c *gin.Context) {
|
||||
httpx.JSON(c, http.StatusOK, status{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *Handler) readyz(c *gin.Context) {
|
||||
if !h.ready.Load() {
|
||||
httpx.Error(c, apperr.Unavailable("service is shutting down"))
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, status{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package apperr is the application's error vocabulary: every module reports
|
||||
// failures as a Kind plus a message that is safe to show to clients, and the
|
||||
// transport layer owns the only mapping from Kind to HTTP status. Causes are
|
||||
// kept for logs but never rendered.
|
||||
package apperr
|
||||
|
||||
import "errors"
|
||||
|
||||
type Kind int
|
||||
|
||||
const (
|
||||
KindInternal Kind = iota
|
||||
KindInvalid
|
||||
KindUnauthorized
|
||||
KindNotFound
|
||||
KindConflict
|
||||
KindPayloadTooLarge
|
||||
KindUnsupportedMedia
|
||||
KindUnavailable
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Kind Kind
|
||||
Message string
|
||||
Cause error
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Message }
|
||||
|
||||
func (e *Error) Unwrap() error { return e.Cause }
|
||||
|
||||
func New(kind Kind, message string) *Error {
|
||||
return &Error{Kind: kind, Message: message}
|
||||
}
|
||||
|
||||
func Wrap(kind Kind, message string, cause error) *Error {
|
||||
return &Error{Kind: kind, Message: message, Cause: cause}
|
||||
}
|
||||
|
||||
// KindOf classifies any error; foreign errors are internal.
|
||||
func KindOf(err error) Kind {
|
||||
if e, ok := errors.AsType[*Error](err); ok {
|
||||
return e.Kind
|
||||
}
|
||||
return KindInternal
|
||||
}
|
||||
|
||||
func Invalid(message string) *Error { return New(KindInvalid, message) }
|
||||
func Unauthorized(message string) *Error { return New(KindUnauthorized, message) }
|
||||
func NotFound(message string) *Error { return New(KindNotFound, message) }
|
||||
func Conflict(message string) *Error { return New(KindConflict, message) }
|
||||
func PayloadTooLarge(message string) *Error { return New(KindPayloadTooLarge, message) }
|
||||
func UnsupportedMedia(message string) *Error { return New(KindUnsupportedMedia, message) }
|
||||
func Unavailable(message string) *Error { return New(KindUnavailable, message) }
|
||||
@@ -0,0 +1,49 @@
|
||||
package apperr_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
func TestKindOfReturnsKindForApplicationError(t *testing.T) {
|
||||
err := apperr.NotFound("chat not found")
|
||||
if got := apperr.KindOf(err); got != apperr.KindNotFound {
|
||||
t.Fatalf("KindOf = %v, want KindNotFound", got)
|
||||
}
|
||||
if err.Error() != "chat not found" {
|
||||
t.Fatalf("Error() = %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindOfSeesThroughWrapping(t *testing.T) {
|
||||
err := fmt.Errorf("service: %w", apperr.Conflict("username taken"))
|
||||
if got := apperr.KindOf(err); got != apperr.KindConflict {
|
||||
t.Fatalf("KindOf = %v, want KindConflict", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindOfDefaultsToInternal(t *testing.T) {
|
||||
if got := apperr.KindOf(errors.New("boom")); got != apperr.KindInternal {
|
||||
t.Fatalf("KindOf = %v, want KindInternal", got)
|
||||
}
|
||||
if got := apperr.KindOf(nil); got != apperr.KindInternal {
|
||||
t.Fatalf("KindOf(nil) = %v, want KindInternal", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapKeepsCause(t *testing.T) {
|
||||
cause := errors.New("cause")
|
||||
err := apperr.Wrap(apperr.KindInvalid, "bad input", cause)
|
||||
if !errors.Is(err, cause) {
|
||||
t.Fatal("wrapped error must unwrap to cause")
|
||||
}
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatal("wrapped error must keep its kind")
|
||||
}
|
||||
if err.Error() != "bad input" {
|
||||
t.Fatalf("Error() = %q, want public message only", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Package config reads the process configuration from the environment.
|
||||
// Every setting has a default suited to the lab stand; an invalid value stops
|
||||
// the process at start-up with a message naming the variable.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
MaxBodyBytes int64
|
||||
}
|
||||
|
||||
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
|
||||
// in production, a map in tests.
|
||||
type Lookup func(key string) (string, bool)
|
||||
|
||||
func Load(lookup Lookup) (Config, error) {
|
||||
cfg := Config{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
Env: "lab",
|
||||
LogLevel: slog.LevelInfo,
|
||||
ShutdownTimeout: 8 * time.Second,
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
}
|
||||
if v, ok := lookup("APP_HOST"); ok {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
return Config{}, fmt.Errorf("APP_HOST must not be empty")
|
||||
}
|
||||
cfg.Host = v
|
||||
}
|
||||
if v, ok := lookup("APP_PORT"); ok {
|
||||
port, err := strconv.Atoi(v)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return Config{}, fmt.Errorf("APP_PORT must be an integer between 1 and 65535, got %q", v)
|
||||
}
|
||||
cfg.Port = port
|
||||
}
|
||||
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
|
||||
cfg.Env = v
|
||||
}
|
||||
if v, ok := lookup("APP_LOG_LEVEL"); ok {
|
||||
var level slog.Level
|
||||
if err := level.UnmarshalText([]byte(v)); err != nil {
|
||||
return Config{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
|
||||
}
|
||||
cfg.LogLevel = level
|
||||
}
|
||||
if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok {
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil || d <= 0 {
|
||||
return Config{}, fmt.Errorf("APP_SHUTDOWN_TIMEOUT must be a positive duration such as 8s, got %q", v)
|
||||
}
|
||||
cfg.ShutdownTimeout = d
|
||||
}
|
||||
if v, ok := lookup("APP_MAX_BODY_BYTES"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || n <= 0 {
|
||||
return Config{}, fmt.Errorf("APP_MAX_BODY_BYTES must be a positive integer, got %q", v)
|
||||
}
|
||||
cfg.MaxBodyBytes = n
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/config"
|
||||
)
|
||||
|
||||
func env(values map[string]string) func(string) (string, bool) {
|
||||
return func(key string) (string, bool) {
|
||||
v, ok := values[key]
|
||||
return v, ok
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
cfg, err := config.Load(env(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("Load error: %v", err)
|
||||
}
|
||||
if cfg.Addr() != "0.0.0.0:8080" {
|
||||
t.Fatalf("Addr = %q", cfg.Addr())
|
||||
}
|
||||
if cfg.Env != "lab" || cfg.LogLevel != slog.LevelInfo {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverrides(t *testing.T) {
|
||||
cfg, err := config.Load(env(map[string]string{
|
||||
"APP_HOST": "127.0.0.1",
|
||||
"APP_PORT": "9090",
|
||||
"APP_ENV": "dev",
|
||||
"APP_LOG_LEVEL": "debug",
|
||||
"APP_SHUTDOWN_TIMEOUT": "3s",
|
||||
"APP_MAX_BODY_BYTES": "1024",
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("Load error: %v", err)
|
||||
}
|
||||
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.LogLevel != slog.LevelDebug {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidValuesAreReported(t *testing.T) {
|
||||
cases := map[string]map[string]string{
|
||||
"port text": {"APP_PORT": "abc"},
|
||||
"port zero": {"APP_PORT": "0"},
|
||||
"port too big": {"APP_PORT": "70000"},
|
||||
"level": {"APP_LOG_LEVEL": "loud"},
|
||||
"timeout": {"APP_SHUTDOWN_TIMEOUT": "soon"},
|
||||
"timeout negative": {"APP_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
"body zero": {"APP_MAX_BODY_BYTES": "0"},
|
||||
"body text": {"APP_MAX_BODY_BYTES": "big"},
|
||||
"empty host": {"APP_HOST": ""},
|
||||
}
|
||||
for name, values := range cases {
|
||||
if _, err := config.Load(env(values)); err == nil {
|
||||
t.Errorf("%s: want error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
// DecodeJSON reads exactly one JSON object into dst and enforces what gin's
|
||||
// binding does not: the media type must be application/json (415), invalid
|
||||
// UTF-8, unknown fields, wrong types, malformed syntax and trailing data are
|
||||
// 400, an oversized body is 413, and messages never expose Go type names.
|
||||
func DecodeJSON(c *gin.Context, dst any) error {
|
||||
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return apperr.UnsupportedMedia("Content-Type must be application/json")
|
||||
}
|
||||
// The body is already capped by the bodyLimit middleware, so reading it
|
||||
// whole is bounded.
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return decodeError(err)
|
||||
}
|
||||
// encoding/json silently replaces invalid UTF-8 with U+FFFD; the contract
|
||||
// and RFC 8259 require UTF-8, so such a body is rejected, not repaired.
|
||||
if !utf8.Valid(body) {
|
||||
return apperr.Invalid("request body must be valid UTF-8")
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return decodeError(err)
|
||||
}
|
||||
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return apperr.Invalid("unexpected data after JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeError(err error) error {
|
||||
if tooLarge, ok := errors.AsType[*http.MaxBytesError](err); ok {
|
||||
return apperr.Wrap(apperr.KindPayloadTooLarge, fmt.Sprintf("request body must be at most %d bytes", tooLarge.Limit), err)
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
return apperr.Wrap(apperr.KindInvalid, "request body is required", err)
|
||||
}
|
||||
if wrongType, ok := errors.AsType[*json.UnmarshalTypeError](err); ok {
|
||||
if wrongType.Field == "" {
|
||||
return apperr.Wrap(apperr.KindInvalid, "request body must be a JSON object", err)
|
||||
}
|
||||
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("field %q has wrong type", wrongType.Field), err)
|
||||
}
|
||||
// encoding/json reports unknown fields as a plain error without a type.
|
||||
const unknownPrefix = "json: unknown field "
|
||||
if msg := err.Error(); strings.HasPrefix(msg, unknownPrefix) {
|
||||
field := strings.Trim(strings.TrimPrefix(msg, unknownPrefix), `"`)
|
||||
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("unknown field %q", field), err)
|
||||
}
|
||||
return apperr.Wrap(apperr.KindInvalid, "malformed JSON body", err)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Package httpx is the transport layer over gin: request ids, access
|
||||
// logging, panic recovery, body limits, strict JSON decoding and the single
|
||||
// error format of the API contract. gin is used for routing and the
|
||||
// middleware chain; everything here exists because the contract demands a
|
||||
// specific behaviour that gin's own helpers do not provide.
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
const (
|
||||
keyRequestID = "messenger.request_id"
|
||||
keyLogger = "messenger.logger"
|
||||
)
|
||||
|
||||
// NewEngine builds an engine whose every response, including routing
|
||||
// failures and panics, carries X-Request-Id and the contract error body.
|
||||
func NewEngine(log *slog.Logger, maxBodyBytes int64) *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
e := gin.New()
|
||||
// Redirects would answer with text/plain and without a request id.
|
||||
e.RedirectTrailingSlash = false
|
||||
e.RedirectFixedPath = false
|
||||
e.HandleMethodNotAllowed = true
|
||||
|
||||
e.Use(requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
|
||||
e.NoRoute(func(c *gin.Context) { Error(c, apperr.NotFound("route not found")) })
|
||||
e.NoMethod(func(c *gin.Context) { Fail(c, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") })
|
||||
return e
|
||||
}
|
||||
|
||||
func RequestID(c *gin.Context) string {
|
||||
return c.GetString(keyRequestID)
|
||||
}
|
||||
|
||||
func logger(c *gin.Context) *slog.Logger {
|
||||
if l, ok := c.Get(keyLogger); ok {
|
||||
if log, ok := l.(*slog.Logger); ok {
|
||||
return log
|
||||
}
|
||||
}
|
||||
return slog.Default()
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package httpx_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
type payload struct {
|
||||
Text string `json:"text"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func newEngine(t *testing.T, logs *bytes.Buffer) *gin.Engine {
|
||||
t.Helper()
|
||||
return newEngineAt(t, logs, slog.LevelDebug)
|
||||
}
|
||||
|
||||
func newEngineAt(t *testing.T, logs *bytes.Buffer, level slog.Level) *gin.Engine {
|
||||
t.Helper()
|
||||
if logs == nil {
|
||||
logs = &bytes.Buffer{}
|
||||
}
|
||||
log := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: level}))
|
||||
e := httpx.NewEngine(log, 64)
|
||||
e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": "<a&b>"}) })
|
||||
e.GET("/panic", func(c *gin.Context) { panic("secret detail") })
|
||||
e.GET("/fail", func(c *gin.Context) { httpx.Error(c, errors.New("db password leaked")) })
|
||||
e.GET("/notfound", func(c *gin.Context) { httpx.Error(c, apperr.NotFound("chat not found")) })
|
||||
e.GET("/who", func(c *gin.Context) {
|
||||
httpx.SetUserID(c, uuid.MustParse("11111111-1111-4111-8111-111111111111"))
|
||||
id, ok := httpx.UserID(c)
|
||||
httpx.JSON(c, http.StatusOK, gin.H{"id": id.String(), "ok": ok})
|
||||
})
|
||||
e.POST("/decode", func(c *gin.Context) {
|
||||
var p payload
|
||||
if err := httpx.DecodeJSON(c, &p); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, p)
|
||||
})
|
||||
return e
|
||||
}
|
||||
|
||||
func do(t *testing.T, e *gin.Engine, method, path string, body string, headers map[string]string) (*httptest.ResponseRecorder, errorBody) {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != "" {
|
||||
reader = strings.NewReader(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, reader)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
var eb errorBody
|
||||
if rec.Code >= 400 {
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &eb); err != nil {
|
||||
t.Fatalf("%s %s: error body is not JSON: %v: %s", method, path, err, rec.Body.String())
|
||||
}
|
||||
}
|
||||
return rec, eb
|
||||
}
|
||||
|
||||
func assertError(t *testing.T, rec *httptest.ResponseRecorder, eb errorBody, status int, code string) {
|
||||
t.Helper()
|
||||
if rec.Code != status {
|
||||
t.Fatalf("status = %d, want %d (body %s)", rec.Code, status, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||
t.Fatalf("Content-Type = %q", ct)
|
||||
}
|
||||
rid := rec.Header().Get("X-Request-Id")
|
||||
if rid == "" {
|
||||
t.Fatal("missing X-Request-Id header")
|
||||
}
|
||||
if eb.Error.RequestID != rid {
|
||||
t.Fatalf("body request_id %q != header %q", eb.Error.RequestID, rid)
|
||||
}
|
||||
if eb.Error.Code != code || eb.Error.Message == "" {
|
||||
t.Fatalf("error = %+v, want code %q with a message", eb.Error, code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownRouteIsJSON404(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/nope", "", nil)
|
||||
assertError(t, rec, eb, http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestTrailingSlashIsNotRedirected(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/ok/", "", nil)
|
||||
assertError(t, rec, eb, http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestWrongMethodIsJSON405WithAllow(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodDelete, "/ok", "", nil)
|
||||
assertError(t, rec, eb, http.StatusMethodNotAllowed, "invalid_request")
|
||||
if !strings.Contains(rec.Header().Get("Allow"), "GET") {
|
||||
t.Fatalf("Allow = %q, want GET", rec.Header().Get("Allow"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanicBecomesJSON500WithoutDetails(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/panic", "", nil)
|
||||
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
|
||||
if strings.Contains(rec.Body.String(), "secret detail") {
|
||||
t.Fatal("panic value leaked to the client")
|
||||
}
|
||||
if !strings.Contains(logs.String(), "secret detail") {
|
||||
t.Fatal("panic must be logged for operators")
|
||||
}
|
||||
}
|
||||
|
||||
func TestForeignErrorBecomesJSON500WithoutDetails(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/fail", "", nil)
|
||||
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
|
||||
if strings.Contains(rec.Body.String(), "password") {
|
||||
t.Fatal("internal error text leaked to the client")
|
||||
}
|
||||
if !strings.Contains(logs.String(), "db password leaked") {
|
||||
t.Fatal("cause must be logged for operators")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationErrorMapping(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/notfound", "", nil)
|
||||
assertError(t, rec, eb, http.StatusNotFound, "not_found")
|
||||
if eb.Error.Message != "chat not found" {
|
||||
t.Fatalf("message = %q", eb.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessResponseHeadersAndEscaping(t *testing.T) {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
|
||||
t.Fatalf("Content-Type = %q", ct)
|
||||
}
|
||||
if rec.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("missing X-Request-Id on success")
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), `"<a&b>"`) {
|
||||
t.Fatalf("HTML escaping must be off, body %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestIDIsGeneratedNotEchoed(t *testing.T) {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": "client-chosen"})
|
||||
if got := rec.Header().Get("X-Request-Id"); got == "" || got == "client-chosen" {
|
||||
t.Fatalf("X-Request-Id = %q, want a server generated value", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONHappyPath(t *testing.T) {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodPost, "/decode", `{"text":"Привет","count":2}`, map[string]string{"Content-Type": "application/json; charset=utf-8"})
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"Привет"`) {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONFailures(t *testing.T) {
|
||||
jsonCT := map[string]string{"Content-Type": "application/json"}
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
headers map[string]string
|
||||
status int
|
||||
code string
|
||||
contain string
|
||||
}{
|
||||
{"no content type", `{"text":"x"}`, nil, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
|
||||
{"wrong content type", `{"text":"x"}`, map[string]string{"Content-Type": "text/plain"}, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
|
||||
{"empty body", "", jsonCT, http.StatusBadRequest, "invalid_request", "body"},
|
||||
{"malformed", `{"text":`, jsonCT, http.StatusBadRequest, "invalid_request", "malformed"},
|
||||
{"invalid utf-8", "{\"text\":\"bad \xff byte\"}", jsonCT, http.StatusBadRequest, "invalid_request", "UTF-8"},
|
||||
{"unknown field", `{"text":"x","extra":1}`, jsonCT, http.StatusBadRequest, "invalid_request", "extra"},
|
||||
{"wrong type", `{"text":123}`, jsonCT, http.StatusBadRequest, "invalid_request", "text"},
|
||||
{"trailing data", `{"text":"x"} {"text":"y"}`, jsonCT, http.StatusBadRequest, "invalid_request", "after"},
|
||||
{"array instead of object", `[1,2]`, jsonCT, http.StatusBadRequest, "invalid_request", ""},
|
||||
{"too large", `{"text":"` + strings.Repeat("x", 100) + `"}`, jsonCT, http.StatusRequestEntityTooLarge, "payload_too_large", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodPost, "/decode", tc.body, tc.headers)
|
||||
assertError(t, rec, eb, tc.status, tc.code)
|
||||
if tc.contain != "" && !strings.Contains(eb.Error.Message, tc.contain) {
|
||||
t.Fatalf("message %q must mention %q", eb.Error.Message, tc.contain)
|
||||
}
|
||||
if strings.Contains(eb.Error.Message, "httpx_test") || strings.Contains(eb.Error.Message, "payload") {
|
||||
t.Fatalf("message must not leak Go type names: %q", eb.Error.Message)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessLogHasRequestFieldsButNoBody(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
e := newEngine(t, logs)
|
||||
rec, _ := do(t, e, http.MethodPost, "/decode", `{"text":"confidential"}`, map[string]string{"Content-Type": "application/json"})
|
||||
var entry map[string]any
|
||||
line := lastLine(logs.String())
|
||||
if err := json.Unmarshal([]byte(line), &entry); err != nil {
|
||||
t.Fatalf("log line is not JSON: %v: %s", err, line)
|
||||
}
|
||||
for _, key := range []string{"request_id", "method", "path", "status", "duration_ms"} {
|
||||
if _, ok := entry[key]; !ok {
|
||||
t.Errorf("log entry missing %q: %s", key, line)
|
||||
}
|
||||
}
|
||||
if entry["request_id"] != rec.Header().Get("X-Request-Id") {
|
||||
t.Errorf("log request_id %v != header %q", entry["request_id"], rec.Header().Get("X-Request-Id"))
|
||||
}
|
||||
if strings.Contains(logs.String(), "confidential") {
|
||||
t.Fatal("request body must never be logged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessLogLevelFollowsStatus(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
e := newEngineAt(t, logs, slog.LevelInfo)
|
||||
|
||||
do(t, e, http.MethodGet, "/ok", "", nil)
|
||||
if strings.Contains(logs.String(), `"msg":"request"`) {
|
||||
t.Fatalf("successful requests must be logged at debug level only, got %s", logs.String())
|
||||
}
|
||||
do(t, e, http.MethodGet, "/notfound", "", nil)
|
||||
if entry := logEntry(t, logs); entry["level"] != "INFO" || entry["status"] != float64(404) {
|
||||
t.Fatalf("client error must be logged at info level with its status, got %v", entry)
|
||||
}
|
||||
do(t, e, http.MethodGet, "/fail", "", nil)
|
||||
if entry := logEntry(t, logs); entry["level"] != "ERROR" || entry["status"] != float64(500) {
|
||||
t.Fatalf("server error must be logged at error level with its status, got %v", entry)
|
||||
}
|
||||
|
||||
verbose := &bytes.Buffer{}
|
||||
do(t, newEngineAt(t, verbose, slog.LevelDebug), http.MethodGet, "/ok", "", nil)
|
||||
if entry := logEntry(t, verbose); entry["level"] != "DEBUG" || entry["status"] != float64(200) {
|
||||
t.Fatalf("at debug level successful requests must be logged, got %v", entry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
rec, _ := do(t, newEngine(t, logs), http.MethodGet, "/who", "", nil)
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) {
|
||||
t.Fatalf("UserID must return what SetUserID stored: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if entry := logEntry(t, logs); entry["user_id"] != "11111111-1111-4111-8111-111111111111" {
|
||||
t.Fatalf("access log must attribute the request to the user, got %v", entry)
|
||||
}
|
||||
anonymous := &bytes.Buffer{}
|
||||
do(t, newEngine(t, anonymous), http.MethodGet, "/ok", "", nil)
|
||||
if _, present := logEntry(t, anonymous)["user_id"]; present {
|
||||
t.Fatal("anonymous requests must not carry user_id")
|
||||
}
|
||||
}
|
||||
|
||||
func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any {
|
||||
t.Helper()
|
||||
var entry map[string]any
|
||||
line := lastLine(logs.String())
|
||||
if err := json.Unmarshal([]byte(line), &entry); err != nil {
|
||||
t.Fatalf("log line is not JSON: %v: %s", err, line)
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestTimestampFormat(t *testing.T) {
|
||||
ts := time.Date(2026, 9, 1, 12, 0, 0, 0, time.FixedZone("MSK", 3*3600))
|
||||
if got := httpx.Timestamp(ts); got != "2026-09-01T09:00:00.000Z" {
|
||||
t.Fatalf("Timestamp = %q", got)
|
||||
}
|
||||
ts = time.Date(2026, 9, 1, 12, 0, 0, 7_000_000, time.UTC)
|
||||
if got := httpx.Timestamp(ts); got != "2026-09-01T12:00:00.007Z" {
|
||||
t.Fatalf("Timestamp = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func lastLine(s string) string {
|
||||
lines := strings.Split(strings.TrimSpace(s), "\n")
|
||||
return lines[len(lines)-1]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const keyUserID = "messenger.user_id"
|
||||
|
||||
// SetUserID records the identified caller for the handlers behind the
|
||||
// identification middleware and for the access log. It lives here rather
|
||||
// than in the auth package because the access log needs it and auth already
|
||||
// depends on this package.
|
||||
func SetUserID(c *gin.Context, id uuid.UUID) {
|
||||
c.Set(keyUserID, id)
|
||||
}
|
||||
|
||||
func UserID(c *gin.Context) (uuid.UUID, bool) {
|
||||
v, ok := c.Get(keyUserID)
|
||||
if !ok {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
id, ok := v.(uuid.UUID)
|
||||
return id, ok
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// requestID assigns a fresh identifier to every request.
|
||||
//
|
||||
// An incoming X-Request-Id is deliberately not reused. This service is
|
||||
// client-facing: there is no trusted upstream that could have minted the
|
||||
// value, so honouring it would let any caller pick an arbitrary string that
|
||||
// ends up in logs (log injection, unbounded length) or collides with another
|
||||
// request and corrupts log correlation. Reusing the header is the right
|
||||
// choice only when the caller is a trusted proxy or a sibling service that
|
||||
// propagates one id across a chain of calls.
|
||||
func requestID(log *slog.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var raw [16]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
panic("httpx: random source unavailable: " + err.Error())
|
||||
}
|
||||
id := hex.EncodeToString(raw[:])
|
||||
c.Set(keyRequestID, id)
|
||||
c.Set(keyLogger, log)
|
||||
c.Writer.Header().Set("X-Request-Id", id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// accessLog writes one line per request at a level that follows the
|
||||
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
|
||||
// how much traffic is recorded. Headers, query strings and bodies are never
|
||||
// recorded. time.Since uses the monotonic clock, so wall clock adjustments
|
||||
// cannot distort the duration.
|
||||
func accessLog() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
|
||||
status := c.Writer.Status()
|
||||
level := slog.LevelDebug
|
||||
switch {
|
||||
case status >= http.StatusInternalServerError:
|
||||
level = slog.LevelError
|
||||
case status >= http.StatusBadRequest:
|
||||
level = slog.LevelInfo
|
||||
}
|
||||
log := logger(c)
|
||||
ctx := c.Request.Context()
|
||||
if !log.Enabled(ctx, level) {
|
||||
return
|
||||
}
|
||||
attrs := []any{
|
||||
"request_id", RequestID(c),
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"status", status,
|
||||
"duration_ms", float64(time.Since(start).Microseconds()) / 1000,
|
||||
"bytes", c.Writer.Size(),
|
||||
}
|
||||
if id, ok := UserID(c); ok {
|
||||
attrs = append(attrs, "user_id", id.String())
|
||||
}
|
||||
log.Log(ctx, level, "request", attrs...)
|
||||
}
|
||||
}
|
||||
|
||||
// recovery turns a panic into a contract 500; the stack goes to the log only.
|
||||
func recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger(c).Error("panic recovered",
|
||||
"request_id", RequestID(c),
|
||||
"panic", fmt.Sprint(r),
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
if !c.Writer.Written() {
|
||||
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
}
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// bodyLimit caps request bodies; exceeding it surfaces from the JSON
|
||||
// decoder as *http.MaxBytesError.
|
||||
func bodyLimit(maxBytes int64) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Body != nil {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorDetail `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type statusCode struct {
|
||||
status int
|
||||
code string
|
||||
}
|
||||
|
||||
var kinds = map[apperr.Kind]statusCode{
|
||||
apperr.KindInvalid: {http.StatusBadRequest, "invalid_request"},
|
||||
apperr.KindUnauthorized: {http.StatusUnauthorized, "unauthorized"},
|
||||
apperr.KindNotFound: {http.StatusNotFound, "not_found"},
|
||||
apperr.KindConflict: {http.StatusConflict, "conflict"},
|
||||
apperr.KindPayloadTooLarge: {http.StatusRequestEntityTooLarge, "payload_too_large"},
|
||||
apperr.KindUnsupportedMedia: {http.StatusUnsupportedMediaType, "unsupported_media_type"},
|
||||
apperr.KindUnavailable: {http.StatusServiceUnavailable, "unavailable"},
|
||||
}
|
||||
|
||||
// JSON is the single place that fixes the response media type; PureJSON
|
||||
// keeps non-ASCII and HTML characters verbatim.
|
||||
func JSON(c *gin.Context, status int, body any) {
|
||||
c.PureJSON(status, body)
|
||||
}
|
||||
|
||||
// Fail writes the contract error body and stops the handler chain.
|
||||
func Fail(c *gin.Context, status int, code, message string) {
|
||||
JSON(c, status, errorEnvelope{Error: errorDetail{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: RequestID(c),
|
||||
}})
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
// Error maps an application error to its status. Anything that is not an
|
||||
// application error is logged with its text and reported as an opaque 500,
|
||||
// so internal details never reach the client.
|
||||
func Error(c *gin.Context, err error) {
|
||||
mapped, known := kinds[apperr.KindOf(err)]
|
||||
if !known {
|
||||
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
|
||||
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
Fail(c, mapped.status, mapped.code, err.Error())
|
||||
}
|
||||
|
||||
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
|
||||
// (the oldest version the public tests support) only parses 3 or 6 fractional
|
||||
// digits, and RFC3339Nano would trim trailing zeros to a variable width.
|
||||
func Timestamp(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Package ident generates and parses entity identifiers.
|
||||
//
|
||||
// Identifiers are UUIDv7 (RFC 9562): the first 48 bits carry a Unix
|
||||
// millisecond timestamp and google/uuid keeps them strictly increasing within
|
||||
// one process even when the system clock steps backwards, so lexicographic
|
||||
// order of ids equals creation order.
|
||||
package ident
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid uuid")
|
||||
|
||||
// New panics only if the platform random source is unavailable, which is a
|
||||
// fatal environment fault rather than a request error.
|
||||
func New() uuid.UUID {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
panic("ident: random source unavailable: " + err.Error())
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// TimeOf extracts the creation time carried by a UUIDv7 as UTC with
|
||||
// millisecond precision.
|
||||
func TimeOf(id uuid.UUID) time.Time {
|
||||
sec, nsec := id.Time().UnixTime()
|
||||
return time.Unix(sec, nsec).UTC()
|
||||
}
|
||||
|
||||
// Parse accepts only the canonical 36-character form; uuid.Parse alone would
|
||||
// also take braces, urn prefixes and bare hex.
|
||||
func Parse(raw string) (uuid.UUID, error) {
|
||||
if len(raw) != 36 {
|
||||
return uuid.Nil, ErrInvalid
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrInvalid
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package ident_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func TestNewProducesVersion7(t *testing.T) {
|
||||
id := ident.New()
|
||||
if got := id.Version(); got != 7 {
|
||||
t.Fatalf("version = %d, want 7", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewIsStrictlyIncreasingWithinProcess(t *testing.T) {
|
||||
prev := ident.New()
|
||||
for i := 0; i < 20000; i++ {
|
||||
next := ident.New()
|
||||
if bytes.Compare(next[:], prev[:]) <= 0 {
|
||||
t.Fatalf("id %s is not greater than previous %s at iteration %d", next, prev, i)
|
||||
}
|
||||
prev = next
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeOfMatchesWallClockAtMillisecondPrecision(t *testing.T) {
|
||||
before := time.Now().Truncate(time.Millisecond)
|
||||
id := ident.New()
|
||||
after := time.Now().Add(time.Millisecond)
|
||||
|
||||
got := ident.TimeOf(id)
|
||||
if got.Location() != time.UTC {
|
||||
t.Fatalf("TimeOf must return UTC, got %v", got.Location())
|
||||
}
|
||||
if got.Before(before) || got.After(after) {
|
||||
t.Fatalf("TimeOf = %v, want within [%v, %v]", got, before, after)
|
||||
}
|
||||
if got.Nanosecond()%int(time.Millisecond) != 0 {
|
||||
t.Fatalf("TimeOf must be truncated to milliseconds, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAcceptsCanonicalForm(t *testing.T) {
|
||||
id := ident.New()
|
||||
parsed, err := ident.Parse(id.String())
|
||||
if err != nil {
|
||||
t.Fatalf("Parse(%q) error: %v", id, err)
|
||||
}
|
||||
if parsed != id {
|
||||
t.Fatalf("Parse round trip mismatch: %s != %s", parsed, id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsNonCanonicalForms(t *testing.T) {
|
||||
id := ident.New().String()
|
||||
for _, raw := range []string{
|
||||
"",
|
||||
"not-a-uuid",
|
||||
"{" + id + "}",
|
||||
"urn:uuid:" + id,
|
||||
id[:32] + id[33:], // hex without one dash
|
||||
id + "0",
|
||||
" " + id,
|
||||
} {
|
||||
if _, err := ident.Parse(raw); err == nil {
|
||||
t.Errorf("Parse(%q) must fail", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package pagination implements keyset paging. A cursor is opaque to the
|
||||
// client and bound to the resource it pages (the chat for history, the user
|
||||
// for the chat list), so a cursor from one resource is rejected on another.
|
||||
// Because ids are UUIDv7 and creation time derives from the id, the keyset
|
||||
// (created_at, id) collapses to the id of the last returned item.
|
||||
package pagination
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLimit = 50
|
||||
MaxLimit = 100
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrInvalidLimit = errors.New("limit must be an integer between 1 and 100")
|
||||
)
|
||||
|
||||
const cursorVersion = 1
|
||||
|
||||
func EncodeCursor(scope, last uuid.UUID) string {
|
||||
raw := make([]byte, 0, 1+16+16)
|
||||
raw = append(raw, cursorVersion)
|
||||
raw = append(raw, scope[:]...)
|
||||
raw = append(raw, last[:]...)
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func DecodeCursor(token string, scope uuid.UUID) (uuid.UUID, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(raw) != 1+16+16 || raw[0] != cursorVersion {
|
||||
return uuid.Nil, ErrInvalidCursor
|
||||
}
|
||||
if got, err := uuid.FromBytes(raw[1:17]); err != nil || got != scope {
|
||||
return uuid.Nil, ErrInvalidCursor
|
||||
}
|
||||
last, err := uuid.FromBytes(raw[17:])
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrInvalidCursor
|
||||
}
|
||||
return last, nil
|
||||
}
|
||||
|
||||
// ParseLimit accepts an unsigned decimal between 1 and MaxLimit; an empty
|
||||
// value means DefaultLimit. ParseUint rejects signs, whitespace and
|
||||
// fractions and reports overflow, so no length guard is needed.
|
||||
func ParseLimit(raw string) (int, error) {
|
||||
if raw == "" {
|
||||
return DefaultLimit, nil
|
||||
}
|
||||
n, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil || n < 1 || n > MaxLimit {
|
||||
return 0, ErrInvalidLimit
|
||||
}
|
||||
return int(n), nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package pagination_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
scope, last := ident.New(), ident.New()
|
||||
encoded := pagination.EncodeCursor(scope, last)
|
||||
if encoded == "" || strings.ContainsAny(encoded, "+/=") {
|
||||
t.Fatalf("cursor must be non-empty URL-safe base64 without padding, got %q", encoded)
|
||||
}
|
||||
got, err := pagination.DecodeCursor(encoded, scope)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeCursor error: %v", err)
|
||||
}
|
||||
if got != last {
|
||||
t.Fatalf("decoded %s, want %s", got, last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCursorRejectsForeignScope(t *testing.T) {
|
||||
encoded := pagination.EncodeCursor(ident.New(), ident.New())
|
||||
_, err := pagination.DecodeCursor(encoded, ident.New())
|
||||
if !errors.Is(err, pagination.ErrInvalidCursor) {
|
||||
t.Fatalf("err = %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCursorRejectsGarbage(t *testing.T) {
|
||||
scope := ident.New()
|
||||
valid := pagination.EncodeCursor(scope, ident.New())
|
||||
for _, raw := range []string{"", "***", "abc", valid[:len(valid)-2], valid + "AA", strings.ToUpper(valid)} {
|
||||
if _, err := pagination.DecodeCursor(raw, scope); !errors.Is(err, pagination.ErrInvalidCursor) {
|
||||
t.Errorf("DecodeCursor(%q) err = %v, want ErrInvalidCursor", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
want int
|
||||
ok bool
|
||||
}{
|
||||
{"", 50, true},
|
||||
{"1", 1, true},
|
||||
{"100", 100, true},
|
||||
{"0", 0, false},
|
||||
{"101", 0, false},
|
||||
{"-1", 0, false},
|
||||
{"+5", 0, false},
|
||||
{"5.0", 0, false},
|
||||
{"abc", 0, false},
|
||||
{" 5", 0, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := pagination.ParseLimit(tc.raw)
|
||||
if tc.ok && (err != nil || got != tc.want) {
|
||||
t.Errorf("ParseLimit(%q) = %d, %v; want %d", tc.raw, got, err, tc.want)
|
||||
}
|
||||
if !tc.ok && !errors.Is(err, pagination.ErrInvalidLimit) {
|
||||
t.Errorf("ParseLimit(%q) err = %v, want ErrInvalidLimit", tc.raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package pagination
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
// Page is the service-level page: the items and the id to continue from,
|
||||
// nil when the listing is exhausted. It carries the raw keyset id so that any
|
||||
// transport can encode the continuation its own way.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
Next *uuid.UUID
|
||||
}
|
||||
|
||||
// PageResponse is the wire form of a page with the continuation already
|
||||
// encoded as an opaque cursor.
|
||||
type PageResponse[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// Cut turns a slice over-fetched by one item into a page of at most limit
|
||||
// items; the extra item only proves that a next page exists.
|
||||
func Cut[T any](items []T, limit int, id func(T) uuid.UUID) Page[T] {
|
||||
if len(items) <= limit {
|
||||
return Page[T]{Items: items}
|
||||
}
|
||||
items = items[:limit]
|
||||
next := id(items[limit-1])
|
||||
return Page[T]{Items: items, Next: &next}
|
||||
}
|
||||
|
||||
func ToResponse[D, R any](p Page[D], scope uuid.UUID, convert func(D) R) PageResponse[R] {
|
||||
out := PageResponse[R]{Items: make([]R, 0, len(p.Items))}
|
||||
for _, item := range p.Items {
|
||||
out.Items = append(out.Items, convert(item))
|
||||
}
|
||||
if p.Next != nil {
|
||||
cursor := EncodeCursor(scope, *p.Next)
|
||||
out.NextCursor = &cursor
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package pagination_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
func self(id uuid.UUID) uuid.UUID { return id }
|
||||
|
||||
func TestCutTrimsOverfetchAndDerivesNext(t *testing.T) {
|
||||
ids := []uuid.UUID{ident.New(), ident.New(), ident.New()}
|
||||
|
||||
fewer := pagination.Cut(ids[:2], 5, self)
|
||||
if len(fewer.Items) != 2 || fewer.Next != nil {
|
||||
t.Fatalf("fewer than limit: %+v", fewer)
|
||||
}
|
||||
exact := pagination.Cut(ids[:2], 2, self)
|
||||
if len(exact.Items) != 2 || exact.Next != nil {
|
||||
t.Fatalf("exactly limit must not continue: %+v", exact)
|
||||
}
|
||||
over := pagination.Cut(ids, 2, self)
|
||||
if len(over.Items) != 2 || over.Next == nil || *over.Next != ids[1] {
|
||||
t.Fatalf("over-fetched page must trim and continue from the last kept id: %+v", over)
|
||||
}
|
||||
if over.Items[0] != ids[0] || over.Items[1] != ids[1] {
|
||||
t.Fatalf("order changed: %v", over.Items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToResponseEncodesCursorWithinScope(t *testing.T) {
|
||||
scope, last := ident.New(), ident.New()
|
||||
page := pagination.Page[uuid.UUID]{Items: []uuid.UUID{last}, Next: &last}
|
||||
res := pagination.ToResponse(page, scope, func(id uuid.UUID) string { return id.String() })
|
||||
if len(res.Items) != 1 || res.Items[0] != last.String() {
|
||||
t.Fatalf("items = %v", res.Items)
|
||||
}
|
||||
if res.NextCursor == nil {
|
||||
t.Fatal("next cursor missing")
|
||||
}
|
||||
got, err := pagination.DecodeCursor(*res.NextCursor, scope)
|
||||
if err != nil || got != last {
|
||||
t.Fatalf("cursor decodes to %s, %v; want %s", got, err, last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToResponseSerializesEmptyPageAsContractRequires(t *testing.T) {
|
||||
res := pagination.ToResponse(pagination.Page[uuid.UUID]{}, ident.New(), func(id uuid.UUID) string { return id.String() })
|
||||
raw, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(raw) != `{"items":[],"next_cursor":null}` {
|
||||
t.Fatalf("empty page = %s", raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Package server runs the HTTP listener with the lifecycle the lab
|
||||
// requires: readiness drops first, the listener stops accepting, in-flight
|
||||
// requests drain within a bounded timeout, then the process exits.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"messenger/internal/app"
|
||||
)
|
||||
|
||||
// Run serves until ctx is cancelled, then shuts down within shutdownTimeout.
|
||||
func Run(ctx context.Context, log *slog.Logger, ln net.Listener, a *app.App, shutdownTimeout time.Duration) error {
|
||||
srv := &http.Server{
|
||||
Handler: a.Engine,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 64 * 1024,
|
||||
ErrorLog: slog.NewLogLogger(log.Handler(), slog.LevelWarn),
|
||||
}
|
||||
|
||||
served := make(chan error, 1)
|
||||
go func() {
|
||||
err := srv.Serve(ln)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
err = nil
|
||||
}
|
||||
served <- err
|
||||
}()
|
||||
log.Info("listening", "addr", ln.Addr().String())
|
||||
|
||||
select {
|
||||
case err := <-served:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
log.Info("shutdown started", "timeout", shutdownTimeout.String())
|
||||
a.Health.SetReady(false)
|
||||
drain, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(drain); err != nil {
|
||||
log.Error("shutdown forced", "error", err.Error())
|
||||
_ = srv.Close()
|
||||
return err
|
||||
}
|
||||
<-served
|
||||
log.Info("shutdown completed")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/app"
|
||||
"messenger/internal/server"
|
||||
)
|
||||
|
||||
func TestServesUntilContextCancelledThenStopsCleanly(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
a := app.New(log, 1024)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- server.Run(ctx, log, ln, a, 5*time.Second) }()
|
||||
|
||||
base := "http://" + ln.Addr().String()
|
||||
waitFor(t, base+"/health/ready", http.StatusOK)
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("Run returned error: %v", err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("Run did not stop within 10s after cancel")
|
||||
}
|
||||
if _, err := http.Get(base + "/health/live"); err == nil {
|
||||
t.Fatal("listener must be closed after shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessDropsBeforeListenerCloses(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
a := app.New(log, 1024)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- server.Run(ctx, log, ln, a, 5*time.Second) }()
|
||||
base := "http://" + ln.Addr().String()
|
||||
waitFor(t, base+"/health/ready", http.StatusOK)
|
||||
|
||||
// Hold one request open so shutdown has something to drain.
|
||||
slow := make(chan struct{})
|
||||
go func() {
|
||||
resp, err := http.Get(base + "/health/live")
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
close(slow)
|
||||
}()
|
||||
|
||||
cancel()
|
||||
<-done
|
||||
<-slow
|
||||
if !a.Health.IsReady() {
|
||||
return
|
||||
}
|
||||
t.Fatal("readiness must be switched off during shutdown")
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, url string, status int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := http.Get(url)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == status {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%s did not return %d in time", url, status)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/platform/httpx"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
users *Service
|
||||
}
|
||||
|
||||
func NewHandler(users *Service) *Handler {
|
||||
return &Handler{users: users}
|
||||
}
|
||||
|
||||
// Register mounts registration on the public router and the current-user
|
||||
// endpoint on the router guarded by RequireUser.
|
||||
func (h *Handler) Register(public, protected gin.IRouter) {
|
||||
public.POST("/users", h.register)
|
||||
protected.GET("/users/me", auth.WithUser(h.me))
|
||||
}
|
||||
|
||||
type createRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func ToResponse(u User) Response {
|
||||
return Response{
|
||||
ID: u.ID.String(),
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: httpx.Timestamp(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) register(c *gin.Context) {
|
||||
var req createRequest
|
||||
if err := httpx.DecodeJSON(c, &req); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusCreated, ToResponse(u))
|
||||
}
|
||||
|
||||
func (h *Handler) me(c *gin.Context, actor uuid.UUID) {
|
||||
u, err := h.users.GetByID(c.Request.Context(), actor)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, ToResponse(u))
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
// Create stores a new user or returns ErrUsernameTaken; the uniqueness
|
||||
// check and the insert must be atomic.
|
||||
Create(ctx context.Context, user User) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (User, error)
|
||||
// ExistingIDs returns the subset of ids that belong to registered users,
|
||||
// in input order, in one round trip.
|
||||
ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo Repository
|
||||
}
|
||||
|
||||
func NewService(repo Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, username, displayName string) (User, error) {
|
||||
u, err := New(ident.New(), username, displayName)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if err := s.repo.Create(ctx, u); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (User, error) {
|
||||
return s.repo.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Exists serves the identification middleware; it is the single-id form of
|
||||
// ExistingIDs so existence is answered by one code path.
|
||||
func (s *Service) Exists(ctx context.Context, id uuid.UUID) (bool, error) {
|
||||
found, err := s.ExistingIDs(ctx, []uuid.UUID{id})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return len(found) == 1, nil
|
||||
}
|
||||
|
||||
// ExistingIDs serves the chats module when it validates member lists.
|
||||
func (s *Service) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
if len(ids) == 0 {
|
||||
return []uuid.UUID{}, nil
|
||||
}
|
||||
found, err := s.repo.ExistingIDs(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("user lookup: %w", err)
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package user_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/user"
|
||||
"messenger/internal/user/store"
|
||||
)
|
||||
|
||||
func newService() *user.Service {
|
||||
return user.NewService(store.NewInMemUsers())
|
||||
}
|
||||
|
||||
func TestRegisterStoresUser(t *testing.T) {
|
||||
svc := newService()
|
||||
ctx := context.Background()
|
||||
u, err := svc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("Register error: %v", err)
|
||||
}
|
||||
if u.ID.Version() != 7 {
|
||||
t.Fatalf("id must be UUIDv7, got version %d", u.ID.Version())
|
||||
}
|
||||
got, err := svc.GetByID(ctx, u.ID)
|
||||
if err != nil || got != u {
|
||||
t.Fatalf("GetByID = %+v, %v; want %+v", got, err, u)
|
||||
}
|
||||
if ok, err := svc.Exists(ctx, u.ID); err != nil || !ok {
|
||||
t.Fatalf("Exists = %v, %v; want true", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterRejectsInvalidInput(t *testing.T) {
|
||||
_, err := newService().Register(context.Background(), "Bad Name", "x")
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatalf("kind = %v, want KindInvalid (%v)", apperr.KindOf(err), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterReportsDuplicateAsConflict(t *testing.T) {
|
||||
svc := newService()
|
||||
ctx := context.Background()
|
||||
if _, err := svc.Register(ctx, "alice", "A"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := svc.Register(ctx, "alice", "B")
|
||||
if !errors.Is(err, user.ErrUsernameTaken) || apperr.KindOf(err) != apperr.KindConflict {
|
||||
t.Fatalf("err = %v, want ErrUsernameTaken with KindConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetByIDUnknownIsNotFound(t *testing.T) {
|
||||
svc := newService()
|
||||
_, err := svc.GetByID(context.Background(), ident.New())
|
||||
if !errors.Is(err, user.ErrNotFound) || apperr.KindOf(err) != apperr.KindNotFound {
|
||||
t.Fatalf("err = %v, want ErrNotFound with KindNotFound", err)
|
||||
}
|
||||
if ok, err := svc.Exists(context.Background(), ident.New()); err != nil || ok {
|
||||
t.Fatalf("Exists = %v, %v; want false, nil", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExistingIDsFiltersInOneCall(t *testing.T) {
|
||||
svc := newService()
|
||||
ctx := context.Background()
|
||||
alice, _ := svc.Register(ctx, "alice", "A")
|
||||
bob, _ := svc.Register(ctx, "bob", "B")
|
||||
unknown := ident.New()
|
||||
got, err := svc.ExistingIDs(ctx, []uuid.UUID{unknown, bob.ID, alice.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0] != bob.ID || got[1] != alice.ID {
|
||||
t.Fatalf("ExistingIDs = %v, want bob then alice", got)
|
||||
}
|
||||
if empty, err := svc.ExistingIDs(ctx, nil); err != nil || len(empty) != 0 {
|
||||
t.Fatalf("ExistingIDs(nil) = %v, %v", empty, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package store holds the repository implementations of the users module.
|
||||
// inmem.go is the in-process one: state lives only in this process and
|
||||
// disappears with it by design of the lab.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
type InMemUsers struct {
|
||||
mu sync.RWMutex
|
||||
byID map[uuid.UUID]user.User
|
||||
byUsername map[string]struct{}
|
||||
}
|
||||
|
||||
var _ user.Repository = (*InMemUsers)(nil)
|
||||
|
||||
func NewInMemUsers() *InMemUsers {
|
||||
return &InMemUsers{
|
||||
byID: make(map[uuid.UUID]user.User),
|
||||
byUsername: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Create checks and inserts under the same write lock, so concurrent
|
||||
// registrations of one username admit exactly one winner.
|
||||
func (r *InMemUsers) Create(_ context.Context, u user.User) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, taken := r.byUsername[u.Username]; taken {
|
||||
return user.ErrUsernameTaken
|
||||
}
|
||||
r.byUsername[u.Username] = struct{}{}
|
||||
r.byID[u.ID] = u
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemUsers) GetByID(_ context.Context, id uuid.UUID) (user.User, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
u, ok := r.byID[id]
|
||||
if !ok {
|
||||
return user.User{}, user.ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (r *InMemUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
found := make([]uuid.UUID, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, ok := r.byID[id]; ok {
|
||||
found = append(found, id)
|
||||
}
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/user"
|
||||
"messenger/internal/user/store"
|
||||
)
|
||||
|
||||
func mustUser(t *testing.T, username string) user.User {
|
||||
t.Helper()
|
||||
u, err := user.New(ident.New(), username, "Display")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func TestCreateThenGetByID(t *testing.T) {
|
||||
repo := store.NewInMemUsers()
|
||||
ctx := context.Background()
|
||||
u := mustUser(t, "alice")
|
||||
if err := repo.Create(ctx, u); err != nil {
|
||||
t.Fatalf("Create error: %v", err)
|
||||
}
|
||||
got, err := repo.GetByID(ctx, u.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByID error: %v", err)
|
||||
}
|
||||
if got != u {
|
||||
t.Fatalf("GetByID = %+v, want %+v", got, u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetByIDUnknownReturnsErrNotFound(t *testing.T) {
|
||||
_, err := store.NewInMemUsers().GetByID(context.Background(), ident.New())
|
||||
if !errors.Is(err, user.ErrNotFound) {
|
||||
t.Fatalf("err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRejectsDuplicateUsername(t *testing.T) {
|
||||
repo := store.NewInMemUsers()
|
||||
ctx := context.Background()
|
||||
if err := repo.Create(ctx, mustUser(t, "alice")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := repo.Create(ctx, mustUser(t, "alice"))
|
||||
if !errors.Is(err, user.ErrUsernameTaken) {
|
||||
t.Fatalf("err = %v, want ErrUsernameTaken", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateIsAtomicUnderConcurrency(t *testing.T) {
|
||||
repo := store.NewInMemUsers()
|
||||
ctx := context.Background()
|
||||
const workers = 50
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
created := 0
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := repo.Create(ctx, mustUser(t, "same_name")); err == nil {
|
||||
mu.Lock()
|
||||
created++
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if created != 1 {
|
||||
t.Fatalf("exactly one Create must win, got %d", created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExistingIDsReturnsOnlyKnownIDs(t *testing.T) {
|
||||
repo := store.NewInMemUsers()
|
||||
ctx := context.Background()
|
||||
alice, bob := mustUser(t, "alice"), mustUser(t, "bob")
|
||||
_ = repo.Create(ctx, alice)
|
||||
_ = repo.Create(ctx, bob)
|
||||
got, err := repo.ExistingIDs(ctx, []uuid.UUID{ident.New(), bob.ID, alice.ID, bob.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 3 || got[0] != bob.ID || got[1] != alice.ID || got[2] != bob.ID {
|
||||
t.Fatalf("ExistingIDs must keep input order and drop unknown ids, got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Package user is the users module. The entity mirrors the future table row
|
||||
// and carries no behaviour; New only enforces input invariants and CreatedAt
|
||||
// derives from the UUIDv7 id.
|
||||
package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
const MaxDisplayNameCodePoints = 100
|
||||
|
||||
var (
|
||||
ErrNotFound = apperr.NotFound("user not found")
|
||||
ErrUsernameTaken = apperr.Conflict("username already taken")
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func New(id uuid.UUID, username, displayName string) (User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return User{}, apperr.Invalid("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return User{}, apperr.Invalid("display_name must not be blank")
|
||||
}
|
||||
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
|
||||
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
|
||||
}
|
||||
return User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: ident.TimeOf(id),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package user_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
func TestNewDerivesCreatedAtFromID(t *testing.T) {
|
||||
id := ident.New()
|
||||
u, err := user.New(id, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("New error: %v", err)
|
||||
}
|
||||
if u.ID != id || u.Username != "alice" || u.DisplayName != "Алиса" {
|
||||
t.Fatalf("unexpected user %+v", u)
|
||||
}
|
||||
if !u.CreatedAt.Equal(ident.TimeOf(id)) {
|
||||
t.Fatalf("CreatedAt = %v, want %v", u.CreatedAt, ident.TimeOf(id))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewValidatesUsername(t *testing.T) {
|
||||
valid := []string{"abc", "a_1", strings.Repeat("a", 32), "user_2026"}
|
||||
for _, name := range valid {
|
||||
if _, err := user.New(ident.New(), name, "ok"); err != nil {
|
||||
t.Errorf("username %q must be accepted: %v", name, err)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "al ice", "алиса", "a-b", "a.b", " abc", "abc\n"}
|
||||
for _, name := range invalid {
|
||||
_, err := user.New(ident.New(), name, "ok")
|
||||
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "username") {
|
||||
t.Errorf("username %q must be rejected as invalid naming the field, got %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewValidatesDisplayNameByCodePoints(t *testing.T) {
|
||||
valid := []string{"A", "Алиса", strings.Repeat("я", 100), "👋 hi"}
|
||||
for _, name := range valid {
|
||||
if _, err := user.New(ident.New(), "alice", name); err != nil {
|
||||
t.Errorf("display_name %q must be accepted: %v", name, err)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101)}
|
||||
for _, name := range invalid {
|
||||
_, err := user.New(ident.New(), "alice", name)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "display_name") {
|
||||
t.Errorf("display_name %q must be rejected as invalid naming the field, got %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user