chore(solution): pull lab1 solution

This commit is contained in:
2026-10-29 10:47:47 +03:00
parent 65003b6119
commit 196e118ede
26 changed files with 1424 additions and 0 deletions
+11
View File
@@ -18,3 +18,14 @@ __pycache__
node_modules
evidence
.DS_Store
assets
contracts
examples
scripts
tests
*.md
Makefile
lab.json
requirements-dev.txt
Dockerfile*
.dockerignore
+17
View File
@@ -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"]
+59
View File
@@ -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")
}
+5
View File
@@ -0,0 +1,5 @@
module messenger
go 1.27.1
require github.com/go-chi/chi/v5 v5.3.2
+2
View File
@@ -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=
+29
View File
@@ -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
}
+55
View File
@@ -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
}
+10
View File
@@ -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")
)
+104
View File
@@ -0,0 +1,104 @@
package handler
import (
"net/http"
"strconv"
"uuid"
"github.com/go-chi/chi/v5"
"messenger/internal/domain"
"messenger/internal/service"
)
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
var req createChatRequest
if err := decodeJSON(w, r, &req); err != nil {
h.fail(w, r, err)
return
}
if req.Title == nil || req.MemberIDs == nil {
h.fail(w, r, badRequest("title and member_ids are required"))
return
}
memberIDs := make([]uuid.UUID, len(*req.MemberIDs))
for i, s := range *req.MemberIDs {
id, ok := parseUUID(s)
if !ok {
h.fail(w, r, badRequest("member_ids must contain UUIDs"))
return
}
memberIDs[i] = id
}
chat, err := h.chats.Create(r.Context(), actor(r), *req.Title, memberIDs)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toChatResponse(chat))
}
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
limit, cursor, err := pageParams(r)
if err != nil {
h.fail(w, r, err)
return
}
page, err := h.chats.List(r.Context(), actor(r), cursor, limit)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toPageResponse(page, toChatResponse))
}
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
chatID, err := chatIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
chat, err := h.chats.Get(r.Context(), actor(r), chatID)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toChatResponse(chat))
}
func chatIDParam(r *http.Request) (uuid.UUID, error) {
id, ok := parseUUID(chi.URLParam(r, "chat_id"))
if !ok {
return uuid.UUID{}, badRequest("chat_id must be a UUID")
}
return id, nil
}
func parseUUID(s string) (uuid.UUID, bool) {
if len(s) != 36 {
return uuid.UUID{}, false
}
id, err := uuid.Parse(s)
return id, err == nil
}
func pageParams(r *http.Request) (int, *domain.Cursor, error) {
q := r.URL.Query()
limit := service.DefaultLimit
if q.Has("limit") {
n, err := strconv.Atoi(q.Get("limit"))
if err != nil {
return 0, nil, badRequest("limit must be an integer")
}
limit = n
}
var cursor *domain.Cursor
if q.Has("cursor") {
c, ok := decodeCursor(q.Get("cursor"))
if !ok {
return 0, nil, badRequest("invalid cursor")
}
cursor = &c
}
return limit, cursor, nil
}
+34
View File
@@ -0,0 +1,34 @@
package handler
import (
"encoding/base64"
"strconv"
"strings"
"time"
"uuid"
"messenger/internal/domain"
)
func encodeCursor(c domain.Cursor) string {
raw := c.Scope.String() + "." + strconv.FormatInt(c.CreatedAt.UnixMicro(), 10) + "." + c.ID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func decodeCursor(s string) (domain.Cursor, bool) {
raw, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return domain.Cursor{}, false
}
parts := strings.Split(string(raw), ".")
if len(parts) != 3 {
return domain.Cursor{}, false
}
scope, err1 := uuid.Parse(parts[0])
micros, err2 := strconv.ParseInt(parts[1], 10, 64)
id, err3 := uuid.Parse(parts[2])
if err1 != nil || err2 != nil || err3 != nil {
return domain.Cursor{}, false
}
return domain.Cursor{Scope: scope, CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, true
}
+111
View File
@@ -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
}
+48
View File
@@ -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")
}
}
+27
View File
@@ -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")
}
+237
View File
@@ -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"])
}
}
+11
View File
@@ -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"})
}
+86
View File
@@ -0,0 +1,86 @@
package handler
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"reflect"
"strings"
"unicode/utf8"
)
const maxBodyBytes = 1 << 20
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mt != "application/json" {
return &apiError{http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json"}
}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, "payload_too_large", "request body is too large"}
}
return badRequest("failed to read request body")
}
if !utf8.Valid(raw) {
return badRequest("request body must be valid UTF-8")
}
if err := checkKeys(raw, dst); err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return badRequest("request body must be a valid JSON object matching the schema")
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return badRequest("request body must contain a single JSON object")
}
return nil
}
func checkKeys(raw []byte, dst any) error {
allowed := jsonFields(dst)
dec := json.NewDecoder(bytes.NewReader(raw))
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
return badRequest("request body must be a JSON object")
}
for dec.More() {
tok, err := dec.Token()
if err != nil {
return badRequest("request body must be a valid JSON object matching the schema")
}
key, _ := tok.(string)
if !allowed[key] {
return badRequest("request body contains unknown field")
}
var value json.RawMessage
if err := dec.Decode(&value); err != nil {
return badRequest("request body must be a valid JSON object matching the schema")
}
}
return nil
}
func jsonFields(dst any) map[string]bool {
t := reflect.TypeOf(dst).Elem()
fields := make(map[string]bool, t.NumField())
for i := range t.NumField() {
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
fields[name] = true
}
return fields
}
+45
View File
@@ -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))
}
+91
View File
@@ -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
}
+25
View File
@@ -0,0 +1,25 @@
package handler
import "net/http"
func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) {
var req createUserRequest
if err := decodeJSON(w, r, &req); err != nil {
h.fail(w, r, err)
return
}
if req.Username == nil || req.DisplayName == nil {
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)))
}
+133
View File
@@ -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)
}
+35
View File
@@ -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
}
+81
View File
@@ -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
}
+60
View File
@@ -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
}
+29
View File
@@ -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)
}
+48
View File
@@ -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
}
+31
View File
@@ -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
}