From 196e118ede601cdab365d7afe0e7a39c68227d69 Mon Sep 17 00:00:00 2001 From: myDan Date: Thu, 29 Oct 2026 10:47:47 +0300 Subject: [PATCH 1/5] chore(solution): pull lab1 solution --- .dockerignore | 11 ++ Dockerfile | 17 ++ cmd/server/main.go | 59 +++++++ go.mod | 5 + go.sum | 2 + internal/config/config.go | 29 ++++ internal/domain/domain.go | 55 +++++++ internal/domain/errors.go | 10 ++ internal/handler/chats.go | 104 ++++++++++++ internal/handler/cursor.go | 34 ++++ internal/handler/dto.go | 111 +++++++++++++ internal/handler/errors.go | 48 ++++++ internal/handler/handler.go | 27 ++++ internal/handler/handler_test.go | 237 ++++++++++++++++++++++++++++ internal/handler/health.go | 11 ++ internal/handler/json.go | 86 ++++++++++ internal/handler/messages.go | 45 ++++++ internal/handler/middleware.go | 91 +++++++++++ internal/handler/users.go | 25 +++ internal/repository/memory/store.go | 133 ++++++++++++++++ internal/router/router.go | 35 ++++ internal/service/chats.go | 81 ++++++++++ internal/service/messages.go | 60 +++++++ internal/service/ports.go | 29 ++++ internal/service/users.go | 48 ++++++ internal/service/validate.go | 31 ++++ 26 files changed, 1424 insertions(+) create mode 100644 Dockerfile create mode 100644 cmd/server/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/config/config.go create mode 100644 internal/domain/domain.go create mode 100644 internal/domain/errors.go create mode 100644 internal/handler/chats.go create mode 100644 internal/handler/cursor.go create mode 100644 internal/handler/dto.go create mode 100644 internal/handler/errors.go create mode 100644 internal/handler/handler.go create mode 100644 internal/handler/handler_test.go create mode 100644 internal/handler/health.go create mode 100644 internal/handler/json.go create mode 100644 internal/handler/messages.go create mode 100644 internal/handler/middleware.go create mode 100644 internal/handler/users.go create mode 100644 internal/repository/memory/store.go create mode 100644 internal/router/router.go create mode 100644 internal/service/chats.go create mode 100644 internal/service/messages.go create mode 100644 internal/service/ports.go create mode 100644 internal/service/users.go create mode 100644 internal/service/validate.go diff --git a/.dockerignore b/.dockerignore index bc16e556..11aa4498 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,14 @@ __pycache__ node_modules evidence .DS_Store +assets +contracts +examples +scripts +tests +*.md +Makefile +lab.json +requirements-dev.txt +Dockerfile* +.dockerignore diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..c6ef4eea --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM golang:1.27.1-alpine3.24 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd ./cmd +COPY internal ./internal +RUN CGO_ENABLED=0 go build -trimpath -o /out/server ./cmd/server + +FROM alpine:3.24.1 +RUN adduser -D -H -u 10001 app +COPY --from=build /out/server /usr/local/bin/server +USER app +ENV APP_HOST=0.0.0.0 APP_PORT=8080 +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/ready" || exit 1 +ENTRYPOINT ["/usr/local/bin/server"] diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..8cb8030e --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,59 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "messenger/internal/config" + "messenger/internal/handler" + "messenger/internal/repository/memory" + "messenger/internal/router" + "messenger/internal/service" +) + +const shutdownTimeout = 5 * time.Second + +func main() { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + cfg := config.Load() + + store := memory.New() + users := service.NewUserService(store) + chats := service.NewChatService(store) + messages := service.NewMessageService(chats, store) + + srv := &http.Server{ + Addr: cfg.Addr(), + Handler: router.New(handler.New(users, chats, messages, log)), + ReadHeaderTimeout: 5 * time.Second, + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) + defer stop() + + go func() { + log.Info("starting server", "addr", srv.Addr, "env", cfg.Env) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Error("server failed", "err", err) + os.Exit(1) + } + }() + + <-ctx.Done() + log.Info("shutdown signal received", "timeout", shutdownTimeout.String()) + + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + err := srv.Shutdown(shutdownCtx) + cancel() + if err != nil { + log.Error("graceful shutdown failed", "err", err) + os.Exit(1) + } + log.Info("server stopped") +} diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..d551bc37 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module messenger + +go 1.27.1 + +require github.com/go-chi/chi/v5 v5.3.2 diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..5a3b06d3 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= +github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 00000000..f6d50973 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,29 @@ +package config + +import ( + "net" + "os" +) + +type Config struct { + Host string + Port string + Env string +} + +func Load() Config { + return Config{ + Host: getenv("APP_HOST", "0.0.0.0"), + Port: getenv("APP_PORT", "8080"), + Env: getenv("APP_ENV", "lab"), + } +} + +func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) } + +func getenv(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} diff --git a/internal/domain/domain.go b/internal/domain/domain.go new file mode 100644 index 00000000..979219a2 --- /dev/null +++ b/internal/domain/domain.go @@ -0,0 +1,55 @@ +package domain + +import ( + "time" + "uuid" +) + +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} + +func (c Chat) HasMember(userID uuid.UUID) bool { + for _, id := range c.MemberIDs { + if id == userID { + return true + } + } + return false +} + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +type Cursor struct { + Scope uuid.UUID + CreatedAt time.Time + ID uuid.UUID +} + +func CompareKey(aTime time.Time, aID uuid.UUID, bTime time.Time, bID uuid.UUID) int { + if c := aTime.Compare(bTime); c != 0 { + return c + } + return aID.Compare(bID) +} + +type Page[T any] struct { + Items []T + Next *Cursor +} diff --git a/internal/domain/errors.go b/internal/domain/errors.go new file mode 100644 index 00000000..888f0de2 --- /dev/null +++ b/internal/domain/errors.go @@ -0,0 +1,10 @@ +package domain + +import "errors" + +var ( + ErrInvalidInput = errors.New("invalid input") + ErrUnauthorized = errors.New("unauthorized") + ErrNotFound = errors.New("not found") + ErrConflict = errors.New("conflict") +) diff --git a/internal/handler/chats.go b/internal/handler/chats.go new file mode 100644 index 00000000..c655ab00 --- /dev/null +++ b/internal/handler/chats.go @@ -0,0 +1,104 @@ +package handler + +import ( + "net/http" + "strconv" + "uuid" + + "github.com/go-chi/chi/v5" + + "messenger/internal/domain" + "messenger/internal/service" +) + +func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { + var req createChatRequest + if err := decodeJSON(w, r, &req); err != nil { + h.fail(w, r, err) + return + } + if req.Title == nil || req.MemberIDs == nil { + h.fail(w, r, badRequest("title and member_ids are required")) + return + } + memberIDs := make([]uuid.UUID, len(*req.MemberIDs)) + for i, s := range *req.MemberIDs { + id, ok := parseUUID(s) + if !ok { + h.fail(w, r, badRequest("member_ids must contain UUIDs")) + return + } + memberIDs[i] = id + } + chat, err := h.chats.Create(r.Context(), actor(r), *req.Title, memberIDs) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toChatResponse(chat)) +} + +func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { + limit, cursor, err := pageParams(r) + if err != nil { + h.fail(w, r, err) + return + } + page, err := h.chats.List(r.Context(), actor(r), cursor, limit) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusOK, toPageResponse(page, toChatResponse)) +} + +func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { + chatID, err := chatIDParam(r) + if err != nil { + h.fail(w, r, err) + return + } + chat, err := h.chats.Get(r.Context(), actor(r), chatID) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusOK, toChatResponse(chat)) +} + +func chatIDParam(r *http.Request) (uuid.UUID, error) { + id, ok := parseUUID(chi.URLParam(r, "chat_id")) + if !ok { + return uuid.UUID{}, badRequest("chat_id must be a UUID") + } + return id, nil +} + +func parseUUID(s string) (uuid.UUID, bool) { + if len(s) != 36 { + return uuid.UUID{}, false + } + id, err := uuid.Parse(s) + return id, err == nil +} + +func pageParams(r *http.Request) (int, *domain.Cursor, error) { + q := r.URL.Query() + limit := service.DefaultLimit + if q.Has("limit") { + n, err := strconv.Atoi(q.Get("limit")) + if err != nil { + return 0, nil, badRequest("limit must be an integer") + } + limit = n + } + var cursor *domain.Cursor + if q.Has("cursor") { + c, ok := decodeCursor(q.Get("cursor")) + if !ok { + return 0, nil, badRequest("invalid cursor") + } + cursor = &c + } + return limit, cursor, nil +} diff --git a/internal/handler/cursor.go b/internal/handler/cursor.go new file mode 100644 index 00000000..94c3f7ff --- /dev/null +++ b/internal/handler/cursor.go @@ -0,0 +1,34 @@ +package handler + +import ( + "encoding/base64" + "strconv" + "strings" + "time" + "uuid" + + "messenger/internal/domain" +) + +func encodeCursor(c domain.Cursor) string { + raw := c.Scope.String() + "." + strconv.FormatInt(c.CreatedAt.UnixMicro(), 10) + "." + c.ID.String() + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func decodeCursor(s string) (domain.Cursor, bool) { + raw, err := base64.RawURLEncoding.DecodeString(s) + if err != nil { + return domain.Cursor{}, false + } + parts := strings.Split(string(raw), ".") + if len(parts) != 3 { + return domain.Cursor{}, false + } + scope, err1 := uuid.Parse(parts[0]) + micros, err2 := strconv.ParseInt(parts[1], 10, 64) + id, err3 := uuid.Parse(parts[2]) + if err1 != nil || err2 != nil || err3 != nil { + return domain.Cursor{}, false + } + return domain.Cursor{Scope: scope, CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, true +} diff --git a/internal/handler/dto.go b/internal/handler/dto.go new file mode 100644 index 00000000..eac64da0 --- /dev/null +++ b/internal/handler/dto.go @@ -0,0 +1,111 @@ +package handler + +import ( + "time" + + "messenger/internal/domain" +) + +type createUserRequest struct { + Username *string `json:"username"` + DisplayName *string `json:"display_name"` +} + +type createChatRequest struct { + Title *string `json:"title"` + MemberIDs *[]string `json:"member_ids"` +} + +type createMessageRequest struct { + Text *string `json:"text"` +} + +type userResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} + +type chatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} + +type messageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} + +type pageResponse[T any] struct { + Items []T `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type healthResponse struct { + Status string `json:"status"` +} + +type errorBody struct { + Error errorDetails `json:"error"` +} + +type errorDetails struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +const timeLayout = "2006-01-02T15:04:05.000000Z" + +func formatTime(t time.Time) string { return t.UTC().Format(timeLayout) } + +func toUserResponse(u domain.User) userResponse { + return userResponse{ + ID: u.ID.String(), + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: formatTime(u.CreatedAt), + } +} + +func toChatResponse(c domain.Chat) chatResponse { + members := make([]string, len(c.MemberIDs)) + for i, id := range c.MemberIDs { + members[i] = id.String() + } + return chatResponse{ + ID: c.ID.String(), + Title: c.Title, + MemberIDs: members, + CreatedAt: formatTime(c.CreatedAt), + } +} + +func toMessageResponse(m domain.Message) messageResponse { + return messageResponse{ + ID: m.ID.String(), + ChatID: m.ChatID.String(), + SenderID: m.SenderID.String(), + Text: m.Text, + CreatedAt: formatTime(m.CreatedAt), + } +} + +func toPageResponse[D, R any](p domain.Page[D], conv func(D) R) pageResponse[R] { + items := make([]R, len(p.Items)) + for i, it := range p.Items { + items[i] = conv(it) + } + resp := pageResponse[R]{Items: items} + if p.Next != nil { + s := encodeCursor(*p.Next) + resp.NextCursor = &s + } + return resp +} diff --git a/internal/handler/errors.go b/internal/handler/errors.go new file mode 100644 index 00000000..da0ff9c9 --- /dev/null +++ b/internal/handler/errors.go @@ -0,0 +1,48 @@ +package handler + +import ( + "errors" + "net/http" + + "messenger/internal/domain" +) + +type apiError struct { + status int + code string + message string +} + +func (e *apiError) Error() string { return e.message } + +func badRequest(msg string) *apiError { + return &apiError{http.StatusBadRequest, "invalid_request", msg} +} + +func writeError(w http.ResponseWriter, status int, code, message string) { + writeJSON(w, status, errorBody{Error: errorDetails{ + Code: code, + Message: message, + RequestID: w.Header().Get(headerRequestID), + }}) +} + +func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) { + var ae *apiError + switch { + case errors.As(err, &ae): + writeError(w, ae.status, ae.code, ae.message) + case errors.Is(err, domain.ErrInvalidInput): + writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) + case errors.Is(err, domain.ErrUnauthorized): + writeError(w, http.StatusUnauthorized, "unauthorized", "valid X-User-Id header is required") + case errors.Is(err, domain.ErrNotFound): + writeError(w, http.StatusNotFound, "not_found", "resource not found") + case errors.Is(err, domain.ErrConflict): + writeError(w, http.StatusConflict, "conflict", "username is already taken") + default: + h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID), + "method", r.Method, "path", r.URL.Path, "err", err) + writeError(w, http.StatusInternalServerError, "internal_error", "internal server error") + } +} diff --git a/internal/handler/handler.go b/internal/handler/handler.go new file mode 100644 index 00000000..42cb1b4a --- /dev/null +++ b/internal/handler/handler.go @@ -0,0 +1,27 @@ +package handler + +import ( + "log/slog" + "net/http" + + "messenger/internal/service" +) + +type Handler struct { + users *service.UserService + chats *service.ChatService + messages *service.MessageService + log *slog.Logger +} + +func New(users *service.UserService, chats *service.ChatService, messages *service.MessageService, log *slog.Logger) *Handler { + return &Handler{users: users, chats: chats, messages: messages, log: log} +} + +func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) { + writeError(w, http.StatusNotFound, "not_found", "resource not found") +} + +func (h *Handler) MethodNotAllowed(w http.ResponseWriter, _ *http.Request) { + writeError(w, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") +} diff --git a/internal/handler/handler_test.go b/internal/handler/handler_test.go new file mode 100644 index 00000000..bea64193 --- /dev/null +++ b/internal/handler/handler_test.go @@ -0,0 +1,237 @@ +package handler_test + +import ( + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "messenger/internal/handler" + "messenger/internal/repository/memory" + "messenger/internal/router" + "messenger/internal/service" +) + +func newServer(t *testing.T) *httptest.Server { + t.Helper() + store := memory.New() + users := service.NewUserService(store) + chats := service.NewChatService(store) + messages := service.NewMessageService(chats, store) + srv := httptest.NewServer(router.New(handler.New(users, chats, messages, slog.New(slog.DiscardHandler)))) + t.Cleanup(srv.Close) + return srv +} + +func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (int, map[string]any) { + t.Helper() + req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + if userID != "" { + req.Header.Set("X-User-Id", userID) + } + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var out map[string]any + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("%s %s: invalid JSON response: %v", method, path, err) + } + return resp.StatusCode, out +} + +func errorCode(body map[string]any) string { + e, _ := body["error"].(map[string]any) + code, _ := e["code"].(string) + return code +} + +func createUser(t *testing.T, srv *httptest.Server, username string) string { + t.Helper() + status, body := do(t, srv, http.MethodPost, "/api/v1/users", "", + fmt.Sprintf(`{"username":%q,"display_name":"Test"}`, username)) + if status != http.StatusCreated { + t.Fatalf("create user %s: status %d", username, status) + } + return body["id"].(string) +} + +func createChat(t *testing.T, srv *httptest.Server, owner string, members ...string) string { + t.Helper() + ids, _ := json.Marshal(members) + status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner, + fmt.Sprintf(`{"title":"Test","member_ids":%s}`, ids)) + if status != http.StatusCreated { + t.Fatalf("create chat: status %d", status) + } + return body["id"].(string) +} + +func TestInvalidJSON(t *testing.T) { + srv := newServer(t) + for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x"}`} { + status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body) + if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" { + t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp)) + } + } +} + +func TestForeignChat(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + bob := createUser(t, srv, "bob") + eve := createUser(t, srv, "eve") + chat := createChat(t, srv, alice, alice, bob) + + cases := []struct{ method, path, body string }{ + {http.MethodGet, "/api/v1/chats/" + chat, ""}, + {http.MethodGet, "/api/v1/chats/" + chat + "/messages", ""}, + {http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`}, + } + for _, c := range cases { + status, resp := do(t, srv, c.method, c.path, eve, c.body) + if status != http.StatusNotFound || errorCode(resp) != "not_found" { + t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status) + } + } + + status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve, "") + if status != http.StatusOK || len(resp["items"].([]any)) != 0 { + t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"]) + } +} + +func TestEmptyMessage(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + chat := createChat(t, srv, alice, alice) + + for _, text := range []string{"", " ", "\n\t"} { + body, _ := json.Marshal(map[string]string{"text": text}) + status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, string(body)) + if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" { + t.Errorf("text %q: got %d, want 400", text, status) + } + } +} + +func TestDuplicateUsername(t *testing.T) { + srv := newServer(t) + createUser(t, srv, "alice") + status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Other"}`) + if status != http.StatusConflict || errorCode(resp) != "conflict" { + t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp)) + } +} + +func TestPaginationMultiplePages(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + chat := createChat(t, srv, alice, alice) + + const total, limit = 7, 3 + for i := range total { + status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, fmt.Sprintf(`{"text":"msg %d"}`, i)) + if status != http.StatusCreated { + t.Fatalf("send message %d: status %d", i, status) + } + } + + seen := map[string]bool{} + pages := 0 + prevCreatedAt := "" + cursor := "" + for { + path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit) + if cursor != "" { + path += "&cursor=" + cursor + } + status, resp := do(t, srv, http.MethodGet, path, alice, "") + if status != http.StatusOK { + t.Fatalf("page %d: status %d", pages+1, status) + } + pages++ + for _, it := range resp["items"].([]any) { + m := it.(map[string]any) + id, createdAt := m["id"].(string), m["created_at"].(string) + if seen[id] { + t.Errorf("message %s returned twice", id) + } + if createdAt < prevCreatedAt { + t.Errorf("messages out of order: %s after %s", createdAt, prevCreatedAt) + } + seen[id] = true + prevCreatedAt = createdAt + } + next, ok := resp["next_cursor"].(string) + if !ok { + break + } + cursor = next + } + + if len(seen) != total { + t.Errorf("got %d messages, want %d", len(seen), total) + } + if want := (total + limit - 1) / limit; pages != want { + t.Errorf("got %d pages, want %d", pages, want) + } +} + +func TestConcurrentMessages(t *testing.T) { + srv := newServer(t) + const clients, perClient = 10, 10 + + users := make([]string, clients) + for i := range users { + users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i)) + } + chat := createChat(t, srv, users[0], users...) + + var wg sync.WaitGroup + errs := make(chan error, clients*perClient) + for c, user := range users { + wg.Go(func() { + for i := range perClient { + status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user, + fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i)) + if status != http.StatusCreated { + errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status) + } + } + }) + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + + status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0], "") + if status != http.StatusOK { + t.Fatalf("read history: status %d", status) + } + items := resp["items"].([]any) + ids := map[string]bool{} + for _, it := range items { + ids[it.(map[string]any)["id"].(string)] = true + } + if len(items) != clients*perClient || len(ids) != clients*perClient { + t.Errorf("got %d messages (%d unique), want %d", len(items), len(ids), clients*perClient) + } + if resp["next_cursor"] != nil { + t.Errorf("next_cursor = %v, want null", resp["next_cursor"]) + } +} diff --git a/internal/handler/health.go b/internal/handler/health.go new file mode 100644 index 00000000..b3cefede --- /dev/null +++ b/internal/handler/health.go @@ -0,0 +1,11 @@ +package handler + +import "net/http" + +func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) +} + +func (h *Handler) Ready(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) +} diff --git a/internal/handler/json.go b/internal/handler/json.go new file mode 100644 index 00000000..54674c25 --- /dev/null +++ b/internal/handler/json.go @@ -0,0 +1,86 @@ +package handler + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "reflect" + "strings" + "unicode/utf8" +) + +const maxBodyBytes = 1 << 20 + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error { + mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || mt != "application/json" { + return &apiError{http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json"} + } + + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes)) + if err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + return &apiError{http.StatusRequestEntityTooLarge, "payload_too_large", "request body is too large"} + } + return badRequest("failed to read request body") + } + if !utf8.Valid(raw) { + return badRequest("request body must be valid UTF-8") + } + if err := checkKeys(raw, dst); err != nil { + return err + } + + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return badRequest("request body must be a valid JSON object matching the schema") + } + if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + return badRequest("request body must contain a single JSON object") + } + return nil +} + +func checkKeys(raw []byte, dst any) error { + allowed := jsonFields(dst) + dec := json.NewDecoder(bytes.NewReader(raw)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return badRequest("request body must be a JSON object") + } + for dec.More() { + tok, err := dec.Token() + if err != nil { + return badRequest("request body must be a valid JSON object matching the schema") + } + key, _ := tok.(string) + if !allowed[key] { + return badRequest("request body contains unknown field") + } + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + return badRequest("request body must be a valid JSON object matching the schema") + } + } + return nil +} + +func jsonFields(dst any) map[string]bool { + t := reflect.TypeOf(dst).Elem() + fields := make(map[string]bool, t.NumField()) + for i := range t.NumField() { + name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",") + fields[name] = true + } + return fields +} diff --git a/internal/handler/messages.go b/internal/handler/messages.go new file mode 100644 index 00000000..be75207f --- /dev/null +++ b/internal/handler/messages.go @@ -0,0 +1,45 @@ +package handler + +import "net/http" + +func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) { + chatID, err := chatIDParam(r) + if err != nil { + h.fail(w, r, err) + return + } + var req createMessageRequest + if err := decodeJSON(w, r, &req); err != nil { + h.fail(w, r, err) + return + } + if req.Text == nil { + h.fail(w, r, badRequest("text is required")) + return + } + msg, err := h.messages.Send(r.Context(), actor(r), chatID, *req.Text) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toMessageResponse(msg)) +} + +func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) { + chatID, err := chatIDParam(r) + if err != nil { + h.fail(w, r, err) + return + } + limit, cursor, err := pageParams(r) + if err != nil { + h.fail(w, r, err) + return + } + page, err := h.messages.History(r.Context(), actor(r), chatID, cursor, limit) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusOK, toPageResponse(page, toMessageResponse)) +} diff --git a/internal/handler/middleware.go b/internal/handler/middleware.go new file mode 100644 index 00000000..b4abf455 --- /dev/null +++ b/internal/handler/middleware.go @@ -0,0 +1,91 @@ +package handler + +import ( + "context" + "errors" + "net/http" + "runtime/debug" + "time" + "uuid" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + + "messenger/internal/domain" +) + +const ( + headerRequestID = "X-Request-Id" + headerUserID = "X-User-Id" +) + +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(headerRequestID, uuid.New().String()) + next.ServeHTTP(w, r) + }) +} + +func (h *Handler) AccessLog(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) + next.ServeHTTP(ww, r) + + route := r.URL.Path + if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" { + route = rc.RoutePattern() + } + h.log.Info("request", + "request_id", w.Header().Get(headerRequestID), + "method", r.Method, + "route", route, + "status", ww.Status(), + "duration_ms", time.Since(start).Milliseconds(), + ) + }) +} + +func (h *Handler) Recoverer(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + rec := recover() + if rec == nil { + return + } + if rec == http.ErrAbortHandler { + panic(rec) + } + h.log.Error("panic", "request_id", w.Header().Get(headerRequestID), + "method", r.Method, "path", r.URL.Path, "panic", rec, "stack", string(debug.Stack())) + writeError(w, http.StatusInternalServerError, "internal_error", "internal server error") + }() + next.ServeHTTP(w, r) + }) +} + +type ctxKey struct{} + +func (h *Handler) Authenticate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id, ok := parseUUID(r.Header.Get(headerUserID)) + if !ok { + h.fail(w, r, domain.ErrUnauthorized) + return + } + user, err := h.users.Authenticate(r.Context(), id) + if err != nil { + h.fail(w, r, err) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, user))) + }) +} + +func actor(r *http.Request) domain.User { + u, ok := r.Context().Value(ctxKey{}).(domain.User) + if !ok { + panic(errors.New("handler: actor requested on unauthenticated route")) + } + return u +} diff --git a/internal/handler/users.go b/internal/handler/users.go new file mode 100644 index 00000000..dbb016cd --- /dev/null +++ b/internal/handler/users.go @@ -0,0 +1,25 @@ +package handler + +import "net/http" + +func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) { + var req createUserRequest + if err := decodeJSON(w, r, &req); err != nil { + h.fail(w, r, err) + return + } + if req.Username == nil || req.DisplayName == nil { + h.fail(w, r, badRequest("username and display_name are required strings")) + return + } + user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toUserResponse(user)) +} + +func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, toUserResponse(actor(r))) +} diff --git a/internal/repository/memory/store.go b/internal/repository/memory/store.go new file mode 100644 index 00000000..03efc020 --- /dev/null +++ b/internal/repository/memory/store.go @@ -0,0 +1,133 @@ +package memory + +import ( + "context" + "slices" + "sync" + "time" + "uuid" + + "messenger/internal/domain" +) + +type Store struct { + mu sync.RWMutex + + users map[uuid.UUID]domain.User + usernames map[string]uuid.UUID + chats map[uuid.UUID]domain.Chat + userChats map[uuid.UUID][]domain.Chat + chatHistory map[uuid.UUID][]domain.Message +} + +func New() *Store { + return &Store{ + users: make(map[uuid.UUID]domain.User), + usernames: make(map[string]uuid.UUID), + chats: make(map[uuid.UUID]domain.Chat), + userChats: make(map[uuid.UUID][]domain.Chat), + chatHistory: make(map[uuid.UUID][]domain.Message), + } +} + +func (s *Store) CreateUser(_ context.Context, u domain.User) error { + s.mu.Lock() + defer s.mu.Unlock() + if _, taken := s.usernames[u.Username]; taken { + return domain.ErrConflict + } + s.users[u.ID] = u + s.usernames[u.Username] = u.ID + return nil +} + +func (s *Store) GetUser(_ context.Context, id uuid.UUID) (domain.User, error) { + s.mu.RLock() + defer s.mu.RUnlock() + u, ok := s.users[id] + if !ok { + return domain.User{}, domain.ErrNotFound + } + return u, nil +} + +func (s *Store) CreateChat(_ context.Context, c domain.Chat) error { + c.MemberIDs = slices.Clone(c.MemberIDs) + s.mu.Lock() + defer s.mu.Unlock() + for _, id := range c.MemberIDs { + if _, ok := s.users[id]; !ok { + return domain.ErrNotFound + } + } + s.chats[c.ID] = c + for _, id := range c.MemberIDs { + s.userChats[id] = insertSorted(s.userChats[id], c, chatKey) + } + return nil +} + +func (s *Store) GetChat(_ context.Context, id uuid.UUID) (domain.Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + c, ok := s.chats[id] + if !ok { + return domain.Chat{}, domain.ErrNotFound + } + c.MemberIDs = slices.Clone(c.MemberIDs) + return c, nil +} + +func (s *Store) ListUserChats(_ context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + items, more := pageAfter(s.userChats[userID], after, limit, chatKey) + for i := range items { + items[i].MemberIDs = slices.Clone(items[i].MemberIDs) + } + return items, more, nil +} + +func (s *Store) CreateMessage(_ context.Context, m domain.Message) error { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.chats[m.ChatID]; !ok { + return domain.ErrNotFound + } + s.chatHistory[m.ChatID] = insertSorted(s.chatHistory[m.ChatID], m, messageKey) + return nil +} + +func (s *Store) ListMessages(_ context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + items, more := pageAfter(s.chatHistory[chatID], after, limit, messageKey) + return items, more, nil +} + +func chatKey(c domain.Chat) (time.Time, uuid.UUID) { return c.CreatedAt, c.ID } +func messageKey(m domain.Message) (time.Time, uuid.UUID) { return m.CreatedAt, m.ID } + +func insertSorted[T any](list []T, item T, key func(T) (time.Time, uuid.UUID)) []T { + t, id := key(item) + i, _ := slices.BinarySearchFunc(list, item, func(e T, _ T) int { + et, eid := key(e) + return domain.CompareKey(et, eid, t, id) + }) + return slices.Insert(list, i, item) +} + +func pageAfter[T any](list []T, after *domain.Cursor, limit int, key func(T) (time.Time, uuid.UUID)) ([]T, bool) { + start := 0 + if after != nil { + start, _ = slices.BinarySearchFunc(list, after, func(e T, c *domain.Cursor) int { + et, eid := key(e) + if r := domain.CompareKey(et, eid, c.CreatedAt, c.ID); r != 0 { + return r + } + return -1 + }) + } + end := min(start+limit, len(list)) + return slices.Clone(list[start:end]), end < len(list) +} diff --git a/internal/router/router.go b/internal/router/router.go new file mode 100644 index 00000000..baf8a98b --- /dev/null +++ b/internal/router/router.go @@ -0,0 +1,35 @@ +package router + +import ( + "net/http" + + "github.com/go-chi/chi/v5" + + "messenger/internal/handler" +) + +func New(h *handler.Handler) http.Handler { + r := chi.NewRouter() + r.Use(handler.RequestID, h.AccessLog, h.Recoverer) + + r.NotFound(h.NotFound) + r.MethodNotAllowed(h.MethodNotAllowed) + + r.Get("/health/live", h.Live) + r.Get("/health/ready", h.Ready) + + r.Route("/api/v1", func(r chi.Router) { + r.Post("/users", h.RegisterUser) + + r.Group(func(r chi.Router) { + r.Use(h.Authenticate) + r.Get("/users/me", h.CurrentUser) + r.Post("/chats", h.CreateChat) + r.Get("/chats", h.ListChats) + r.Get("/chats/{chat_id}", h.GetChat) + r.Post("/chats/{chat_id}/messages", h.SendMessage) + r.Get("/chats/{chat_id}/messages", h.ListMessages) + }) + }) + return r +} diff --git a/internal/service/chats.go b/internal/service/chats.go new file mode 100644 index 00000000..aafa7c56 --- /dev/null +++ b/internal/service/chats.go @@ -0,0 +1,81 @@ +package service + +import ( + "context" + "errors" + "fmt" + "uuid" + + "messenger/internal/domain" +) + +type ChatService struct { + repo ChatRepository +} + +func NewChatService(repo ChatRepository) *ChatService { + return &ChatService{repo: repo} +} + +func (s *ChatService) Create(ctx context.Context, actor domain.User, title string, memberIDs []uuid.UUID) (domain.Chat, error) { + if err := checkText("title", title, 100); err != nil { + return domain.Chat{}, err + } + if len(memberIDs) < 1 || len(memberIDs) > 100 { + return domain.Chat{}, fmt.Errorf("%w: member_ids must contain 1 to 100 users", domain.ErrInvalidInput) + } + seen := make(map[uuid.UUID]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return domain.Chat{}, fmt.Errorf("%w: member_ids must not contain duplicates", domain.ErrInvalidInput) + } + seen[id] = struct{}{} + } + if _, ok := seen[actor.ID]; !ok { + return domain.Chat{}, fmt.Errorf("%w: member_ids must include the current user", domain.ErrInvalidInput) + } + + c := domain.Chat{ + ID: uuid.New(), + Title: title, + MemberIDs: memberIDs, + CreatedAt: now(), + } + if err := s.repo.CreateChat(ctx, c); err != nil { + if errors.Is(err, domain.ErrNotFound) { + return domain.Chat{}, fmt.Errorf("%w: member_ids contains unknown user", domain.ErrInvalidInput) + } + return domain.Chat{}, err + } + return c, nil +} + +func (s *ChatService) Get(ctx context.Context, actor domain.User, chatID uuid.UUID) (domain.Chat, error) { + c, err := s.repo.GetChat(ctx, chatID) + if err != nil { + return domain.Chat{}, err + } + if !c.HasMember(actor.ID) { + return domain.Chat{}, domain.ErrNotFound + } + return c, nil +} + +func (s *ChatService) List(ctx context.Context, actor domain.User, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) { + if err := checkLimit(limit); err != nil { + return domain.Page[domain.Chat]{}, err + } + if after != nil && after.Scope != actor.ID { + return domain.Page[domain.Chat]{}, fmt.Errorf("%w: cursor does not belong to this request", domain.ErrInvalidInput) + } + items, more, err := s.repo.ListUserChats(ctx, actor.ID, after, limit) + if err != nil { + return domain.Page[domain.Chat]{}, err + } + page := domain.Page[domain.Chat]{Items: items} + if more { + last := items[len(items)-1] + page.Next = &domain.Cursor{Scope: actor.ID, CreatedAt: last.CreatedAt, ID: last.ID} + } + return page, nil +} diff --git a/internal/service/messages.go b/internal/service/messages.go new file mode 100644 index 00000000..f44ee93f --- /dev/null +++ b/internal/service/messages.go @@ -0,0 +1,60 @@ +package service + +import ( + "context" + "fmt" + "uuid" + + "messenger/internal/domain" +) + +type MessageService struct { + chats *ChatService + messages MessageRepository +} + +func NewMessageService(chats *ChatService, messages MessageRepository) *MessageService { + return &MessageService{chats: chats, messages: messages} +} + +func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, text string) (domain.Message, error) { + if _, err := s.chats.Get(ctx, actor, chatID); err != nil { + return domain.Message{}, err + } + if err := checkText("text", text, 4000); err != nil { + return domain.Message{}, err + } + m := domain.Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: actor.ID, + Text: text, + CreatedAt: now(), + } + if err := s.messages.CreateMessage(ctx, m); err != nil { + return domain.Message{}, err + } + return m, nil +} + +func (s *MessageService) History(ctx context.Context, actor domain.User, chatID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) { + if _, err := s.chats.Get(ctx, actor, chatID); err != nil { + return domain.Page[domain.Message]{}, err + } + if err := checkLimit(limit); err != nil { + return domain.Page[domain.Message]{}, err + } + if after != nil && after.Scope != chatID { + return domain.Page[domain.Message]{}, fmt.Errorf("%w: cursor belongs to another chat", domain.ErrInvalidInput) + } + items, more, err := s.messages.ListMessages(ctx, chatID, after, limit) + if err != nil { + return domain.Page[domain.Message]{}, err + } + page := domain.Page[domain.Message]{Items: items} + if more { + last := items[len(items)-1] + page.Next = &domain.Cursor{Scope: chatID, CreatedAt: last.CreatedAt, ID: last.ID} + } + return page, nil +} diff --git a/internal/service/ports.go b/internal/service/ports.go new file mode 100644 index 00000000..ae3f4f76 --- /dev/null +++ b/internal/service/ports.go @@ -0,0 +1,29 @@ +package service + +import ( + "context" + "time" + "uuid" + + "messenger/internal/domain" +) + +type UserRepository interface { + CreateUser(ctx context.Context, u domain.User) error + GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) +} + +type ChatRepository interface { + CreateChat(ctx context.Context, c domain.Chat) error + GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error) + ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) +} + +type MessageRepository interface { + CreateMessage(ctx context.Context, m domain.Message) error + ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) +} + +func now() time.Time { + return time.Now().UTC().Truncate(time.Microsecond) +} diff --git a/internal/service/users.go b/internal/service/users.go new file mode 100644 index 00000000..e0499b11 --- /dev/null +++ b/internal/service/users.go @@ -0,0 +1,48 @@ +package service + +import ( + "context" + "errors" + "fmt" + "regexp" + "uuid" + + "messenger/internal/domain" +) + +var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type UserService struct { + repo UserRepository +} + +func NewUserService(repo UserRepository) *UserService { + return &UserService{repo: repo} +} + +func (s *UserService) Register(ctx context.Context, username, displayName string) (domain.User, error) { + if !usernameRe.MatchString(username) { + return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput) + } + if err := checkText("display_name", displayName, 100); err != nil { + return domain.User{}, err + } + u := domain.User{ + ID: uuid.New(), + Username: username, + DisplayName: displayName, + CreatedAt: now(), + } + if err := s.repo.CreateUser(ctx, u); err != nil { + return domain.User{}, err + } + return u, nil +} + +func (s *UserService) Authenticate(ctx context.Context, id uuid.UUID) (domain.User, error) { + u, err := s.repo.GetUser(ctx, id) + if errors.Is(err, domain.ErrNotFound) { + return domain.User{}, domain.ErrUnauthorized + } + return u, err +} diff --git a/internal/service/validate.go b/internal/service/validate.go new file mode 100644 index 00000000..68540bc8 --- /dev/null +++ b/internal/service/validate.go @@ -0,0 +1,31 @@ +package service + +import ( + "fmt" + "strings" + "unicode/utf8" + + "messenger/internal/domain" +) + +const ( + DefaultLimit = 50 + MaxLimit = 100 +) + +func checkText(field, value string, maxRunes int) error { + if strings.TrimSpace(value) == "" { + return fmt.Errorf("%w: %s must not be empty", domain.ErrInvalidInput, field) + } + if n := utf8.RuneCountInString(value); n > maxRunes { + return fmt.Errorf("%w: %s must be at most %d characters", domain.ErrInvalidInput, field, maxRunes) + } + return nil +} + +func checkLimit(limit int) error { + if limit < 1 || limit > MaxLimit { + return fmt.Errorf("%w: limit must be between 1 and %d", domain.ErrInvalidInput, MaxLimit) + } + return nil +} -- 2.54.0 From f68710818df42467df8e6921849ca78e2f4423ee Mon Sep 17 00:00:00 2001 From: myDan Date: Fri, 30 Oct 2026 01:34:50 +0300 Subject: [PATCH 2/5] feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis --- cmd/server/main.go | 80 ++++-- go.mod | 20 +- go.sum | 97 +++++++ internal/config/config.go | 47 +++- internal/domain/domain.go | 6 + internal/domain/errors.go | 1 + internal/handler/auth.go | 53 ++++ internal/handler/auth_test.go | 102 ++++++++ internal/handler/dto.go | 17 ++ internal/handler/errors.go | 9 +- internal/handler/handler.go | 10 +- internal/handler/handler_test.go | 142 ++++++++--- internal/handler/health.go | 18 +- internal/handler/middleware.go | 39 ++- internal/handler/users.go | 6 +- internal/repository/memory/store.go | 133 ---------- internal/repository/postgres/migrate.go | 39 +++ .../postgres/migrations/000001_init.down.sql | 4 + .../postgres/migrations/000001_init.up.sql | 32 +++ internal/repository/postgres/postgres_test.go | 106 ++++++++ internal/repository/postgres/store.go | 237 ++++++++++++++++++ internal/repository/redis/sessions.go | 71 ++++++ internal/router/router.go | 2 + internal/service/auth.go | 74 ++++++ internal/service/password.go | 60 +++++ internal/service/ports.go | 9 +- internal/service/users.go | 29 ++- 27 files changed, 1229 insertions(+), 214 deletions(-) create mode 100644 internal/handler/auth.go create mode 100644 internal/handler/auth_test.go delete mode 100644 internal/repository/memory/store.go create mode 100644 internal/repository/postgres/migrate.go create mode 100644 internal/repository/postgres/migrations/000001_init.down.sql create mode 100644 internal/repository/postgres/migrations/000001_init.up.sql create mode 100644 internal/repository/postgres/postgres_test.go create mode 100644 internal/repository/postgres/store.go create mode 100644 internal/repository/redis/sessions.go create mode 100644 internal/service/auth.go create mode 100644 internal/service/password.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 8cb8030e..0150fef8 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -12,48 +12,100 @@ import ( "messenger/internal/config" "messenger/internal/handler" - "messenger/internal/repository/memory" + "messenger/internal/repository/postgres" + "messenger/internal/repository/redis" "messenger/internal/router" "messenger/internal/service" ) -const shutdownTimeout = 5 * time.Second +const ( + shutdownTimeout = 5 * time.Second + migrateAttempts = 60 +) func main() { log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - cfg := config.Load() + if err := run(log); err != nil { + log.Error("server failed", "err", err) + os.Exit(1) + } +} + +func run(log *slog.Logger) error { + cfg, err := config.Load() + if err != nil { + return err + } + + if err := migrateWithRetry(log, cfg.DatabaseURL); err != nil { + return err + } + + pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL) + if err != nil { + return err + } + defer pool.Close() + store := postgres.New(pool) + + redisClient, err := redis.NewClient(cfg.CacheURL) + if err != nil { + return err + } + defer redisClient.Close() + sessions := redis.NewSessionStore(redisClient) - store := memory.New() users := service.NewUserService(store) + auth := service.NewAuthService(store, sessions, cfg.SessionTTL) chats := service.NewChatService(store) messages := service.NewMessageService(chats, store) + deps := []handler.Pinger{store.Ping, sessions.Ping} srv := &http.Server{ Addr: cfg.Addr(), - Handler: router.New(handler.New(users, chats, messages, log)), + Handler: router.New(handler.New(users, auth, chats, messages, deps, log)), ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) defer stop() + errCh := make(chan error, 1) go func() { - log.Info("starting server", "addr", srv.Addr, "env", cfg.Env) + log.Info("starting server", "addr", srv.Addr, "env", cfg.Env, "session_ttl", cfg.SessionTTL.String()) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - log.Error("server failed", "err", err) - os.Exit(1) + errCh <- err } }() - <-ctx.Done() + select { + case err := <-errCh: + return err + case <-ctx.Done(): + } log.Info("shutdown signal received", "timeout", shutdownTimeout.String()) shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) - err := srv.Shutdown(shutdownCtx) - cancel() - if err != nil { - log.Error("graceful shutdown failed", "err", err) - os.Exit(1) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + return err } log.Info("server stopped") + return nil +} + +func migrateWithRetry(log *slog.Logger, databaseURL string) error { + var err error + for attempt := 1; attempt <= migrateAttempts; attempt++ { + if err = postgres.Migrate(databaseURL); err == nil { + log.Info("migrations applied") + return nil + } + log.Warn("migrations failed, retrying", "attempt", attempt, "err", err) + time.Sleep(time.Second) + } + return err } diff --git a/go.mod b/go.mod index d551bc37..4357d257 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,22 @@ module messenger go 1.27.1 -require github.com/go-chi/chi/v5 v5.3.2 +require ( + github.com/go-chi/chi/v5 v5.3.2 + github.com/golang-migrate/migrate/v4 v4.20.1 + github.com/jackc/pgx/v5 v5.11.0 + github.com/redis/go-redis/v9 v9.23.0 + golang.org/x/crypto v0.58.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + go.uber.org/atomic v1.12.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect +) diff --git a/go.sum b/go.sum index 5a3b06d3..7d438f00 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,99 @@ +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4= +github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM= +github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= +github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU= +github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM= +github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw= +github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg= +github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= +github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY= +github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/config.go b/internal/config/config.go index f6d50973..29a8b74b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,26 +1,57 @@ package config import ( + "fmt" "net" "os" + "strconv" + "strings" + "time" ) type Config struct { - Host string - Port string - Env string + Host string + Port string + Env string + SessionTTL time.Duration + DatabaseURL string + CacheURL string } -func Load() Config { - return Config{ - Host: getenv("APP_HOST", "0.0.0.0"), - Port: getenv("APP_PORT", "8080"), - Env: getenv("APP_ENV", "lab"), +func Load() (Config, error) { + ttl, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600")) + if err != nil || ttl <= 0 { + return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer") } + databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url") + if err != nil { + return Config{}, err + } + cacheURL, err := readSecret("CACHE_URL_FILE", "/run/secrets/cache_url") + if err != nil { + return Config{}, err + } + return Config{ + Host: getenv("APP_HOST", "0.0.0.0"), + Port: getenv("APP_PORT", "8080"), + Env: getenv("APP_ENV", "lab"), + SessionTTL: time.Duration(ttl) * time.Second, + DatabaseURL: databaseURL, + CacheURL: cacheURL, + }, nil } func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) } +func readSecret(key, def string) (string, error) { + path := getenv(key, def) + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("%s: cannot read %s", key, path) + } + return strings.TrimSpace(string(b)), nil +} + func getenv(key, def string) string { if v := os.Getenv(key); v != "" { return v diff --git a/internal/domain/domain.go b/internal/domain/domain.go index 979219a2..f1036b72 100644 --- a/internal/domain/domain.go +++ b/internal/domain/domain.go @@ -36,6 +36,12 @@ type Message struct { CreatedAt time.Time } +type Session struct { + Token string + ExpiresAt time.Time + User User +} + type Cursor struct { Scope uuid.UUID CreatedAt time.Time diff --git a/internal/domain/errors.go b/internal/domain/errors.go index 888f0de2..b4adb605 100644 --- a/internal/domain/errors.go +++ b/internal/domain/errors.go @@ -7,4 +7,5 @@ var ( ErrUnauthorized = errors.New("unauthorized") ErrNotFound = errors.New("not found") ErrConflict = errors.New("conflict") + ErrUnavailable = errors.New("dependency unavailable") ) diff --git a/internal/handler/auth.go b/internal/handler/auth.go new file mode 100644 index 00000000..cea44f64 --- /dev/null +++ b/internal/handler/auth.go @@ -0,0 +1,53 @@ +package handler + +import ( + "encoding/base64" + "errors" + "net/http" + "strings" + "unicode/utf8" + + "messenger/internal/domain" +) + +func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) { + username, password, ok := basicCredentials(r) + if !ok { + h.failLogin(w, r, domain.ErrUnauthorized) + return + } + session, err := h.auth.Login(r.Context(), username, password) + if err != nil { + h.failLogin(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toSessionResponse(session)) +} + +func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) { + if errors.Is(err, domain.ErrUnauthorized) { + w.Header().Set(headerWWWAuthenticate, basicChallenge) + } + h.fail(w, r, err) +} + +func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) { + if err := h.auth.Logout(r.Context(), current(r).token); err != nil { + h.fail(w, r, err) + return + } + w.WriteHeader(http.StatusNoContent) +} + +func basicCredentials(r *http.Request) (string, string, bool) { + encoded, ok := authCredentials(r, "Basic") + if !ok { + return "", "", false + } + raw, err := base64.StdEncoding.DecodeString(encoded) + if err != nil || !utf8.Valid(raw) { + return "", "", false + } + username, password, ok := strings.Cut(string(raw), ":") + return username, password, ok +} diff --git a/internal/handler/auth_test.go b/internal/handler/auth_test.go new file mode 100644 index 00000000..9fb027be --- /dev/null +++ b/internal/handler/auth_test.go @@ -0,0 +1,102 @@ +package handler_test + +import ( + "net/http" + "strings" + "testing" + "time" +) + +const ( + deadDatabaseURL = "postgres://messenger:x@127.0.0.1:1/messenger?sslmode=disable" + deadRedisURL = "redis://127.0.0.1:1/0" +) + +func TestSessionExpiry(t *testing.T) { + dbURL, redisURL := testURLs(t) + srv := newStack(t, dbURL, redisURL, 2*time.Second) + alice := createUser(t, srv, "alice") + + if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusOK { + t.Fatalf("fresh session: got %d, want 200", status) + } + time.Sleep(3 * time.Second) + resp := request(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, "") + resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expired session: got %d, want 401", resp.StatusCode) + } + if got := resp.Header.Get("WWW-Authenticate"); !strings.HasPrefix(got, "Bearer") { + t.Errorf("WWW-Authenticate = %q, want Bearer challenge", got) + } +} + +func TestLogout(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + + resp := request(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, "") + resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { + t.Fatalf("logout: got %d, want 204", resp.StatusCode) + } + if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusUnauthorized { + t.Errorf("revoked token on /users/me: got %d, want 401", status) + } + if status, _ := do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, ""); status != http.StatusUnauthorized { + t.Errorf("repeated logout: got %d, want 401", status) + } +} + +func TestWrongPassword(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + + for name, password := range map[string]string{"wrong password": "Wrong-password-123", "unknown user": alice.Password} { + username := alice.Username + if name == "unknown user" { + username = "nobody_" + alice.Username[:10] + } + resp := login(t, srv, username, password) + resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("%s: got %d, want 401", name, resp.StatusCode) + } + if got := resp.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Errorf("%s: WWW-Authenticate = %q", name, got) + } + } +} + +func TestRedisUnavailable(t *testing.T) { + dbURL, _ := testURLs(t) + srv := newStack(t, dbURL, deadRedisURL, time.Hour) + + if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", "some-token-from-before-the-outage", ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" { + t.Errorf("bearer request: got %d %q, want 503 unavailable", status, errorCode(body)) + } + if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", "", ""); status != http.StatusUnauthorized { + t.Errorf("anonymous request: got %d, want 401", status) + } + if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable { + t.Errorf("ready: got %d, want 503", status) + } +} + +func TestDatabaseUnavailable(t *testing.T) { + dbURL, redisURL := testURLs(t) + healthy := newStack(t, dbURL, redisURL, time.Hour) + alice := createUser(t, healthy, "alice") + + srv := newStack(t, deadDatabaseURL, redisURL, time.Hour) + if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" { + t.Errorf("valid session: got %d %q, want 503 unavailable", status, errorCode(body)) + } + if status, _ := do(t, srv, http.MethodPost, "/api/v1/users", "", + `{"username":"db_down_user","display_name":"X","password":"long-enough-pass"}`); status != http.StatusServiceUnavailable { + t.Errorf("register: got %d, want 503", status) + } + if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable { + t.Errorf("ready: got %d, want 503", status) + } +} diff --git a/internal/handler/dto.go b/internal/handler/dto.go index eac64da0..2bacc087 100644 --- a/internal/handler/dto.go +++ b/internal/handler/dto.go @@ -9,6 +9,7 @@ import ( type createUserRequest struct { Username *string `json:"username"` DisplayName *string `json:"display_name"` + Password *string `json:"password"` } type createChatRequest struct { @@ -47,6 +48,13 @@ type pageResponse[T any] struct { NextCursor *string `json:"next_cursor"` } +type sessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt string `json:"expires_at"` + User userResponse `json:"user"` +} + type healthResponse struct { Status string `json:"status"` } @@ -74,6 +82,15 @@ func toUserResponse(u domain.User) userResponse { } } +func toSessionResponse(s domain.Session) sessionResponse { + return sessionResponse{ + Token: s.Token, + TokenType: "Bearer", + ExpiresAt: formatTime(s.ExpiresAt), + User: toUserResponse(s.User), + } +} + func toChatResponse(c domain.Chat) chatResponse { members := make([]string, len(c.MemberIDs)) for i, id := range c.MemberIDs { diff --git a/internal/handler/errors.go b/internal/handler/errors.go index da0ff9c9..3d148c4f 100644 --- a/internal/handler/errors.go +++ b/internal/handler/errors.go @@ -35,11 +35,18 @@ func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) { case errors.Is(err, domain.ErrInvalidInput): writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) case errors.Is(err, domain.ErrUnauthorized): - writeError(w, http.StatusUnauthorized, "unauthorized", "valid X-User-Id header is required") + if w.Header().Get(headerWWWAuthenticate) == "" { + w.Header().Set(headerWWWAuthenticate, bearerChallenge) + } + writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required") case errors.Is(err, domain.ErrNotFound): writeError(w, http.StatusNotFound, "not_found", "resource not found") case errors.Is(err, domain.ErrConflict): writeError(w, http.StatusConflict, "conflict", "username is already taken") + case errors.Is(err, domain.ErrUnavailable): + h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID), + "method", r.Method, "path", r.URL.Path, "err", err) + writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable") default: h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID), "method", r.Method, "path", r.URL.Path, "err", err) diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 42cb1b4a..0491ac47 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -1,21 +1,27 @@ package handler import ( + "context" "log/slog" "net/http" "messenger/internal/service" ) +type Pinger func(ctx context.Context) error + type Handler struct { users *service.UserService + auth *service.AuthService chats *service.ChatService messages *service.MessageService + deps []Pinger log *slog.Logger } -func New(users *service.UserService, chats *service.ChatService, messages *service.MessageService, log *slog.Logger) *Handler { - return &Handler{users: users, chats: chats, messages: messages, log: log} +func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService, + messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler { + return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log} } func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) { diff --git a/internal/handler/handler_test.go b/internal/handler/handler_test.go index bea64193..9f87846c 100644 --- a/internal/handler/handler_test.go +++ b/internal/handler/handler_test.go @@ -1,33 +1,75 @@ package handler_test import ( + "context" + "encoding/base64" "encoding/json" "fmt" "log/slog" "net/http" "net/http/httptest" + "os" "strings" "sync" "testing" + "time" + "uuid" "messenger/internal/handler" - "messenger/internal/repository/memory" + "messenger/internal/repository/postgres" + "messenger/internal/repository/redis" "messenger/internal/router" "messenger/internal/service" ) +func testURLs(t *testing.T) (string, string) { + t.Helper() + dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL") + if dbURL == "" || redisURL == "" { + t.Skip("TEST_DATABASE_URL and TEST_REDIS_URL are required") + } + return dbURL, redisURL +} + func newServer(t *testing.T) *httptest.Server { t.Helper() - store := memory.New() + dbURL, redisURL := testURLs(t) + return newStack(t, dbURL, redisURL, time.Hour) +} + +func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest.Server { + t.Helper() + pool, err := postgres.NewPool(context.Background(), dbURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + store := postgres.New(pool) + client, err := redis.NewClient(redisURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close() }) + sessions := redis.NewSessionStore(client) + users := service.NewUserService(store) + auth := service.NewAuthService(store, sessions, ttl) chats := service.NewChatService(store) messages := service.NewMessageService(chats, store) - srv := httptest.NewServer(router.New(handler.New(users, chats, messages, slog.New(slog.DiscardHandler)))) + h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler)) + srv := httptest.NewServer(router.New(h)) t.Cleanup(srv.Close) return srv } -func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (int, map[string]any) { +type testUser struct { + ID string + Username string + Password string + Token string +} + +func request(t *testing.T, srv *httptest.Server, method, path, token, body string) *http.Response { t.Helper() req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body)) if err != nil { @@ -36,13 +78,19 @@ func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) ( if body != "" { req.Header.Set("Content-Type", "application/json") } - if userID != "" { - req.Header.Set("X-User-Id", userID) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) } resp, err := srv.Client().Do(req) if err != nil { t.Fatal(err) } + return resp +} + +func do(t *testing.T, srv *httptest.Server, method, path, token, body string) (int, map[string]any) { + t.Helper() + resp := request(t, srv, method, path, token, body) defer resp.Body.Close() var out map[string]any if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { @@ -57,21 +105,56 @@ func errorCode(body map[string]any) string { return code } -func createUser(t *testing.T, srv *httptest.Server, username string) string { - t.Helper() - status, body := do(t, srv, http.MethodPost, "/api/v1/users", "", - fmt.Sprintf(`{"username":%q,"display_name":"Test"}`, username)) - if status != http.StatusCreated { - t.Fatalf("create user %s: status %d", username, status) - } - return body["id"].(string) +func basic(username, password string) string { + return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)) } -func createChat(t *testing.T, srv *httptest.Server, owner string, members ...string) string { +func login(t *testing.T, srv *httptest.Server, username, password string) *http.Response { t.Helper() - ids, _ := json.Marshal(members) - status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner, - fmt.Sprintf(`{"title":"Test","member_ids":%s}`, ids)) + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", basic(username, password)) + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + return resp +} + +func createUser(t *testing.T, srv *httptest.Server, label string) testUser { + t.Helper() + u := testUser{ + Username: label + "_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12], + Password: "Test-password-" + label, + } + status, body := do(t, srv, http.MethodPost, "/api/v1/users", "", + fmt.Sprintf(`{"username":%q,"display_name":"Test","password":%q}`, u.Username, u.Password)) + if status != http.StatusCreated { + t.Fatalf("create user %s: status %d", u.Username, status) + } + u.ID = body["id"].(string) + + resp := login(t, srv, u.Username, u.Password) + defer resp.Body.Close() + var session map[string]any + if err := json.NewDecoder(resp.Body).Decode(&session); err != nil || resp.StatusCode != http.StatusCreated { + t.Fatalf("login %s: status %d", u.Username, resp.StatusCode) + } + u.Token = session["token"].(string) + return u +} + +func createChat(t *testing.T, srv *httptest.Server, owner testUser, members ...testUser) string { + t.Helper() + ids := make([]string, len(members)) + for i, m := range members { + ids[i] = m.ID + } + raw, _ := json.Marshal(ids) + status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner.Token, + fmt.Sprintf(`{"title":"Test","member_ids":%s}`, raw)) if status != http.StatusCreated { t.Fatalf("create chat: status %d", status) } @@ -80,7 +163,7 @@ func createChat(t *testing.T, srv *httptest.Server, owner string, members ...str func TestInvalidJSON(t *testing.T) { srv := newServer(t) - for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x"}`} { + for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x","password":"long-enough-pass"}`} { status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body) if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" { t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp)) @@ -101,13 +184,13 @@ func TestForeignChat(t *testing.T) { {http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`}, } for _, c := range cases { - status, resp := do(t, srv, c.method, c.path, eve, c.body) + status, resp := do(t, srv, c.method, c.path, eve.Token, c.body) if status != http.StatusNotFound || errorCode(resp) != "not_found" { t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status) } } - status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve, "") + status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve.Token, "") if status != http.StatusOK || len(resp["items"].([]any)) != 0 { t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"]) } @@ -120,7 +203,7 @@ func TestEmptyMessage(t *testing.T) { for _, text := range []string{"", " ", "\n\t"} { body, _ := json.Marshal(map[string]string{"text": text}) - status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, string(body)) + status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, string(body)) if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" { t.Errorf("text %q: got %d, want 400", text, status) } @@ -129,8 +212,9 @@ func TestEmptyMessage(t *testing.T) { func TestDuplicateUsername(t *testing.T) { srv := newServer(t) - createUser(t, srv, "alice") - status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Other"}`) + alice := createUser(t, srv, "alice") + status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", + fmt.Sprintf(`{"username":%q,"display_name":"Other","password":"another-password"}`, alice.Username)) if status != http.StatusConflict || errorCode(resp) != "conflict" { t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp)) } @@ -143,7 +227,7 @@ func TestPaginationMultiplePages(t *testing.T) { const total, limit = 7, 3 for i := range total { - status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, fmt.Sprintf(`{"text":"msg %d"}`, i)) + status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, fmt.Sprintf(`{"text":"msg %d"}`, i)) if status != http.StatusCreated { t.Fatalf("send message %d: status %d", i, status) } @@ -158,7 +242,7 @@ func TestPaginationMultiplePages(t *testing.T) { if cursor != "" { path += "&cursor=" + cursor } - status, resp := do(t, srv, http.MethodGet, path, alice, "") + status, resp := do(t, srv, http.MethodGet, path, alice.Token, "") if status != http.StatusOK { t.Fatalf("page %d: status %d", pages+1, status) } @@ -194,7 +278,7 @@ func TestConcurrentMessages(t *testing.T) { srv := newServer(t) const clients, perClient = 10, 10 - users := make([]string, clients) + users := make([]testUser, clients) for i := range users { users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i)) } @@ -205,7 +289,7 @@ func TestConcurrentMessages(t *testing.T) { for c, user := range users { wg.Go(func() { for i := range perClient { - status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user, + status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user.Token, fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i)) if status != http.StatusCreated { errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status) @@ -219,7 +303,7 @@ func TestConcurrentMessages(t *testing.T) { t.Error(err) } - status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0], "") + status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0].Token, "") if status != http.StatusOK { t.Fatalf("read history: status %d", status) } diff --git a/internal/handler/health.go b/internal/handler/health.go index b3cefede..2268d8ec 100644 --- a/internal/handler/health.go +++ b/internal/handler/health.go @@ -1,11 +1,25 @@ package handler -import "net/http" +import ( + "context" + "net/http" + "time" +) + +const readyTimeout = time.Second func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) } -func (h *Handler) Ready(w http.ResponseWriter, _ *http.Request) { +func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), readyTimeout) + defer cancel() + for _, dep := range h.deps { + if err := dep(ctx); err != nil { + h.fail(w, r, err) + return + } + } writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) } diff --git a/internal/handler/middleware.go b/internal/handler/middleware.go index b4abf455..fb364899 100644 --- a/internal/handler/middleware.go +++ b/internal/handler/middleware.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "runtime/debug" + "strings" "time" "uuid" @@ -15,8 +16,10 @@ import ( ) const ( - headerRequestID = "X-Request-Id" - headerUserID = "X-User-Id" + headerRequestID = "X-Request-Id" + headerWWWAuthenticate = "WWW-Authenticate" + bearerChallenge = `Bearer realm="messenger"` + basicChallenge = `Basic realm="messenger", charset="UTF-8"` ) func RequestID(next http.Handler) http.Handler { @@ -66,26 +69,44 @@ func (h *Handler) Recoverer(next http.Handler) http.Handler { type ctxKey struct{} +type principal struct { + user domain.User + token string +} + func (h *Handler) Authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - id, ok := parseUUID(r.Header.Get(headerUserID)) - if !ok { + token, ok := authCredentials(r, "Bearer") + if !ok || token == "" { h.fail(w, r, domain.ErrUnauthorized) return } - user, err := h.users.Authenticate(r.Context(), id) + user, err := h.auth.Authenticate(r.Context(), token) if err != nil { h.fail(w, r, err) return } - next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, user))) + ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token}) + next.ServeHTTP(w, r.WithContext(ctx)) }) } -func actor(r *http.Request) domain.User { - u, ok := r.Context().Value(ctxKey{}).(domain.User) +func authCredentials(r *http.Request, scheme string) (string, bool) { + gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ") + if !ok || !strings.EqualFold(gotScheme, scheme) { + return "", false + } + return credentials, true +} + +func current(r *http.Request) principal { + p, ok := r.Context().Value(ctxKey{}).(principal) if !ok { panic(errors.New("handler: actor requested on unauthenticated route")) } - return u + return p +} + +func actor(r *http.Request) domain.User { + return current(r).user } diff --git a/internal/handler/users.go b/internal/handler/users.go index dbb016cd..c427ca4e 100644 --- a/internal/handler/users.go +++ b/internal/handler/users.go @@ -8,11 +8,11 @@ func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) { h.fail(w, r, err) return } - if req.Username == nil || req.DisplayName == nil { - h.fail(w, r, badRequest("username and display_name are required strings")) + if req.Username == nil || req.DisplayName == nil || req.Password == nil { + h.fail(w, r, badRequest("username, display_name and password are required strings")) return } - user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName) + user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName, *req.Password) if err != nil { h.fail(w, r, err) return diff --git a/internal/repository/memory/store.go b/internal/repository/memory/store.go deleted file mode 100644 index 03efc020..00000000 --- a/internal/repository/memory/store.go +++ /dev/null @@ -1,133 +0,0 @@ -package memory - -import ( - "context" - "slices" - "sync" - "time" - "uuid" - - "messenger/internal/domain" -) - -type Store struct { - mu sync.RWMutex - - users map[uuid.UUID]domain.User - usernames map[string]uuid.UUID - chats map[uuid.UUID]domain.Chat - userChats map[uuid.UUID][]domain.Chat - chatHistory map[uuid.UUID][]domain.Message -} - -func New() *Store { - return &Store{ - users: make(map[uuid.UUID]domain.User), - usernames: make(map[string]uuid.UUID), - chats: make(map[uuid.UUID]domain.Chat), - userChats: make(map[uuid.UUID][]domain.Chat), - chatHistory: make(map[uuid.UUID][]domain.Message), - } -} - -func (s *Store) CreateUser(_ context.Context, u domain.User) error { - s.mu.Lock() - defer s.mu.Unlock() - if _, taken := s.usernames[u.Username]; taken { - return domain.ErrConflict - } - s.users[u.ID] = u - s.usernames[u.Username] = u.ID - return nil -} - -func (s *Store) GetUser(_ context.Context, id uuid.UUID) (domain.User, error) { - s.mu.RLock() - defer s.mu.RUnlock() - u, ok := s.users[id] - if !ok { - return domain.User{}, domain.ErrNotFound - } - return u, nil -} - -func (s *Store) CreateChat(_ context.Context, c domain.Chat) error { - c.MemberIDs = slices.Clone(c.MemberIDs) - s.mu.Lock() - defer s.mu.Unlock() - for _, id := range c.MemberIDs { - if _, ok := s.users[id]; !ok { - return domain.ErrNotFound - } - } - s.chats[c.ID] = c - for _, id := range c.MemberIDs { - s.userChats[id] = insertSorted(s.userChats[id], c, chatKey) - } - return nil -} - -func (s *Store) GetChat(_ context.Context, id uuid.UUID) (domain.Chat, error) { - s.mu.RLock() - defer s.mu.RUnlock() - c, ok := s.chats[id] - if !ok { - return domain.Chat{}, domain.ErrNotFound - } - c.MemberIDs = slices.Clone(c.MemberIDs) - return c, nil -} - -func (s *Store) ListUserChats(_ context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) { - s.mu.RLock() - defer s.mu.RUnlock() - items, more := pageAfter(s.userChats[userID], after, limit, chatKey) - for i := range items { - items[i].MemberIDs = slices.Clone(items[i].MemberIDs) - } - return items, more, nil -} - -func (s *Store) CreateMessage(_ context.Context, m domain.Message) error { - s.mu.Lock() - defer s.mu.Unlock() - if _, ok := s.chats[m.ChatID]; !ok { - return domain.ErrNotFound - } - s.chatHistory[m.ChatID] = insertSorted(s.chatHistory[m.ChatID], m, messageKey) - return nil -} - -func (s *Store) ListMessages(_ context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) { - s.mu.RLock() - defer s.mu.RUnlock() - items, more := pageAfter(s.chatHistory[chatID], after, limit, messageKey) - return items, more, nil -} - -func chatKey(c domain.Chat) (time.Time, uuid.UUID) { return c.CreatedAt, c.ID } -func messageKey(m domain.Message) (time.Time, uuid.UUID) { return m.CreatedAt, m.ID } - -func insertSorted[T any](list []T, item T, key func(T) (time.Time, uuid.UUID)) []T { - t, id := key(item) - i, _ := slices.BinarySearchFunc(list, item, func(e T, _ T) int { - et, eid := key(e) - return domain.CompareKey(et, eid, t, id) - }) - return slices.Insert(list, i, item) -} - -func pageAfter[T any](list []T, after *domain.Cursor, limit int, key func(T) (time.Time, uuid.UUID)) ([]T, bool) { - start := 0 - if after != nil { - start, _ = slices.BinarySearchFunc(list, after, func(e T, c *domain.Cursor) int { - et, eid := key(e) - if r := domain.CompareKey(et, eid, c.CreatedAt, c.ID); r != 0 { - return r - } - return -1 - }) - } - end := min(start+limit, len(list)) - return slices.Clone(list[start:end]), end < len(list) -} diff --git a/internal/repository/postgres/migrate.go b/internal/repository/postgres/migrate.go new file mode 100644 index 00000000..5c4e2532 --- /dev/null +++ b/internal/repository/postgres/migrate.go @@ -0,0 +1,39 @@ +package postgres + +import ( + "embed" + "errors" + "strings" + + "github.com/golang-migrate/migrate/v4" + _ "github.com/golang-migrate/migrate/v4/database/pgx/v5" + "github.com/golang-migrate/migrate/v4/source/iofs" +) + +//go:embed migrations/*.sql +var migrationsFS embed.FS + +func Migrate(databaseURL string) error { + src, err := iofs.New(migrationsFS, "migrations") + if err != nil { + return err + } + m, err := migrate.NewWithSourceInstance("iofs", src, migrateURL(databaseURL)) + if err != nil { + return err + } + defer m.Close() + if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { + return err + } + return nil +} + +func migrateURL(databaseURL string) string { + for _, prefix := range []string{"postgresql://", "postgres://"} { + if rest, ok := strings.CutPrefix(databaseURL, prefix); ok { + return "pgx5://" + rest + } + } + return databaseURL +} diff --git a/internal/repository/postgres/migrations/000001_init.down.sql b/internal/repository/postgres/migrations/000001_init.down.sql new file mode 100644 index 00000000..1ba630fa --- /dev/null +++ b/internal/repository/postgres/migrations/000001_init.down.sql @@ -0,0 +1,4 @@ +DROP TABLE IF EXISTS messages; +DROP TABLE IF EXISTS chat_members; +DROP TABLE IF EXISTS chats; +DROP TABLE IF EXISTS users; diff --git a/internal/repository/postgres/migrations/000001_init.up.sql b/internal/repository/postgres/migrations/000001_init.up.sql new file mode 100644 index 00000000..694ae232 --- /dev/null +++ b/internal/repository/postgres/migrations/000001_init.up.sql @@ -0,0 +1,32 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + position int NOT NULL, + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_id_idx ON chat_members (user_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users (id), + text text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); diff --git a/internal/repository/postgres/postgres_test.go b/internal/repository/postgres/postgres_test.go new file mode 100644 index 00000000..5029a08e --- /dev/null +++ b/internal/repository/postgres/postgres_test.go @@ -0,0 +1,106 @@ +package postgres_test + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + "uuid" + + "github.com/jackc/pgx/v5/pgxpool" + + "messenger/internal/domain" + "messenger/internal/repository/postgres" +) + +func newStore(t *testing.T) (*postgres.Store, *pgxpool.Pool) { + t.Helper() + dbURL := os.Getenv("TEST_DATABASE_URL") + if dbURL == "" { + t.Skip("TEST_DATABASE_URL is required") + } + if err := postgres.Migrate(dbURL); err != nil { + t.Fatal(err) + } + pool, err := postgres.NewPool(context.Background(), dbURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + return postgres.New(pool), pool +} + +func newUser(username string) domain.User { + return domain.User{ID: uuid.New(), Username: username, DisplayName: "Test", CreatedAt: time.Now().UTC()} +} + +func TestRegisterUsernameRace(t *testing.T) { + store, pool := newStore(t) + ctx := context.Background() + username := "race_" + uuid.New().String()[:8] + + const workers = 20 + var wg sync.WaitGroup + errs := make([]error, workers) + start := make(chan struct{}) + for i := range workers { + wg.Go(func() { + <-start + errs[i] = store.CreateUser(ctx, newUser(username), "hash") + }) + } + close(start) + wg.Wait() + + created := 0 + for _, err := range errs { + switch { + case err == nil: + created++ + case !errors.Is(err, domain.ErrConflict): + t.Errorf("unexpected error: %v", err) + } + } + if created != 1 { + t.Errorf("created %d users, want exactly 1", created) + } + var rows int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = $1`, username).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 1 { + t.Errorf("users rows = %d, want 1", rows) + } +} + +func TestCreateChatRollback(t *testing.T) { + store, pool := newStore(t) + ctx := context.Background() + alice := newUser("rb_" + uuid.New().String()[:8]) + if err := store.CreateUser(ctx, alice, "hash"); err != nil { + t.Fatal(err) + } + + chat := domain.Chat{ + ID: uuid.New(), + Title: "rollback", + MemberIDs: []uuid.UUID{alice.ID, uuid.New()}, + CreatedAt: time.Now().UTC(), + } + if err := store.CreateChat(ctx, chat); !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("CreateChat with unknown member: got %v, want ErrNotFound", err) + } + + var chats, members int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE id = $1`, chat.ID).Scan(&chats); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE chat_id = $1`, chat.ID).Scan(&members); err != nil { + t.Fatal(err) + } + if chats != 0 || members != 0 { + t.Errorf("after rollback: chats=%d chat_members=%d, want 0 and 0", chats, members) + } +} diff --git a/internal/repository/postgres/store.go b/internal/repository/postgres/store.go new file mode 100644 index 00000000..074e9c12 --- /dev/null +++ b/internal/repository/postgres/store.go @@ -0,0 +1,237 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + "uuid" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "messenger/internal/domain" +) + +const ( + maxConns = 10 + connectTimeout = 3 * time.Second + statementTimeout = "5000" +) + +type Store struct { + pool *pgxpool.Pool +} + +func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + return nil, err + } + cfg.MaxConns = maxConns + cfg.ConnConfig.ConnectTimeout = connectTimeout + cfg.ConnConfig.RuntimeParams["statement_timeout"] = statementTimeout + return pgxpool.NewWithConfig(ctx, cfg) +} + +func New(pool *pgxpool.Pool) *Store { + return &Store{pool: pool} +} + +func (s *Store) Ping(ctx context.Context) error { + return dbErr(s.pool.Ping(ctx)) +} + +func (s *Store) CreateUser(ctx context.Context, u domain.User, passwordHash string) error { + _, err := s.pool.Exec(ctx, + `INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`, + u.ID, u.Username, u.DisplayName, passwordHash, u.CreatedAt) + return dbErr(err) +} + +func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) { + var u domain.User + err := s.pool.QueryRow(ctx, + `SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id, + ).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt) + return u, dbErr(err) +} + +func (s *Store) GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) { + var u domain.User + var hash string + err := s.pool.QueryRow(ctx, + `SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1`, username, + ).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash) + return u, hash, dbErr(err) +} + +func (s *Store) CreateChat(ctx context.Context, c domain.Chat) error { + tx, err := s.pool.Begin(ctx) + if err != nil { + return dbErr(err) + } + defer tx.Rollback(ctx) + + if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, + c.ID, c.Title, c.CreatedAt); err != nil { + return dbErr(err) + } + for i, userID := range c.MemberIDs { + if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1, $2, $3)`, + c.ID, userID, i); err != nil { + return dbErr(err) + } + } + return dbErr(tx.Commit(ctx)) +} + +func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error) { + var c domain.Chat + err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, id). + Scan(&c.ID, &c.Title, &c.CreatedAt) + if err != nil { + return domain.Chat{}, dbErr(err) + } + chats := []domain.Chat{c} + if err := s.loadMembers(ctx, chats); err != nil { + return domain.Chat{}, err + } + return chats[0], nil +} + +func (s *Store) ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) { + var rows pgx.Rows + var err error + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 + ORDER BY c.created_at, c.id + LIMIT $2`, userID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 AND (c.created_at, c.id) > ($2, $3) + ORDER BY c.created_at, c.id + LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, false, dbErr(err) + } + chats, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Chat, error) { + var c domain.Chat + err := row.Scan(&c.ID, &c.Title, &c.CreatedAt) + return c, err + }) + if err != nil { + return nil, false, dbErr(err) + } + more := len(chats) > limit + if more { + chats = chats[:limit] + } + if err := s.loadMembers(ctx, chats); err != nil { + return nil, false, err + } + return chats, more, nil +} + +func (s *Store) loadMembers(ctx context.Context, chats []domain.Chat) error { + if len(chats) == 0 { + return nil + } + ids := make([]uuid.UUID, len(chats)) + index := make(map[uuid.UUID]int, len(chats)) + for i, c := range chats { + ids[i] = c.ID + index[c.ID] = i + } + rows, err := s.pool.Query(ctx, + `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1) ORDER BY chat_id, position`, ids) + if err != nil { + return dbErr(err) + } + defer rows.Close() + for rows.Next() { + var chatID, userID uuid.UUID + if err := rows.Scan(&chatID, &userID); err != nil { + return dbErr(err) + } + i := index[chatID] + chats[i].MemberIDs = append(chats[i].MemberIDs, userID) + } + return dbErr(rows.Err()) +} + +func (s *Store) CreateMessage(ctx context.Context, m domain.Message) error { + _, err := s.pool.Exec(ctx, + `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`, + m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt) + return dbErr(err) +} + +func (s *Store) ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) { + var rows pgx.Rows + var err error + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + ORDER BY created_at, id + LIMIT $2`, chatID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 AND (created_at, id) > ($2, $3) + ORDER BY created_at, id + LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, false, dbErr(err) + } + msgs, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Message, error) { + var m domain.Message + err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt) + return m, err + }) + if err != nil { + return nil, false, dbErr(err) + } + more := len(msgs) > limit + if more { + msgs = msgs[:limit] + } + return msgs, more, nil +} + +func dbErr(err error) error { + if err == nil { + return nil + } + if errors.Is(err, pgx.ErrNoRows) { + return domain.ErrNotFound + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + switch pgErr.Code { + case "23505": + return domain.ErrConflict + case "23503": + return domain.ErrNotFound + } + switch pgErr.Code[:2] { + case "08", "53", "57": + return fmt.Errorf("%w: %v", domain.ErrUnavailable, err) + } + return err + } + return fmt.Errorf("%w: %v", domain.ErrUnavailable, err) +} diff --git a/internal/repository/redis/sessions.go b/internal/repository/redis/sessions.go new file mode 100644 index 00000000..1c054cad --- /dev/null +++ b/internal/repository/redis/sessions.go @@ -0,0 +1,71 @@ +package redis + +import ( + "context" + "errors" + "fmt" + "time" + "uuid" + + goredis "github.com/redis/go-redis/v9" + + "messenger/internal/domain" +) + +const keyPrefix = "session:" + +type SessionStore struct { + client *goredis.Client +} + +func NewClient(url string) (*goredis.Client, error) { + opts, err := goredis.ParseURL(url) + if err != nil { + return nil, err + } + opts.PoolSize = 10 + opts.DialTimeout = 2 * time.Second + opts.ReadTimeout = time.Second + opts.WriteTimeout = time.Second + opts.MaxRetries = 0 + return goredis.NewClient(opts), nil +} + +func NewSessionStore(client *goredis.Client) *SessionStore { + return &SessionStore{client: client} +} + +func (s *SessionStore) Ping(ctx context.Context) error { + return cacheErr(s.client.Ping(ctx).Err()) +} + +func (s *SessionStore) Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error { + return cacheErr(s.client.SetArgs(ctx, keyPrefix+tokenHash, userID.String(), + goredis.SetArgs{ExpireAt: expiresAt}).Err()) +} + +func (s *SessionStore) Get(ctx context.Context, tokenHash string) (uuid.UUID, error) { + v, err := s.client.Get(ctx, keyPrefix+tokenHash).Result() + if errors.Is(err, goredis.Nil) { + return uuid.UUID{}, domain.ErrUnauthorized + } + if err != nil { + return uuid.UUID{}, cacheErr(err) + } + id, err := uuid.Parse(v) + if err != nil { + return uuid.UUID{}, domain.ErrUnauthorized + } + return id, nil +} + +func (s *SessionStore) Delete(ctx context.Context, tokenHash string) error { + return cacheErr(s.client.Del(ctx, keyPrefix+tokenHash).Err()) +} + +func cacheErr(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%w: %v", domain.ErrUnavailable, err) +} diff --git a/internal/router/router.go b/internal/router/router.go index baf8a98b..91d9b85c 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -20,9 +20,11 @@ func New(h *handler.Handler) http.Handler { r.Route("/api/v1", func(r chi.Router) { r.Post("/users", h.RegisterUser) + r.Post("/auth/sessions", h.CreateSession) r.Group(func(r chi.Router) { r.Use(h.Authenticate) + r.Delete("/auth/sessions/current", h.DeleteSession) r.Get("/users/me", h.CurrentUser) r.Post("/chats", h.CreateChat) r.Get("/chats", h.ListChats) diff --git a/internal/service/auth.go b/internal/service/auth.go new file mode 100644 index 00000000..698058af --- /dev/null +++ b/internal/service/auth.go @@ -0,0 +1,74 @@ +package service + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "time" + + "messenger/internal/domain" +) + +const tokenBytes = 32 + +type AuthService struct { + users UserRepository + sessions SessionStore + ttl time.Duration +} + +func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService { + return &AuthService{users: users, sessions: sessions, ttl: ttl} +} + +func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) { + user, hash, err := s.users.GetUserByUsername(ctx, username) + if errors.Is(err, domain.ErrNotFound) { + return domain.Session{}, domain.ErrUnauthorized + } + if err != nil { + return domain.Session{}, err + } + ok, err := verifyPassword(password, hash) + if err != nil { + return domain.Session{}, err + } + if !ok { + return domain.Session{}, domain.ErrUnauthorized + } + + raw := make([]byte, tokenBytes) + if _, err := rand.Read(raw); err != nil { + return domain.Session{}, err + } + token := base64.RawURLEncoding.EncodeToString(raw) + expiresAt := now().Add(s.ttl) + if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil { + return domain.Session{}, err + } + return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil +} + +func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) { + userID, err := s.sessions.Get(ctx, HashToken(token)) + if err != nil { + return domain.User{}, err + } + u, err := s.users.GetUser(ctx, userID) + if errors.Is(err, domain.ErrNotFound) { + return domain.User{}, domain.ErrUnauthorized + } + return u, err +} + +func (s *AuthService) Logout(ctx context.Context, token string) error { + return s.sessions.Delete(ctx, HashToken(token)) +} + +func HashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/service/password.go b/internal/service/password.go new file mode 100644 index 00000000..a52c4700 --- /dev/null +++ b/internal/service/password.go @@ -0,0 +1,60 @@ +package service + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +const ( + argonMemory = 19 * 1024 + argonTime = 2 + argonThreads = 1 + argonSaltLen = 16 + argonKeyLen = 32 +) + +var errBadHash = errors.New("malformed password hash") + +func hashPassword(password string) (string, error) { + salt := make([]byte, argonSaltLen) + if _, err := rand.Read(salt); err != nil { + return "", err + } + key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen) + b64 := base64.RawStdEncoding + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil +} + +func verifyPassword(password, encoded string) (bool, error) { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return false, errBadHash + } + var version int + var memory, time uint32 + var threads uint8 + if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version { + return false, errBadHash + } + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil { + return false, errBadHash + } + b64 := base64.RawStdEncoding + salt, err := b64.DecodeString(parts[4]) + if err != nil { + return false, errBadHash + } + want, err := b64.DecodeString(parts[5]) + if err != nil { + return false, errBadHash + } + got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want))) + return subtle.ConstantTimeCompare(got, want) == 1, nil +} diff --git a/internal/service/ports.go b/internal/service/ports.go index ae3f4f76..ce75a6ed 100644 --- a/internal/service/ports.go +++ b/internal/service/ports.go @@ -9,8 +9,9 @@ import ( ) type UserRepository interface { - CreateUser(ctx context.Context, u domain.User) error + CreateUser(ctx context.Context, u domain.User, passwordHash string) error GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) + GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) } type ChatRepository interface { @@ -24,6 +25,12 @@ type MessageRepository interface { ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) } +type SessionStore interface { + Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error + Get(ctx context.Context, tokenHash string) (uuid.UUID, error) + Delete(ctx context.Context, tokenHash string) error +} + func now() time.Time { return time.Now().UTC().Truncate(time.Microsecond) } diff --git a/internal/service/users.go b/internal/service/users.go index e0499b11..f97e111c 100644 --- a/internal/service/users.go +++ b/internal/service/users.go @@ -2,9 +2,9 @@ package service import ( "context" - "errors" "fmt" "regexp" + "unicode/utf8" "uuid" "messenger/internal/domain" @@ -12,6 +12,11 @@ import ( var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) +const ( + minPasswordLen = 12 + maxPasswordLen = 128 +) + type UserService struct { repo UserRepository } @@ -20,29 +25,31 @@ func NewUserService(repo UserRepository) *UserService { return &UserService{repo: repo} } -func (s *UserService) Register(ctx context.Context, username, displayName string) (domain.User, error) { +func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) { if !usernameRe.MatchString(username) { return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput) } if err := checkText("display_name", displayName, 100); err != nil { return domain.User{}, err } + if err := checkText("password", password, maxPasswordLen); err != nil { + return domain.User{}, err + } + if utf8.RuneCountInString(password) < minPasswordLen { + return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen) + } + hash, err := hashPassword(password) + if err != nil { + return domain.User{}, err + } u := domain.User{ ID: uuid.New(), Username: username, DisplayName: displayName, CreatedAt: now(), } - if err := s.repo.CreateUser(ctx, u); err != nil { + if err := s.repo.CreateUser(ctx, u, hash); err != nil { return domain.User{}, err } return u, nil } - -func (s *UserService) Authenticate(ctx context.Context, id uuid.UUID) (domain.User, error) { - u, err := s.repo.GetUser(ctx, id) - if errors.Is(err, domain.ErrNotFound) { - return domain.User{}, domain.ErrUnauthorized - } - return u, err -} -- 2.54.0 From df7b8fb7010de0dd96c213ba028be9d6e838976c Mon Sep 17 00:00:00 2001 From: myDan Date: Fri, 30 Oct 2026 01:35:04 +0300 Subject: [PATCH 3/5] chore: add compose stack, restart hook and helper scripts --- .env.example | 2 +- Makefile | 9 +++++- compose.yaml | 69 +++++++++++++++++++++++++++++++++++++++++ scripts/explain.sh | 10 ++++++ scripts/explain.sql | 66 +++++++++++++++++++++++++++++++++++++++ scripts/init-secrets.sh | 18 +++++++++++ scripts/outage-demo.sh | 27 ++++++++++++++++ scripts/restart.sh | 7 +++++ 8 files changed, 206 insertions(+), 2 deletions(-) create mode 100644 compose.yaml create mode 100755 scripts/explain.sh create mode 100644 scripts/explain.sql create mode 100755 scripts/init-secrets.sh create mode 100755 scripts/outage-demo.sh create mode 100755 scripts/restart.sh diff --git a/.env.example b/.env.example index 714c8076..c3822416 100644 --- a/.env.example +++ b/.env.example @@ -7,5 +7,5 @@ SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres +SESSION_STORE=redis CACHE_URL_FILE=/run/secrets/cache_url diff --git a/Makefile b/Makefile index 9ecb223e..e6265ec4 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,16 @@ PYTHON ?= python3 BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= +COMPOSE ?= docker compose +TEST_DATABASE_URL ?= $(shell sed 's/@postgres:5432/@127.0.0.1:55432/' secrets/database_url 2>/dev/null) +TEST_REDIS_URL ?= redis://127.0.0.1:56379/0 TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +.PHONY: help check validate test load test-persistence test-go help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "test-go: Go unit/integration tests against the running stand (race, rollback, expiry, logout, outages)" check: $(PYTHON) scripts/check_contract.py @@ -24,3 +28,6 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-go: + TEST_DATABASE_URL="$(TEST_DATABASE_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" go test -count=1 -v ./... diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..903d369a --- /dev/null +++ b/compose.yaml @@ -0,0 +1,69 @@ +name: messenger + +services: + postgres: + image: docker.io/library/postgres:18.6-alpine3.24 + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql + ports: + - "127.0.0.1:55432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 3s + retries: 30 + restart: unless-stopped + + redis: + image: docker.io/library/redis:8.10.3-alpine3.23 + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redisdata:/data + ports: + - "127.0.0.1:56379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 3s + retries: 30 + restart: unless-stopped + + api: + build: . + image: localhost/messenger-api:lab2 + environment: + APP_HOST: 0.0.0.0 + APP_PORT: "8080" + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + secrets: + - database_url + - cache_url + ports: + - "8080:8080" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + restart: unless-stopped + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + +volumes: + pgdata: + redisdata: diff --git a/scripts/explain.sh b/scripts/explain.sh new file mode 100755 index 00000000..a6a5d4d2 --- /dev/null +++ b/scripts/explain.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +COMPOSE=${COMPOSE:-docker compose} + +{ + echo "# scripts/explain.sh; date: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + $COMPOSE exec -T postgres psql -U messenger -d messenger -X -q < scripts/explain.sql +} > evidence/explain.txt +cat evidence/explain.txt diff --git a/scripts/explain.sql b/scripts/explain.sql new file mode 100644 index 00000000..e8b02b5a --- /dev/null +++ b/scripts/explain.sql @@ -0,0 +1,66 @@ +\set ON_ERROR_STOP on +\set big_chat '''00000000-0000-4000-8000-00000000e001''' +\set seed_user '''00000000-0000-4000-8000-00000000e000''' + +INSERT INTO users (id, username, display_name, password_hash, created_at) +VALUES (:seed_user, 'explain_seed', 'Explain seed', 'not-a-login', now()) +ON CONFLICT DO NOTHING; + +INSERT INTO chats (id, title, created_at) +SELECT CASE WHEN g = 0 THEN :big_chat::uuid + ELSE ('00000000-0000-4000-8000-' || lpad(to_hex(57345 + g), 12, '0'))::uuid END, + 'explain chat ' || g, now() +FROM generate_series(0, 20) AS g +ON CONFLICT DO NOTHING; + +INSERT INTO chat_members (chat_id, user_id, position) +SELECT id, :seed_user, 0 FROM chats WHERE title LIKE 'explain chat %' +ON CONFLICT DO NOTHING; + +INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), c.id, :seed_user, 'synthetic message ' || n, + timestamptz '2026-01-01' + n * interval '1 second' +FROM chats c +CROSS JOIN LATERAL generate_series(1, CASE WHEN c.id = :big_chat THEN 20000 ELSE 2000 END) AS n +WHERE c.title LIKE 'explain chat %' + AND NOT EXISTS (SELECT 1 FROM messages m WHERE m.chat_id = c.id); + +ANALYZE users; +ANALYZE chats; +ANALYZE chat_members; +ANALYZE messages; + +SELECT count(*) AS messages_total, + count(*) FILTER (WHERE chat_id = :big_chat) AS messages_in_big_chat +FROM messages; + +SELECT created_at AS cur_ts, id AS cur_id +FROM messages WHERE chat_id = :big_chat +ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset + +\echo '=== 1. First page (limit=50 -> LIMIT 51), index messages_chat_created_id_idx' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = :big_chat +ORDER BY created_at, id +LIMIT 51; + +\echo '=== 2. Page in the middle by keyset cursor (after 10 000 messages)' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = :big_chat AND (created_at, id) > (:'cur_ts', :'cur_id') +ORDER BY created_at, id +LIMIT 51; + +\echo '=== 3. Same middle page WITHOUT the index (dropped inside a rolled-back transaction)' +BEGIN; +DROP INDEX messages_chat_created_id_idx; +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = :big_chat AND (created_at, id) > (:'cur_ts', :'cur_id') +ORDER BY created_at, id +LIMIT 51; +ROLLBACK; diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..11e9661a --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +mkdir -p secrets +chmod 700 secrets + +if [ ! -f secrets/postgres_password ]; then + head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > secrets/postgres_password +fi +password=$(cat secrets/postgres_password) + +[ -f secrets/database_url ] || + printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$password" > secrets/database_url +[ -f secrets/cache_url ] || + printf 'redis://redis:6379/0\n' > secrets/cache_url + +chmod 644 secrets/postgres_password secrets/database_url secrets/cache_url +echo "secrets ready in ./secrets" diff --git a/scripts/outage-demo.sh b/scripts/outage-demo.sh new file mode 100755 index 00000000..35676036 --- /dev/null +++ b/scripts/outage-demo.sh @@ -0,0 +1,27 @@ +#!/bin/sh +set -u +cd "$(dirname "$0")/.." +B=http://localhost:8080 +C=${COMPOSE:-docker compose} +u="outage_$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')"; p="Outage-demo-password" +code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } +wait_ready() { for i in $(seq 1 60); do [ "$(code $B/health/ready)" = 200 ] && return; sleep 1; done; } +echo "# Dependency outage demo on the live stand; date: $(date -u +%Y-%m-%dT%H:%M:%SZ). Token is kept in a shell variable, never printed." +curl -s -o /dev/null -X POST $B/api/v1/users -H 'Content-Type: application/json' -d "{\"username\":\"$u\",\"display_name\":\"Demo\",\"password\":\"$p\"}" +T=$(curl -s -X POST $B/api/v1/auth/sessions -u "$u:$p" | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])') +echo "baseline: GET /users/me (Bearer) -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")" +echo; echo "## $C stop redis"; $C stop redis >/dev/null 2>&1 +echo "GET /health/ready -> $(code $B/health/ready)" +echo "GET /users/me (valid Bearer) -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")" +echo "GET /users/me (no auth) -> $(code $B/api/v1/users/me)" +echo "POST /auth/sessions (Basic) -> $(code -X POST $B/api/v1/auth/sessions -u "$u:$p")" +echo "body: $(curl -s $B/api/v1/users/me -H "Authorization: Bearer $T")" +$C start redis >/dev/null 2>&1; wait_ready +echo "## $C start redis -> ready; same token: GET /users/me -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")" +echo; echo "## $C stop postgres"; $C stop postgres >/dev/null 2>&1 +echo "GET /health/ready -> $(code $B/health/ready)" +echo "GET /users/me (valid Bearer) -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")" +echo "GET /chats (valid Bearer) -> $(code $B/api/v1/chats -H "Authorization: Bearer $T")" +echo "body: $(curl -s $B/api/v1/chats -H "Authorization: Bearer $T")" +$C start postgres >/dev/null 2>&1; wait_ready +echo "## $C start postgres -> ready; same token: GET /users/me -> $(code $B/api/v1/users/me -H "Authorization: Bearer $T")" diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..a0c69b8f --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +COMPOSE=${COMPOSE:-docker compose} + +$COMPOSE stop api postgres redis +$COMPOSE start postgres redis api -- 2.54.0 From 02a55ad29e3c2e5935c95c94409e2faecb432ba2 Mon Sep 17 00:00:00 2001 From: myDan Date: Fri, 30 Oct 2026 01:40:38 +0300 Subject: [PATCH 4/5] docs: fill report --- REPORT.md | 108 ++++++++++++++++++++++++++++++++------- evidence/explain.txt | 53 +++++++++++++++++++ evidence/outage.txt | 18 +++++++ evidence/persistence.txt | 26 ++++++++++ evidence/smoke.txt | 5 ++ evidence/test-go.txt | 18 +++++++ 6 files changed, 209 insertions(+), 19 deletions(-) create mode 100644 evidence/explain.txt create mode 100644 evidence/outage.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/test-go.txt diff --git a/REPORT.md b/REPORT.md index e42f2b05..e1d2f444 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,107 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Спесивцев Даниил БПИ2301 +- Целевая оценка 4; выбранный трек 5, если нужен: +- Commit/PR: commit "df7b8fb7010de0dd96c213ba028be9d6e838976c" +- Использованные источники, библиотеки и помощь ИИ: Go 1.27.1 (стандартная библиотека). Для консультации, реализации некоторых фич, написания отчета использовались LLM. Библиотеки: + - [go-chi/chi v5.3.2](https://github.com/go-chi/chi) — HTTP-роутинг; + - [jackc/pgx v5.11.0](https://github.com/jackc/pgx) — драйвер PostgreSQL и пул соединений `pgxpool`; + - [golang-migrate/migrate v4.20.1](https://github.com/golang-migrate/migrate) — версионируемые миграции; + - [redis/go-redis v9.23.0](https://github.com/redis/go-redis) — клиент Redis для сессий; + - [golang.org/x/crypto v0.58.0](https://pkg.go.dev/golang.org/x/crypto/argon2) — Argon2id для хеширования паролей. -## Запуск из чистого clone +## Запуск из clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Тестовый стенд: i5-11400H, 16 GB RAM, без лимитов на контейнеры + +Образы: `postgres:18.6-alpine3.24`, `redis:8.10.3-alpine3.23`; API собирается из `Dockerfile` (`golang:1.27.1-alpine3.24` → `alpine:3.24.1`). `COMPOSE` по умолчанию `docker compose`, для podman: `export COMPOSE="podman compose"`. + +```sh +scripts/init-secrets.sh && cp .env.example .env # локальные secrets, вне Git +$COMPOSE --env-file .env up -d --build # миграции применяет API при старте +until curl -sf http://localhost:8080/health/ready; do sleep 1; done + +make check && make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-go # Go-тесты уровня 4 +scripts/explain.sh # → evidence/explain.txt +scripts/outage-demo.sh # отказ Redis/PostgreSQL + +$COMPOSE down # остановка, данные сохраняются +$COMPOSE down -v # удаление учебных данных +``` ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` +клиент ──HTTP:8080──▶ api (Go) ──pgx pool──▶ postgres [volume pgdata] + └─go-redis──▶ redis [volume redisdata, AOF] +``` + +- **Источник истины:** PostgreSQL — пользователи, чаты, участники, сообщения. Redis — единственное хранилище сессий (COURSE.md допускает сессии в Redis/Valkey), поэтому включён AOF (`appendfsync everysec`). +- **Сессии:** + - токен — 32 байта из `crypto/rand`, base64url; + - в Redis хранится `session: → user_id` командой `SET ... EXAT`. Срок абсолютный, рестарт его не продлевает; + - logout = `DEL`; + - после `FLUSHALL` или потери volume Redis все сессии теряются, пользователи входят заново, данные в PG не затрагиваются. +- **Пароли:** Argon2id (m=19 MiB, t=2, p=1), формат PHC, проверка через `subtle.ConstantTimeCompare`. +- **Транзакции:** `POST /chats` — `chats` + `chat_members` в одной транзакции, неизвестный участник (FK 23503) → rollback → 400. Уникальность username обеспечивает `UNIQUE` (23505 → 409). +- **Миграции:** golang-migrate, SQL встроен в бинарник через `embed`, версия в `schema_migrations`, повторный запуск — no-op. +- **Схема:** + - `users` (`UNIQUE username`); + - `chats`; + - `chat_members` (PK `(chat_id,user_id)`, индекс `(user_id)`); + - `messages` (индекс `(chat_id, created_at, id)`). +- **БД и Redis:** запросы только параметризованные. Pool pgx `MaxConns=10`, `ConnectTimeout=3s`, `statement_timeout=5s`. Redis `PoolSize=10`, таймауты 1–2 с. +- **Отказы:** ошибки соединения и SQLSTATE классов 08/53/57 → `503 unavailable`. Критичны PG и Redis: `/health/ready` проверяет оба. Без Redis запрос с токеном получает 503, а не анонимный доступ. +- **Переход с lab1:** + - `password` при регистрации; + - Basic только на `POST /auth/sessions`, на остальных Bearer; + - `X-User-Id` игнорируется; + - in-memory хранилище заменено на PG и Redis. +- **`.env.example`:** + - `SESSION_TTL_SECONDS` → TTL сессии; + - `DATABASE_URL_FILE`, `CACHE_URL_FILE` → файлы-secrets; + - `SESSION_STORE=redis` только документирует выбор. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| Критерий | Команда | Результат | Файл | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Публичный smoke | `make check && make test` | PASS | `evidence/smoke.txt` | +| 3: данные и сессии переживают рестарт | `make test-persistence` | PASS; все 3 контейнера перезапущены, volumes те же | `evidence/persistence.txt` | +| 3: миграции повторно без дублей | рестарт стенда | `schema_migrations=1, dirty=f` до и после | `evidence/persistence.txt` | +| 3/4: атомарность и rollback чата | `TestCreateChatRollback` | 0 строк в `chats`/`chat_members` | `evidence/test-go.txt` | +| 3: Basic/Bearer, `X-User-Id` не даёт доступа | smoke | PASS | `evidence/smoke.txt` | +| 4: Redis — сессии с TTL и persistence | `make test-persistence` | прежний токен работает после рестарта Redis | `evidence/persistence.txt` | +| 4: гонка регистрации username | `TestRegisterUsernameRace` | из 20 параллельных запросов 1 успех, 19 conflict | `evidence/test-go.txt` | +| 4: индекс + EXPLAIN на ≥10 000 | `scripts/explain.sh` | Index Scan, 4–5 буферов | `evidence/explain.txt` | +| 4: expiry, logout, неверный пароль | `TestSessionExpiry`, `TestLogout`, `TestWrongPassword` | 401 с нужным `WWW-Authenticate` | `evidence/test-go.txt` | +| 4: недоступность Redis/БД | `TestRedisUnavailable`, `TestDatabaseUnavailable`, `scripts/outage-demo.sh` | 503; без токена 401; после старта тот же токен 200 | `evidence/test-go.txt`, `evidence/outage.txt` | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +## EXPLAIN истории + +Запрос API: `WHERE chat_id=$1 AND (created_at,id) > ($2,$3) ORDER BY created_at,id LIMIT 51`. Данные: 60 328 сообщений, 20 000 из них в одном чате. + +| План | Узел | Buffers | Время | +| --- | --- | --- | --- | +| Первая страница | Index Scan `messages_chat_created_id_idx` | 4 | 0.024 ms | +| Страница после 10 000 сообщений | Index Scan, cursor в `Index Cond` | 5 | 0.042 ms | +| Та же без индекса | Seq Scan (отброшено 50 328 строк) + Sort | 819 | 3.492 ms | + +Индекс совпадает с фильтром и порядком сортировки, поэтому страница читает ровно 51 запись при любой глубине cursor. Цена индекса — дополнительное обновление B-tree на каждую вставку. ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. - -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| Воздействие | Ожидание | Наблюдение | Восстановление / потери | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `restart.sh` (API, PG, Redis) | данные и токен сохраняются | PASS | потерь нет | +| `stop redis` | 503, без токена 401 | совпадает | после старта токен работает (AOF) | +| `stop postgres` | 503, ready 503 | совпадает | pool переподключается сам | -## Ограничения и следующие шаги +## Ограничения -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Один host, без HA и backup. При аварийном падении Redis возможна потеря сессий за последнюю секунду (`everysec`). +- Redis без пароля. Порты PG и Redis открыты только на `127.0.0.1`, они нужны для `make test-go`. +- HTTP допустим только на локальном стенде, TLS будет в lab7. +- Не реализовано, потому что не требуется контрактом: отказ на тело у `POST /auth/sessions`, выравнивание времени ответа для неизвестного username, кэш данных. diff --git a/evidence/explain.txt b/evidence/explain.txt new file mode 100644 index 00000000..db1529e4 --- /dev/null +++ b/evidence/explain.txt @@ -0,0 +1,53 @@ +# scripts/explain.sh; date: 2026-10-29T22:07:31Z + messages_total | messages_in_big_chat +----------------+---------------------- + 60328 | 20000 +(1 row) + +=== 1. First page (limit=50 -> LIMIT 51), index messages_chat_created_id_idx + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.41..8.31 rows=51 width=78) (actual time=0.009..0.014 rows=51.00 loops=1) + Buffers: shared hit=4 + -> Index Scan using messages_chat_created_id_idx on messages (cost=0.41..3088.25 rows=19942 width=78) (actual time=0.008..0.012 rows=51.00 loops=1) + Index Cond: (chat_id = '00000000-0000-4000-8000-00000000e001'::uuid) + Index Searches: 1 + Buffers: shared hit=4 + Planning: + Buffers: shared hit=10 + Planning Time: 0.077 ms + Execution Time: 0.024 ms +(10 rows) + +=== 2. Page in the middle by keyset cursor (after 10 000 messages) + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + Limit (cost=0.41..27.77 rows=51 width=78) (actual time=0.008..0.014 rows=51.00 loops=1) + Buffers: shared hit=5 + -> Index Scan using messages_chat_created_id_idx on messages (cost=0.41..1834.26 rows=3419 width=78) (actual time=0.008..0.012 rows=51.00 loops=1) + Index Cond: ((chat_id = '00000000-0000-4000-8000-00000000e001'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:46:40+00'::timestamp with time zone, 'ea1e0a08-377a-4911-aa17-221192625ad3'::uuid))) + Index Searches: 1 + Buffers: shared hit=5 + Planning Time: 0.035 ms + Execution Time: 0.042 ms +(8 rows) + +=== 3. Same middle page WITHOUT the index (dropped inside a rolled-back transaction) + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=1988.81..1988.93 rows=51 width=78) (actual time=3.462..3.467 rows=51.00 loops=1) + Buffers: shared hit=819 + -> Sort (cost=1988.81..1997.35 rows=3419 width=78) (actual time=3.462..3.464 rows=51.00 loops=1) + Sort Key: created_at, id + Sort Method: top-N heapsort Memory: 31kB + Buffers: shared hit=819 + -> Seq Scan on messages (cost=0.00..1874.74 rows=3419 width=78) (actual time=0.498..2.888 rows=10000.00 loops=1) + Filter: ((chat_id = '00000000-0000-4000-8000-00000000e001'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:46:40+00'::timestamp with time zone, 'ea1e0a08-377a-4911-aa17-221192625ad3'::uuid))) + Rows Removed by Filter: 50328 + Buffers: shared hit=819 + Planning: + Buffers: shared hit=4 + Planning Time: 0.052 ms + Execution Time: 3.492 ms +(14 rows) + diff --git a/evidence/outage.txt b/evidence/outage.txt new file mode 100644 index 00000000..a75c4d2f --- /dev/null +++ b/evidence/outage.txt @@ -0,0 +1,18 @@ +# scripts/outage-demo.sh (COMPOSE="podman compose") +# Dependency outage demo on the live stand; date: 2026-10-29T22:09:23Z. Token is kept in a shell variable, never printed. +baseline: GET /users/me (Bearer) -> 200 + +## podman compose stop redis +GET /health/ready -> 503 +GET /users/me (valid Bearer) -> 503 +GET /users/me (no auth) -> 401 +POST /auth/sessions (Basic) -> 503 +body: {"error":{"code":"unavailable","message":"service temporarily unavailable","request_id":"0fc08a63-dc18-4508-a95e-7274844d13c8"}} +## podman compose start redis -> ready; same token: GET /users/me -> 200 + +## podman compose stop postgres +GET /health/ready -> 503 +GET /users/me (valid Bearer) -> 503 +GET /chats (valid Bearer) -> 503 +body: {"error":{"code":"unavailable","message":"service temporarily unavailable","request_id":"43f47140-394e-461e-b5bc-1863a33fc6da"}} +## podman compose start postgres -> ready; same token: GET /users/me -> 200 diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..4ef7430f --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,26 @@ +# make test-persistence ACTION_SCRIPT=scripts/restart.sh (COMPOSE="podman compose") +# date: 2026-10-29T22:09:51Z; podman 6.1.0, podman-compose 1.6.0 + +## containers before +messenger_api_1 id=e8951624fe7a started=2026-10-30 01:09:02.81809688 +0300 MSK +messenger_postgres_1 id=6aab8ebe96dd started=2026-10-30 01:09:30.742003352 +0300 MSK +messenger_redis_1 id=7af579a966dd started=2026-10-30 01:09:28.731706375 +0300 MSK +schema_migrations (version|dirty): 1|f +rows users|chats|messages: 111|43|60437 + +## test +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +## containers after (same IDs, new start time = real restart, volumes kept) +messenger_api_1 id=e8951624fe7a started=2026-10-30 01:09:54.107586909 +0300 MSK +messenger_postgres_1 id=6aab8ebe96dd started=2026-10-30 01:09:53.97943161 +0300 MSK +messenger_redis_1 id=7af579a966dd started=2026-10-30 01:09:54.047665509 +0300 MSK +schema_migrations (version|dirty): 1|f +rows users|chats|messages: 114|44|60438 (test adds 3 users, 1 chat, 1 message) +api log after restart: "msg":"migrations applied" + +## volumes +messenger_pgdata +messenger_redisdata diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..8f332ce5 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,5 @@ +# make check && make test; date: 2026-10-29T22:09:30Z +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/test-go.txt b/evidence/test-go.txt new file mode 100644 index 00000000..9804c7d6 --- /dev/null +++ b/evidence/test-go.txt @@ -0,0 +1,18 @@ +# make test-go; date: 2026-10-29T22:09:31Z; go version go1.27.1 linux/amd64 +--- PASS: TestSessionExpiry (3.10s) +--- PASS: TestLogout (0.07s) +--- PASS: TestWrongPassword (0.09s) +--- PASS: TestRedisUnavailable (2.80s) +--- PASS: TestDatabaseUnavailable (0.16s) +--- PASS: TestInvalidJSON (0.01s) +--- PASS: TestForeignChat (0.16s) +--- PASS: TestEmptyMessage (0.07s) +--- PASS: TestDuplicateUsername (0.09s) +--- PASS: TestPaginationMultiplePages (0.08s) +--- PASS: TestConcurrentMessages (0.50s) +PASS +ok messenger/internal/handler 7.128s +--- PASS: TestRegisterUsernameRace (0.08s) +--- PASS: TestCreateChatRollback (0.03s) +PASS +ok messenger/internal/repository/postgres 0.109s -- 2.54.0 From 2ba6991c6cb1dda6d40467401d8f899194b4beed Mon Sep 17 00:00:00 2001 From: myDan Date: Fri, 30 Oct 2026 01:46:45 +0300 Subject: [PATCH 5/5] fix: hide database URL in test-go output and complete report infra section --- Makefile | 2 +- REPORT.md | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index e6265ec4..6ad460bd 100644 --- a/Makefile +++ b/Makefile @@ -30,4 +30,4 @@ test-persistence: $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) test-go: - TEST_DATABASE_URL="$(TEST_DATABASE_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" go test -count=1 -v ./... + @TEST_DATABASE_URL="$(TEST_DATABASE_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" go test -count=1 -v ./... diff --git a/REPORT.md b/REPORT.md index e1d2f444..da2cec41 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,7 +1,7 @@ # Отчёт — лабораторная 2 - Автор, группа: Спесивцев Даниил БПИ2301 -- Целевая оценка 4; выбранный трек 5, если нужен: +- Целевая оценка 4; выбранный трек 5, если нужен: не заявлен - Commit/PR: commit "df7b8fb7010de0dd96c213ba028be9d6e838976c" - Использованные источники, библиотеки и помощь ИИ: Go 1.27.1 (стандартная библиотека). Для консультации, реализации некоторых фич, написания отчета использовались LLM. Библиотеки: - [go-chi/chi v5.3.2](https://github.com/go-chi/chi) — HTTP-роутинг; @@ -27,6 +27,9 @@ make test-go # Go-тесты уровн scripts/explain.sh # → evidence/explain.txt scripts/outage-demo.sh # отказ Redis/PostgreSQL +# проверка expiry на стенде (сценарий защиты): короткий TTL, затем вернуть 3600 +SESSION_TTL_SECONDS=2 $COMPOSE --env-file .env up -d --force-recreate --no-deps api + $COMPOSE down # остановка, данные сохраняются $COMPOSE down -v # удаление учебных данных ``` @@ -38,6 +41,14 @@ $COMPOSE down -v # удаление уче └─go-redis──▶ redis [volume redisdata, AOF] ``` +| Роль | Service | Образ | Health | Volume | Порт | Credentials | +| --- | --- | --- | --- | --- | --- | --- | +| api | `api` | сборка из `Dockerfile` | `/health/ready` (PG + Redis) | — | `8080` | secrets `database_url`, `cache_url` | +| postgres | `postgres` | `postgres:18.6-alpine3.24` | `pg_isready` | `pgdata` | `127.0.0.1:55432` | secret `postgres_password` | +| redis | `redis` | `redis:8.10.3-alpine3.23` | `redis-cli ping` | `redisdata` | `127.0.0.1:56379` | без пароля | + +Bootstrap: `scripts/init-secrets.sh` создаёт secrets, БД и пользователя создаёт образ postgres, схему — миграции при старте API. Всё безопасно повторять. + - **Источник истины:** PostgreSQL — пользователи, чаты, участники, сообщения. Redis — единственное хранилище сессий (COURSE.md допускает сессии в Redis/Valkey), поэтому включён AOF (`appendfsync everysec`). - **Сессии:** - токен — 32 байта из `crypto/rand`, base64url; -- 2.54.0