diff --git a/.dockerignore b/.dockerignore index bc16e556..94f7c95a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,12 @@ __pycache__ node_modules evidence .DS_Store +bin +coverage +*.out +*.test +**/*_test.go +cmd/*_test.go +internal/api/*_test.go +internal/store/*_test.go +internal/config/*_test.go diff --git a/.env.example b/.env.example index 714c8076..4152e9fd 100644 --- a/.env.example +++ b/.env.example @@ -3,9 +3,5 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab -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 -CACHE_URL_FILE=/run/secrets/cache_url +# SIGTERM budget. Must stay within 1..10 seconds. +SHUTDOWN_TIMEOUT_SECONDS=8 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..22a27b71 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +FROM golang:1.25-bookworm AS build +WORKDIR /src +COPY go.mod ./ +COPY cmd ./cmd +COPY internal ./internal +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ + go build -trimpath -ldflags='-s -w' -o /out/messenger ./cmd/messenger \ + && chmod 755 /out/messenger + +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab +COPY --from=build --chown=65532:65532 /out/messenger /messenger +USER 65532:65532 +ENV APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + APP_ENV=lab \ + SHUTDOWN_TIMEOUT_SECONDS=8 +EXPOSE 8080 +HEALTHCHECK --interval=5s --timeout=3s --start-period=3s --retries=3 \ + CMD ["/messenger", "healthcheck"] +ENTRYPOINT ["/messenger"] diff --git a/Makefile b/Makefile index 9ecb223e..7108e3fe 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,10 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +.PHONY: help check validate test load test-own help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; test-own: Go tests" check: $(PYTHON) scripts/check_contract.py @@ -21,6 +21,5 @@ test: load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) -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-own: + go test ./... diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..7a1e48bf --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module messenger + +go 1.25.0 diff --git a/internal/api/handlers.go b/internal/api/handlers.go new file mode 100644 index 00000000..2543d072 --- /dev/null +++ b/internal/api/handlers.go @@ -0,0 +1,312 @@ +package api + +import ( + "net/http" + "strings" + + "messenger/internal/store" +) + +func (a *API) live(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) +} + +func (a *API) ready(w http.ResponseWriter, r *http.Request) { + if a.shutting.Load() { + a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1) + return + } + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) +} + +func (a *API) route(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case path == "/api/v1/users" && r.Method == http.MethodPost: + a.createUser(w, r) + case path == "/api/v1/users/me" && r.Method == http.MethodGet: + a.currentUser(w, r) + case path == "/api/v1/chats" && r.Method == http.MethodPost: + a.createChat(w, r) + case path == "/api/v1/chats" && r.Method == http.MethodGet: + a.listChats(w, r) + default: + chatID, messages, ok := splitChatPath(path) + if !ok { + if knownWrongMethod(path) { + a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0) + return + } + a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0) + return + } + switch { + case !messages && r.Method == http.MethodGet: + a.getChat(w, r, chatID) + case messages && r.Method == http.MethodPost: + a.createMessage(w, r, chatID) + case messages && r.Method == http.MethodGet: + a.listMessages(w, r, chatID) + default: + a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0) + } + } +} + +func knownWrongMethod(path string) bool { + switch path { + case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats": + return true + default: + return false + } +} + +func (a *API) createUser(w http.ResponseWriter, r *http.Request) { + var body struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + } + if !a.readJSON(w, r, &body) { + return + } + if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 0) + return + } + user, err := a.store.CreateUser(body.Username, body.DisplayName) + if err == store.ErrConflict { + a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0) + return + } + if err != nil { + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + return + } + writeJSON(w, http.StatusCreated, asUser(user)) +} + +func (a *API) currentUser(w http.ResponseWriter, r *http.Request) { + user, ok := a.authenticate(w, r) + if !ok { + return + } + writeJSON(w, http.StatusOK, asUser(user)) +} + +func (a *API) createChat(w http.ResponseWriter, r *http.Request) { + caller, ok := a.authenticate(w, r) + if !ok { + return + } + var body struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + } + if !a.readJSON(w, r, &body) { + return + } + if !validText(body.Title, 1, 100) || len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля чата", 0) + return + } + ids := make([]string, len(body.MemberIDs)) + seen := make(map[string]struct{}, len(body.MemberIDs)) + callerIn := false + for i, raw := range body.MemberIDs { + id, ok := canonicalUUID(raw) + if !ok { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0) + return + } + if _, dup := seen[id]; dup { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0) + return + } + seen[id] = struct{}{} + if _, exists := a.store.User(id); !exists { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0) + return + } + if id == caller.ID { + callerIn = true + } + ids[i] = id + } + if !callerIn { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0) + return + } + chat, err := a.store.CreateChat(body.Title, ids, caller.ID) + switch err { + case nil: + writeJSON(w, http.StatusCreated, asChat(chat)) + case store.ErrInvalid: + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0) + default: + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + } +} + +func (a *API) listChats(w http.ResponseWriter, r *http.Request) { + user, ok := a.authenticate(w, r) + if !ok { + return + } + limit, cur, ok := a.pageQuery(w, r, "chats:"+user.ID) + if !ok { + return + } + items, hasMore, err := a.store.ListChats(user.ID, cur, limit) + if err == store.ErrBadCursor { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0) + return + } + if err != nil { + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + return + } + out := make([]chatJSON, 0, len(items)) + for _, c := range items { + out = append(out, asChat(c)) + } + var next *string + if hasMore && len(items) > 0 { + last := items[len(items)-1] + encoded := encodeCursor(cursorPayload{Scope: "chats:" + user.ID, ID: last.ID, At: formatTime(last.CreatedAt)}) + next = &encoded + } + writeJSON(w, http.StatusOK, chatPage{Items: out, NextCursor: next}) +} + +func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) { + user, ok := a.authenticate(w, r) + if !ok { + return + } + id, ok := a.chatID(w, r, rawID) + if !ok { + return + } + chat, err := a.store.ChatFor(id, user.ID) + if err == store.ErrNotFound { + a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0) + return + } + if err != nil { + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + return + } + writeJSON(w, http.StatusOK, asChat(chat)) +} + +func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string) { + user, ok := a.authenticate(w, r) + if !ok { + return + } + id, ok := a.chatID(w, r, rawID) + if !ok { + return + } + if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound { + a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0) + return + } else if err != nil { + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + return + } + var body struct { + Text string `json:"text"` + } + if !a.readJSON(w, r, &body) { + return + } + if !validText(body.Text, 1, 4000) { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0) + return + } + msg, err := a.store.AddMessage(id, user.ID, body.Text) + switch err { + case nil: + writeJSON(w, http.StatusCreated, asMessage(msg)) + case store.ErrNotFound: + a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0) + default: + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + } +} + +func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string) { + user, ok := a.authenticate(w, r) + if !ok { + return + } + id, ok := a.chatID(w, r, rawID) + if !ok { + return + } + if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound { + a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0) + return + } else if err != nil { + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + return + } + limit, cur, ok := a.pageQuery(w, r, "msg:"+id) + if !ok { + return + } + items, hasMore, err := a.store.ListMessages(id, user.ID, cur, limit) + if err == store.ErrBadCursor { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0) + return + } + if err == store.ErrNotFound { + a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0) + return + } + if err != nil { + a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + return + } + out := make([]messageJSON, 0, len(items)) + for _, m := range items { + out = append(out, asMessage(m)) + } + var next *string + if hasMore && len(items) > 0 { + last := items[len(items)-1] + encoded := encodeCursor(cursorPayload{Scope: "msg:" + id, ID: last.ID, At: formatTime(last.CreatedAt)}) + next = &encoded + } + writeJSON(w, http.StatusOK, messagePage{Items: out, NextCursor: next}) +} + +func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string, bool) { + id, ok := canonicalUUID(raw) + if !ok { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0) + return "", false + } + return id, true +} + +func splitChatPath(path string) (id string, messages bool, ok bool) { + const prefix = "/api/v1/chats/" + if !strings.HasPrefix(path, prefix) { + return "", false, false + } + rest := strings.TrimPrefix(path, prefix) + if rest == "" || strings.Contains(rest, "/") && !strings.HasSuffix(rest, "/messages") { + return "", false, false + } + if strings.HasSuffix(rest, "/messages") { + id = strings.TrimSuffix(rest, "/messages") + if id == "" || strings.Contains(id, "/") { + return "", false, false + } + return id, true, true + } + return rest, false, true +} diff --git a/internal/api/http.go b/internal/api/http.go new file mode 100644 index 00000000..672533fe --- /dev/null +++ b/internal/api/http.go @@ -0,0 +1,321 @@ +package api + +import ( + "bytes" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "messenger/internal/store" +) + +var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) +var uuidRe = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) +var limitRe = regexp.MustCompile(`^[0-9]{1,3}$`) +var requestIDRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`) + +type errorEnvelope struct { + Error errorObject `json:"error"` +} + +type errorObject struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +type userJSON struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} + +type chatJSON struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} + +type messageJSON 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 chatPage struct { + Items []chatJSON `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type messagePage struct { + Items []messageJSON `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type cursorPayload struct { + Scope string `json:"scope"` + ID string `json:"id"` + At string `json:"at"` +} + +type statusWriter struct { + http.ResponseWriter + status int + wrote bool +} + +func (s *statusWriter) WriteHeader(code int) { + if s.wrote { + return + } + s.status = code + s.wrote = true + s.ResponseWriter.WriteHeader(code) +} + +func (s *statusWriter) Write(b []byte) (int, error) { + if !s.wrote { + s.WriteHeader(http.StatusOK) + } + return s.ResponseWriter.Write(b) +} + +func (a *API) fail(w http.ResponseWriter, r *http.Request, status int, code, message string, retryAfter int) { + if retryAfter > 0 { + w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) + } + writeJSON(w, status, errorEnvelope{Error: errorObject{ + Code: code, + Message: message, + RequestID: requestIDFrom(r), + }}) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + enc := json.NewEncoder(w) + enc.SetEscapeHTML(false) + _ = enc.Encode(v) +} + +func (a *API) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool { + media := "" + if ct := r.Header.Get("Content-Type"); ct != "" { + media = strings.TrimSpace(strings.Split(ct, ";")[0]) + } + if !strings.EqualFold(media, "application/json") { + a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен Content-Type application/json", 0) + return false + } + body, err := io.ReadAll(r.Body) + if err != nil || !utf8.Valid(body) || !decodeExactJSON(body, dst) { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный JSON", 0) + return false + } + return true +} + +// decodeExactJSON принимает один JSON-объект: точные имена полей, без хвоста и без замены битого UTF-8. +func decodeExactJSON(body []byte, dst any) bool { + dec := json.NewDecoder(bytes.NewReader(body)) + var fields map[string]json.RawMessage + if err := dec.Decode(&fields); err != nil || fields == nil { + return false + } + var trailing json.RawMessage + if err := dec.Decode(&trailing); err != io.EOF { + return false + } + allowed, ok := jsonFieldNames(dst) + if !ok { + return false + } + for name := range fields { + if _, ok := allowed[name]; !ok { + return false + } + } + return json.Unmarshal(body, dst) == nil +} + +func jsonFieldNames(dst any) (map[string]struct{}, bool) { + t := reflect.TypeOf(dst) + if t == nil || t.Kind() != reflect.Pointer { + return nil, false + } + t = t.Elem() + if t.Kind() != reflect.Struct { + return nil, false + } + names := make(map[string]struct{}, t.NumField()) + for i := 0; i < t.NumField(); i++ { + name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",") + if name == "" || name == "-" { + return nil, false + } + names[name] = struct{}{} + } + return names, true +} + +func (a *API) authenticate(w http.ResponseWriter, r *http.Request) (store.User, bool) { + raw := strings.TrimSpace(r.Header.Get("X-User-Id")) + id, ok := canonicalUUID(raw) + if !ok { + a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0) + return store.User{}, false + } + user, exists := a.store.User(id) + if !exists { + a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0) + return store.User{}, false + } + return user, true +} + +func (a *API) pageQuery(w http.ResponseWriter, r *http.Request, scope string) (int, *store.Cursor, bool) { + q := r.URL.Query() + limit := 50 + if q.Has("limit") { + raw := q.Get("limit") + n, err := strconv.Atoi(raw) + if err != nil || !limitRe.MatchString(raw) || n < 1 || n > 100 { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный limit", 0) + return 0, nil, false + } + limit = n + } + if !q.Has("cursor") { + return limit, nil, true + } + raw := q.Get("cursor") + if raw == "" || len(raw) > 512 { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0) + return 0, nil, false + } + payload, err := decodeCursor(raw) + if err != nil || payload.Scope != scope || payload.ID == "" || payload.At == "" { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0) + return 0, nil, false + } + at, err := time.Parse("2006-01-02T15:04:05.000000Z", payload.At) + if err != nil { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0) + return 0, nil, false + } + id, ok := canonicalUUID(payload.ID) + if !ok { + a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0) + return 0, nil, false + } + return limit, &store.Cursor{ID: id, At: at}, true +} + +func asUser(u store.User) userJSON { + return userJSON{ + ID: u.ID, + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: formatTime(u.CreatedAt), + } +} + +func asChat(c store.Chat) chatJSON { + ids := c.MemberIDs + if ids == nil { + ids = []string{} + } + return chatJSON{ + ID: c.ID, + Title: c.Title, + MemberIDs: ids, + CreatedAt: formatTime(c.CreatedAt), + } +} + +func asMessage(m store.Message) messageJSON { + return messageJSON{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.SenderID, + Text: m.Text, + CreatedAt: formatTime(m.CreatedAt), + } +} + +func formatTime(t time.Time) string { + return t.UTC().Format("2006-01-02T15:04:05.000000Z") +} + +func canonicalUUID(s string) (string, bool) { + if !uuidRe.MatchString(s) { + return "", false + } + return strings.ToLower(s), true +} + +func validText(s string, min, max int) bool { + if strings.TrimSpace(s) == "" { + return false + } + n := utf8.RuneCountInString(s) + return n >= min && n <= max +} + +func requestID(r *http.Request) string { + incoming := strings.TrimSpace(r.Header.Get("X-Request-Id")) + if requestIDRe.MatchString(incoming) { + return incoming + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return strconv.FormatInt(time.Now().UnixNano(), 36) + } + return hex.EncodeToString(b[:]) +} + +func encodeCursor(p cursorPayload) string { + raw, err := json.Marshal(p) + if err != nil { + return "" + } + return base64.RawURLEncoding.EncodeToString(raw) +} + +func decodeCursor(s string) (cursorPayload, error) { + b, err := base64.RawURLEncoding.DecodeString(s) + if err != nil { + b, err = base64.URLEncoding.DecodeString(s) + if err != nil { + return cursorPayload{}, err + } + } + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + var p cursorPayload + if err := dec.Decode(&p); err != nil { + return cursorPayload{}, err + } + var trailing json.RawMessage + if err := dec.Decode(&trailing); err != io.EOF { + if err == nil { + err = io.ErrUnexpectedEOF + } + return cursorPayload{}, err + } + return p, nil +} diff --git a/internal/api/server.go b/internal/api/server.go new file mode 100644 index 00000000..d6b58c37 --- /dev/null +++ b/internal/api/server.go @@ -0,0 +1,86 @@ +package api + +import ( + "context" + "log/slog" + "net/http" + "sync/atomic" + "time" + + "messenger/internal/store" +) + +type ctxKey struct{} + +type API struct { + store *store.Store + log *slog.Logger + shutting atomic.Bool +} + +// Создает Api +func New(st *store.Store, log *slog.Logger) *API { + if log == nil { + log = slog.Default() + } + return &API{ + store: st, + log: log, + } +} + +// BeginShutdown переводит /health/ready в 503 и говорит новым бизнес-запросам +// отказать до закрытия слушателя. Уже принятые обработчики дорабатывают. +func (a *API) BeginShutdown() { + a.shutting.Store(true) + a.log.Info("shutdown started") +} + +// Точка входа +func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) { + sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} + start := time.Now() + id := requestID(r) + sw.Header().Set("X-Request-Id", id) + r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id)) + + defer func() { + if p := recover(); p != nil { + a.log.Error("panic", "request_id", id) + if !sw.wrote { + a.fail(sw, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0) + } + } + a.log.Info("request", + "request_id", id, + "method", r.Method, + "path", r.URL.Path, + "status", sw.status, + "duration_ms", time.Since(start).Milliseconds(), + "bytes_in", r.ContentLength, + ) + }() + + switch { + case r.Method == http.MethodGet && r.URL.Path == "/health/live": + a.live(sw, r) + return + case r.Method == http.MethodGet && r.URL.Path == "/health/ready": + a.ready(sw, r) + return + } + + if a.shutting.Load() { + a.fail(sw, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1) + return + } + a.route(sw, r) +} + +func requestIDFrom(r *http.Request) string { + id, _ := r.Context().Value(ctxKey{}).(string) + if id == "" { + return "unknown" + } + return id +} diff --git a/internal/api/server_test.go b/internal/api/server_test.go new file mode 100644 index 00000000..0202cb6c --- /dev/null +++ b/internal/api/server_test.go @@ -0,0 +1,409 @@ +package api + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + + "messenger/internal/store" +) + +func newServer(t *testing.T) (*httptest.Server, *API, *bytes.Buffer) { + t.Helper() + var logs bytes.Buffer + st := store.New() + application := New(st, slog.New(slog.NewJSONHandler(&logs, nil))) + srv := httptest.NewServer(application) + t.Cleanup(srv.Close) + return srv, application, &logs +} + +func do(t *testing.T, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) { + t.Helper() + var rdr io.Reader + if raw != nil { + rdr = bytes.NewReader(raw) + } else if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rdr = bytes.NewReader(b) + } + req, err := http.NewRequest(method, url, rdr) + if err != nil { + t.Fatal(err) + } + if body != nil || raw != nil { + if contentType == "" { + contentType = "application/json" + } + req.Header.Set("Content-Type", contentType) + } + if user != "" { + req.Header.Set("X-User-Id", user) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + if resp.Header.Get("X-Request-Id") == "" { + t.Fatalf("%s %s: missing X-Request-Id", method, url) + } + if resp.StatusCode >= 400 { + var env errorEnvelope + if err := json.Unmarshal(data, &env); err != nil { + t.Fatalf("error json: %v body %s", err, data) + } + if env.Error.RequestID != resp.Header.Get("X-Request-Id") || env.Error.Code == "" || env.Error.Message == "" { + t.Fatalf("bad error envelope: %+v", env) + } + } + return resp.StatusCode, resp.Header, data +} + +func createUser(t *testing.T, base, username, display string) userJSON { + t.Helper() + status, _, body := do(t, http.MethodPost, base+"/api/v1/users", "", map[string]string{ + "username": username, "display_name": display, + }, nil, "") + if status != http.StatusCreated { + t.Fatalf("create user %s: %d %s", username, status, body) + } + var u userJSON + if err := json.Unmarshal(body, &u); err != nil { + t.Fatal(err) + } + return u +} + +func createChat(t *testing.T, base, caller, title string, members ...string) chatJSON { + t.Helper() + status, _, body := do(t, http.MethodPost, base+"/api/v1/chats", caller, map[string]any{ + "title": title, "member_ids": members, + }, nil, "") + if status != http.StatusCreated { + t.Fatalf("create chat: %d %s", status, body) + } + var c chatJSON + if err := json.Unmarshal(body, &c); err != nil { + t.Fatal(err) + } + return c +} + +func TestInvalidJSONExtraFieldAndTypes(t *testing.T) { + srv, _, _ := newServer(t) + cases := [][]byte{ + []byte(`{`), + []byte(`{"username":"abc","display_name":"Алиса","extra":1}`), + []byte(`{"username":1,"display_name":"Алиса"}`), + []byte(`null`), + } + for _, raw := range cases { + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json") + if status != http.StatusBadRequest || !bytes.Contains(body, []byte(`"invalid_request"`)) { + t.Fatalf("body %s: %d %s", raw, status, body) + } + } + status, _, _ := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, []byte(`{"username":"abc","display_name":"Алиса"}`), "text/plain") + if status != http.StatusUnsupportedMediaType { + t.Fatalf("content type: %d", status) + } +} + +func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) { + srv, _, _ := newServer(t) + bad := [][]byte{ + []byte(`{"username":"bad_json","display_name":"Я"}]`), + []byte(`{"username":"bad_json","display_name":"Я"}}`), + []byte(`{"Username":"bad_case","display_name":"Я"}`), + append([]byte(`{"username":"bad_utf","display_name":"`), 0xff, '"', '}'), + } + for _, raw := range bad { + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json") + if status != http.StatusBadRequest { + t.Fatalf("user body %q: %d %s", raw, status, body) + } + } + + alice := createUser(t, srv.URL, "alice", "Алиса") + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats", alice.ID, nil, []byte(`{"Title":"чат","member_ids":["`+alice.ID+`"]}`), "application/json") + if status != http.StatusBadRequest { + t.Fatalf("Title: %d %s", status, body) + } + chat := createChat(t, srv.URL, alice.ID, "чат", alice.ID) + + status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, []byte(`{"TEXT":"hi"}`), "application/json") + if status != http.StatusBadRequest { + t.Fatalf("TEXT: %d %s", status, body) + } + rawText := append([]byte(`{"text":"`), 0xff, '"', '}') + status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, rawText, "application/json") + if status != http.StatusBadRequest { + t.Fatalf("message utf-8: %d %s", status, body) + } + + status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "one"}, nil, "") + if status != http.StatusCreated { + t.Fatalf("seed: %d %s", status, body) + } + status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "two"}, nil, "") + if status != http.StatusCreated { + t.Fatalf("seed2: %d %s", status, body) + } + status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil, "") + if status != http.StatusOK { + t.Fatalf("page: %d %s", status, body) + } + var page messagePage + if err := json.Unmarshal(body, &page); err != nil || page.NextCursor == nil { + t.Fatalf("cursor: %v %s", err, body) + } + decoded, err := base64.RawURLEncoding.DecodeString(*page.NextCursor) + if err != nil { + t.Fatal(err) + } + tampered := base64.RawURLEncoding.EncodeToString(append(decoded, []byte("garbage")...)) + status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(tampered), alice.ID, nil, nil, "") + if status != http.StatusBadRequest { + t.Fatalf("tampered cursor: %d %s", status, body) + } + status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(*page.NextCursor), alice.ID, nil, nil, "") + if status != http.StatusOK { + t.Fatalf("valid cursor: %d", status) + } +} + +func TestDuplicateUsername(t *testing.T) { + srv, _, _ := newServer(t) + createUser(t, srv.URL, "alice", "Алиса") + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", map[string]string{ + "username": "alice", "display_name": "Другая", + }, nil, "") + if status != http.StatusConflict || !bytes.Contains(body, []byte(`"conflict"`)) { + t.Fatalf("duplicate: %d %s", status, body) + } +} + +func TestEmptyMessageForeignChatAndAuth(t *testing.T) { + srv, _, _ := newServer(t) + alice := createUser(t, srv.URL, "alice", "Алиса") + bob := createUser(t, srv.URL, "bob", "Боб") + eve := createUser(t, srv.URL, "eve", "Ева") + chat := createChat(t, srv.URL, alice.ID, "Контрактный тест", alice.ID, bob.ID) + + status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "", nil, nil, "") + if status != http.StatusUnauthorized { + t.Fatalf("missing header: %d", status) + } + status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "11111111-1111-4111-8111-111111111111", nil, nil, "") + if status != http.StatusUnauthorized { + t.Fatalf("unknown user: %d", status) + } + meStatus, _, meBody := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", alice.ID, nil, nil, "") + if meStatus != http.StatusOK || !bytes.Contains(meBody, []byte(alice.ID)) { + t.Fatalf("me: %d %s", meStatus, meBody) + } + + status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID, eve.ID, nil, nil, "") + if status != http.StatusNotFound { + t.Fatalf("foreign chat: %d", status) + } + status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", eve.ID, map[string]string{"text": "чужое"}, nil, "") + if status != http.StatusNotFound { + t.Fatalf("foreign post: %d", status) + } + for _, text := range []string{"", " ", "\n\t"} { + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "") + if status != http.StatusBadRequest { + t.Fatalf("empty %q: %d %s", text, status, body) + } + } + status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "привет", "sender_id": eve.ID}, nil, "") + if status != http.StatusBadRequest { + t.Fatalf("sender_id must be rejected: %d", status) + } + + text := "Привет, мир 👋" + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "") + if status != http.StatusCreated { + t.Fatalf("unicode: %d %s", status, body) + } + var msg messageJSON + if err := json.Unmarshal(body, &msg); err != nil { + t.Fatal(err) + } + if msg.Text != text || msg.SenderID != alice.ID || msg.ChatID != chat.ID { + t.Fatalf("message mutated: %+v", msg) + } + if !strings.HasSuffix(msg.CreatedAt, "Z") { + t.Fatalf("timestamp: %s", msg.CreatedAt) + } +} + +func TestPaginationSeveralPages(t *testing.T) { + srv, _, _ := newServer(t) + alice := createUser(t, srv.URL, "alice", "Алиса") + bob := createUser(t, srv.URL, "bob", "Боб") + chat := createChat(t, srv.URL, alice.ID, "страницы", alice.ID, bob.ID) + other := createChat(t, srv.URL, alice.ID, "другой", alice.ID) + const n = 25 + ids := make([]string, 0, n) + for i := 0; i < n; i++ { + sender := alice.ID + if i%2 == 1 { + sender = bob.ID + } + status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", sender, map[string]string{ + "text": "сообщение " + strings.Repeat("я", i%3) + string(rune('a'+i%26)), + }, nil, "") + if status != http.StatusCreated { + t.Fatalf("post %d: %d %s", i, status, body) + } + var msg messageJSON + if err := json.Unmarshal(body, &msg); err != nil { + t.Fatal(err) + } + ids = append(ids, msg.ID) + } + var got []string + cursor := "" + pages := 0 + for { + pages++ + if pages > 10 { + t.Fatal("pagination did not finish") + } + url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10" + if cursor != "" { + url += "&cursor=" + cursor + } + status, _, body := do(t, http.MethodGet, url, bob.ID, nil, nil, "") + if status != http.StatusOK { + t.Fatalf("page: %d %s", status, body) + } + var page messagePage + if err := json.Unmarshal(body, &page); err != nil { + t.Fatal(err) + } + if len(page.Items) == 0 || len(page.Items) > 10 { + t.Fatalf("page size %d", len(page.Items)) + } + for _, item := range page.Items { + got = append(got, item.ID) + } + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + if pages < 3 { + t.Fatalf("expected several pages, got %d", pages) + } + if strings.Join(got, ",") != strings.Join(ids, ",") { + t.Fatalf("order/duplication mismatch\nwant %v\ngot %v", ids, got) + } + status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+other.ID+"/messages?limit=10&cursor="+cursor, alice.ID, nil, nil, "") + if status != http.StatusBadRequest { + t.Fatalf("foreign cursor: %d", status) + } + status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=0", alice.ID, nil, nil, "") + if status != http.StatusBadRequest { + t.Fatalf("limit 0: %d", status) + } +} + +func TestConcurrentHundredMessages(t *testing.T) { + srv, _, _ := newServer(t) + users := make([]userJSON, 10) + ids := make([]string, 10) + for i := 0; i < 10; i++ { + users[i] = createUser(t, srv.URL, "u"+string(rune('a'+i))+"x", "Участник") + ids[i] = users[i].ID + } + chat := createChat(t, srv.URL, ids[0], "гонка", ids...) + var wg sync.WaitGroup + errCh := make(chan error, 100) + for i := 0; i < 10; i++ { + wg.Add(1) + go func(user string) { + defer wg.Done() + for j := 0; j < 10; j++ { + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(`{"text":"n"}`)) + if err != nil { + errCh <- err + return + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", user) + resp, err := http.DefaultClient.Do(req) + if err != nil { + errCh <- err + return + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != http.StatusCreated { + errCh <- &statusErr{resp.StatusCode, body} + } + } + }(ids[i]) + } + wg.Wait() + close(errCh) + for err := range errCh { + t.Fatal(err) + } + seen := map[string]struct{}{} + cursor := "" + for { + url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17" + if cursor != "" { + url += "&cursor=" + cursor + } + status, _, body := do(t, http.MethodGet, url, ids[3], nil, nil, "") + if status != http.StatusOK { + t.Fatalf("list: %d %s", status, body) + } + var page messagePage + if err := json.Unmarshal(body, &page); err != nil { + t.Fatal(err) + } + for _, item := range page.Items { + if _, ok := seen[item.ID]; ok { + t.Fatalf("duplicate %s", item.ID) + } + seen[item.ID] = struct{}{} + } + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + if len(seen) != 100 { + t.Fatalf("unique messages = %d, want 100", len(seen)) + } +} + +type statusErr struct { + code int + body []byte +} + +func (e *statusErr) Error() string { + return http.StatusText(e.code) + " " + string(e.body) +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 00000000..0c3095c0 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,67 @@ +package config + +import ( + "fmt" + "net" + "os" + "strconv" + "time" +) + +// Config - параметры процесса. +type Config struct { + Host string + Port string + Env string + ShutdownTimeout time.Duration +} + +// Addr — адрес прослушивания. В контейнере это 0.0.0.0:8080, +// иначе published port Docker не попадёт в процесс. +func (c Config) Addr() string { + return net.JoinHostPort(c.Host, c.Port) +} + +// Load завершает запуск ошибкой, если значение вне допустимого диапазона. +func Load() (Config, error) { + var c Config + c.Host = getenv("APP_HOST", "0.0.0.0") + c.Port = getenv("APP_PORT", "8080") + c.Env = getenv("APP_ENV", "lab") + if c.Host == "" { + return Config{}, fmt.Errorf("APP_HOST is empty") + } + port, err := strconv.Atoi(c.Port) + if err != nil || port < 1 || port > 65535 { + return Config{}, fmt.Errorf("APP_PORT must be 1..65535") + } + + sec, err := nonNeg("SHUTDOWN_TIMEOUT_SECONDS", 8) + if err != nil { + return Config{}, err + } + if sec < 1 || sec > 10 { + return Config{}, fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..10") + } + c.ShutdownTimeout = time.Duration(sec) * time.Second + return c, nil +} + +func getenv(key, def string) string { + if v, ok := os.LookupEnv(key); ok && v != "" { + return v + } + return def +} + +func nonNeg(key string, def int) (int, error) { + v, ok := os.LookupEnv(key) + if !ok || v == "" { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + return 0, fmt.Errorf("%s must be a non-negative integer", key) + } + return n, nil +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 00000000..fe119dda --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,267 @@ +package store + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "sync" + "time" +) + +var ( + ErrConflict = errors.New("conflict") + ErrNotFound = errors.New("not found") + ErrInvalid = errors.New("invalid") + ErrBadCursor = errors.New("bad cursor") +) + +// User - публичная карточка. +type User struct { + ID string + Username string + DisplayName string + CreatedAt time.Time +} + +// Chat - неизменяемый состав участников. +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} + +// Message - подтверждённое сообщение. Текст после записи не меняется. +type Message struct { + ID string + ChatID string + SenderID string + Text string + CreatedAt time.Time +} + +// Cursor - позиция keyset (created_at, id), уже проверенная вызывающим слоем +// на принадлежность ресурсу. Пустые поля означают первую страницу. +type Cursor struct { + ID string + At time.Time +} + +type chatRec struct { + chat Chat + members map[string]struct{} +} + +// Store сериализует записи мьютексом. Чтения берут RLock и копируют срез, +// поэтому параллельные запросы не делят изменяемый буфер. +type Store struct { + mu sync.RWMutex + users map[string]User + byName map[string]string + chats map[string]*chatRec + chatOrder []string + messages map[string][]Message + msgIndex map[string]map[string]int + last time.Time +} + +func New() *Store { + return &Store{ + users: make(map[string]User), + byName: make(map[string]string), + chats: make(map[string]*chatRec), + messages: make(map[string][]Message), + msgIndex: make(map[string]map[string]int), + } +} + +func (s *Store) CreateUser(username, displayName string) (User, error) { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.byName[username]; ok { + return User{}, ErrConflict + } + u := User{ + ID: newID(), + Username: username, + DisplayName: displayName, + CreatedAt: s.nextTimeLocked(), + } + s.users[u.ID] = u + s.byName[username] = u.ID + return u, nil +} + +func (s *Store) User(id string) (User, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + u, ok := s.users[id] + return u, ok +} + +func (s *Store) CreateChat(title string, memberIDs []string, caller string) (Chat, error) { + s.mu.Lock() + defer s.mu.Unlock() + seen := make(map[string]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return Chat{}, ErrInvalid + } + seen[id] = struct{}{} + if _, ok := s.users[id]; !ok { + return Chat{}, ErrInvalid + } + } + if _, ok := seen[caller]; !ok { + return Chat{}, ErrInvalid + } + c := Chat{ + ID: newID(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), + CreatedAt: s.nextTimeLocked(), + } + s.chats[c.ID] = &chatRec{chat: c, members: seen} + s.chatOrder = append(s.chatOrder, c.ID) + s.messages[c.ID] = nil + s.msgIndex[c.ID] = make(map[string]int) + return c, nil +} + +func (s *Store) ChatFor(chatID, userID string) (Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + rec, ok := s.chats[chatID] + if !ok { + return Chat{}, ErrNotFound + } + if _, member := rec.members[userID]; !member { + return Chat{}, ErrNotFound + } + return rec.chat.clone(), nil +} + +func (s *Store) ListChats(userID string, cur *Cursor, limit int) ([]Chat, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + filtered := make([]Chat, 0) + for _, id := range s.chatOrder { + rec := s.chats[id] + if _, ok := rec.members[userID]; ok { + filtered = append(filtered, rec.chat.clone()) + } + } + start, err := indexAfter(filtered, cur, func(c Chat) (string, time.Time) { + return c.ID, c.CreatedAt + }) + if err != nil { + return nil, false, err + } + end := start + limit + if end > len(filtered) { + end = len(filtered) + } + return append([]Chat(nil), filtered[start:end]...), end < len(filtered), nil +} + +func (s *Store) AddMessage(chatID, senderID, text string) (Message, error) { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.chats[chatID] + if !ok { + return Message{}, ErrNotFound + } + if _, member := rec.members[senderID]; !member { + return Message{}, ErrNotFound + } + m := Message{ + ID: newID(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: s.nextTimeLocked(), + } + idx := len(s.messages[chatID]) + s.messages[chatID] = append(s.messages[chatID], m) + s.msgIndex[chatID][m.ID] = idx + return m, nil +} + +func (s *Store) ListMessages(chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) { + s.mu.RLock() + defer s.mu.RUnlock() + rec, ok := s.chats[chatID] + if !ok { + return nil, false, ErrNotFound + } + if _, member := rec.members[userID]; !member { + return nil, false, ErrNotFound + } + all := s.messages[chatID] + start := 0 + if cur != nil { + idx, ok := s.msgIndex[chatID][cur.ID] + if !ok || !all[idx].CreatedAt.Equal(cur.At) { + return nil, false, ErrBadCursor + } + start = idx + 1 + } + end := start + limit + if end > len(all) { + end = len(all) + } + // Копия значений: вызывающий не удерживает внутренний срез. + out := append([]Message(nil), all[start:end]...) + return out, end < len(all), nil +} + +// nextTimeLocked выдаёт неубывающее время фиксации. +func (s *Store) nextTimeLocked() time.Time { + now := time.Now().UTC().Truncate(time.Microsecond) + if !now.After(s.last) { + now = s.last.Add(time.Microsecond) + } + s.last = now + return now +} + +func indexAfter[T any](items []T, cur *Cursor, key func(T) (string, time.Time)) (int, error) { + if cur == nil { + return 0, nil + } + for i, item := range items { + id, at := key(item) + if id == cur.ID { + if !at.Equal(cur.At) { + return 0, ErrBadCursor + } + return i + 1, nil + } + } + return 0, ErrBadCursor +} + +func (c Chat) clone() Chat { + c.MemberIDs = append([]string(nil), c.MemberIDs...) + return c +} + +func newID() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + panic("crypto/rand: " + err.Error()) + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + var buf [36]byte + hex.Encode(buf[0:8], b[0:4]) + buf[8] = '-' + hex.Encode(buf[9:13], b[4:6]) + buf[13] = '-' + hex.Encode(buf[14:18], b[6:8]) + buf[18] = '-' + hex.Encode(buf[19:23], b[8:10]) + buf[23] = '-' + hex.Encode(buf[24:36], b[10:16]) + return string(buf[:]) +} diff --git a/messenger/main.go b/messenger/main.go new file mode 100644 index 00000000..973629b6 --- /dev/null +++ b/messenger/main.go @@ -0,0 +1,106 @@ +package main + +import ( + "context" + "errors" + "io" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "syscall" + "time" + + "messenger/internal/api" + "messenger/internal/config" + "messenger/internal/store" +) + +func main() { + if len(os.Args) > 1 && os.Args[1] == "healthcheck" { + os.Exit(runHealthcheck()) + } + + // Инициализация + cfg, err := config.Load() + if err != nil { + slog.Error("config", "err", err.Error()) + os.Exit(2) + } + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + st := store.New() + application := api.New(st, log) + // http сервер + srv := &http.Server{ + Addr: cfg.Addr(), + Handler: application, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + MaxHeaderBytes: 1 << 20, + } + + // Запуск сервера + errCh := make(chan error, 1) + go func() { + log.Info("listening", + "addr", cfg.Addr(), + "env", cfg.Env, + "shutdown_timeout_seconds", int(cfg.ShutdownTimeout/time.Second), + ) + err := srv.ListenAndServe() + if err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- err + } + close(errCh) + }() + + // Ожидание сигнала или ошибки + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT) + select { + case err := <-errCh: + log.Error("server", "err", err.Error()) + os.Exit(1) + case <-sig: + } + + // Плавное завершение + application.BeginShutdown() + ctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) + defer cancel() + if err := srv.Shutdown(ctx); err != nil { + log.Error("shutdown timeout, closing listener", "err", err.Error()) + _ = srv.Close() + } + log.Info("shutdown complete") +} + +func runHealthcheck() int { + port := os.Getenv("APP_PORT") + if port == "" { + port = "8080" + } + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 { + return 1 + } + client := http.Client{Timeout: 2 * time.Second} + req, err := http.NewRequest(http.MethodGet, "http://"+net.JoinHostPort("127.0.0.1", port)+"/health/ready", nil) + if err != nil { + return 1 + } + resp, err := client.Do(req) + if err != nil { + return 1 + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + if resp.StatusCode != http.StatusOK { + return 1 + } + return 0 +}