Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+70
View File
@@ -0,0 +1,70 @@
package httpx
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strings"
"unicode/utf8"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
// DecodeJSON reads exactly one JSON object into dst and enforces what gin's
// binding does not: the media type must be application/json (415), invalid
// UTF-8, unknown fields, wrong types, malformed syntax and trailing data are
// 400, an oversized body is 413, and messages never expose Go type names.
func DecodeJSON(c *gin.Context, dst any) error {
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || mediaType != "application/json" {
return apperr.UnsupportedMedia("Content-Type must be application/json")
}
// The body is already capped by the bodyLimit middleware, so reading it
// whole is bounded.
body, err := io.ReadAll(c.Request.Body)
if err != nil {
return decodeError(err)
}
// encoding/json silently replaces invalid UTF-8 with U+FFFD; the contract
// and RFC 8259 require UTF-8, so such a body is rejected, not repaired.
if !utf8.Valid(body) {
return apperr.Invalid("request body must be valid UTF-8")
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return decodeError(err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return apperr.Invalid("unexpected data after JSON body")
}
return nil
}
func decodeError(err error) error {
if tooLarge, ok := errors.AsType[*http.MaxBytesError](err); ok {
return apperr.Wrap(apperr.KindPayloadTooLarge, fmt.Sprintf("request body must be at most %d bytes", tooLarge.Limit), err)
}
if errors.Is(err, io.EOF) {
return apperr.Wrap(apperr.KindInvalid, "request body is required", err)
}
if wrongType, ok := errors.AsType[*json.UnmarshalTypeError](err); ok {
if wrongType.Field == "" {
return apperr.Wrap(apperr.KindInvalid, "request body must be a JSON object", err)
}
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("field %q has wrong type", wrongType.Field), err)
}
// encoding/json reports unknown fields as a plain error without a type.
const unknownPrefix = "json: unknown field "
if msg := err.Error(); strings.HasPrefix(msg, unknownPrefix) {
field := strings.Trim(strings.TrimPrefix(msg, unknownPrefix), `"`)
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("unknown field %q", field), err)
}
return apperr.Wrap(apperr.KindInvalid, "malformed JSON body", err)
}
+50
View File
@@ -0,0 +1,50 @@
// Package httpx is the transport layer over gin: request ids, access
// logging, panic recovery, body limits, strict JSON decoding and the single
// error format of the API contract. gin is used for routing and the
// middleware chain; everything here exists because the contract demands a
// specific behaviour that gin's own helpers do not provide.
package httpx
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
const (
keyRequestID = "messenger.request_id"
keyLogger = "messenger.logger"
)
// NewEngine builds an engine whose every response, including routing
// failures and panics, carries X-Instance-Id, X-Request-Id and the contract
// error body.
func NewEngine(log *slog.Logger, maxBodyBytes int64, instanceID string) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
e := gin.New()
// Redirects would answer with text/plain and without a request id.
e.RedirectTrailingSlash = false
e.RedirectFixedPath = false
e.HandleMethodNotAllowed = true
e.Use(instance(instanceID), requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
e.NoRoute(func(c *gin.Context) { Error(c, apperr.NotFound("route not found")) })
e.NoMethod(func(c *gin.Context) { Fail(c, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") })
return e
}
func RequestID(c *gin.Context) string {
return c.GetString(keyRequestID)
}
func logger(c *gin.Context) *slog.Logger {
if l, ok := c.Get(keyLogger); ok {
if log, ok := l.(*slog.Logger); ok {
return log
}
}
return slog.Default()
}
+409
View File
@@ -0,0 +1,409 @@
package httpx_test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
)
type errorBody struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
type payload struct {
Text string `json:"text"`
Count int `json:"count"`
}
const testInstance = "0123456789abcdef"
func newEngine(t *testing.T, logs *bytes.Buffer) *gin.Engine {
t.Helper()
return newEngineAt(t, logs, slog.LevelDebug)
}
func newEngineAt(t *testing.T, logs *bytes.Buffer, level slog.Level) *gin.Engine {
t.Helper()
if logs == nil {
logs = &bytes.Buffer{}
}
log := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: level}))
e := httpx.NewEngine(log, 64, testInstance)
e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": "<a&b>"}) })
e.GET("/panic", func(c *gin.Context) { panic("secret detail") })
e.GET("/fail", func(c *gin.Context) { httpx.Error(c, errors.New("db password leaked")) })
e.GET("/notfound", func(c *gin.Context) { httpx.Error(c, apperr.NotFound("chat not found")) })
e.GET("/who", func(c *gin.Context) {
httpx.SetUserID(c, uuid.MustParse("11111111-1111-4111-8111-111111111111"))
id, ok := httpx.UserID(c)
httpx.JSON(c, http.StatusOK, gin.H{"id": id.String(), "ok": ok})
})
e.POST("/decode", func(c *gin.Context) {
var p payload
if err := httpx.DecodeJSON(c, &p); err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, p)
})
return e
}
func do(t *testing.T, e *gin.Engine, method, path string, body string, headers map[string]string) (*httptest.ResponseRecorder, errorBody) {
t.Helper()
var reader io.Reader
if body != "" {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, reader)
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
var eb errorBody
if rec.Code >= 400 {
if err := json.Unmarshal(rec.Body.Bytes(), &eb); err != nil {
t.Fatalf("%s %s: error body is not JSON: %v: %s", method, path, err, rec.Body.String())
}
}
return rec, eb
}
func assertError(t *testing.T, rec *httptest.ResponseRecorder, eb errorBody, status int, code string) {
t.Helper()
if rec.Code != status {
t.Fatalf("status = %d, want %d (body %s)", rec.Code, status, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Fatalf("Content-Type = %q", ct)
}
rid := rec.Header().Get("X-Request-Id")
if rid == "" {
t.Fatal("missing X-Request-Id header")
}
if eb.Error.RequestID != rid {
t.Fatalf("body request_id %q != header %q", eb.Error.RequestID, rid)
}
if eb.Error.Code != code || eb.Error.Message == "" {
t.Fatalf("error = %+v, want code %q with a message", eb.Error, code)
}
}
// The balancer spreads one client's requests over the replicas; the header
// is how a client tells which process answered, so no response may lack it.
func TestEveryResponseCarriesInstanceID(t *testing.T) {
e := newEngine(t, nil)
for _, r := range []struct{ method, path string }{
{http.MethodGet, "/ok"},
{http.MethodGet, "/missing"},
{http.MethodDelete, "/ok"},
{http.MethodGet, "/panic"},
{http.MethodGet, "/fail"},
{http.MethodPost, "/decode"},
} {
rec, _ := do(t, e, r.method, r.path, "", nil)
if got := rec.Header().Get("X-Instance-Id"); got != testInstance {
t.Errorf("%s %s (status %d): X-Instance-Id = %q, want %q", r.method, r.path, rec.Code, got, testInstance)
}
}
}
func TestUnknownRouteIsJSON404(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/nope", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
}
func TestTrailingSlashIsNotRedirected(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/ok/", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
}
func TestWrongMethodIsJSON405WithAllow(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodDelete, "/ok", "", nil)
assertError(t, rec, eb, http.StatusMethodNotAllowed, "invalid_request")
if !strings.Contains(rec.Header().Get("Allow"), "GET") {
t.Fatalf("Allow = %q, want GET", rec.Header().Get("Allow"))
}
}
func TestPanicBecomesJSON500WithoutDetails(t *testing.T) {
logs := &bytes.Buffer{}
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/panic", "", nil)
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
if strings.Contains(rec.Body.String(), "secret detail") {
t.Fatal("panic value leaked to the client")
}
if !strings.Contains(logs.String(), "secret detail") {
t.Fatal("panic must be logged for operators")
}
}
func TestForeignErrorBecomesJSON500WithoutDetails(t *testing.T) {
logs := &bytes.Buffer{}
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/fail", "", nil)
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
if strings.Contains(rec.Body.String(), "password") {
t.Fatal("internal error text leaked to the client")
}
if !strings.Contains(logs.String(), "db password leaked") {
t.Fatal("cause must be logged for operators")
}
}
func TestApplicationErrorMapping(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/notfound", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
if eb.Error.Message != "chat not found" {
t.Fatalf("message = %q", eb.Error.Message)
}
}
func TestSuccessResponseHeadersAndEscaping(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", nil)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Fatalf("Content-Type = %q", ct)
}
if rec.Header().Get("X-Request-Id") == "" {
t.Fatal("missing X-Request-Id on success")
}
if !strings.Contains(rec.Body.String(), `"<a&b>"`) {
t.Fatalf("HTML escaping must be off, body %s", rec.Body.String())
}
}
// The balancer sets X-Request-Id on every request, overwriting what the
// client sent; the API keeps it so that one id spans both logs.
func TestRequestIDFromTheBalancerIsKept(t *testing.T) {
const fromLB = "0123456789abcdef0123456789abcdef"
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": fromLB})
if got := rec.Header().Get("X-Request-Id"); got != fromLB {
t.Fatalf("X-Request-Id = %q, want %q", got, fromLB)
}
}
func TestMalformedRequestIDIsReplaced(t *testing.T) {
for _, bad := range []string{"has space", "semi;colon", "tab\there", strings.Repeat("a", 65)} {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": bad})
if got := rec.Header().Get("X-Request-Id"); got == "" || got == bad {
t.Errorf("X-Request-Id for %q = %q, want a generated value", bad, got)
}
}
}
func TestDecodeJSONHappyPath(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodPost, "/decode", `{"text":"Привет","count":2}`, map[string]string{"Content-Type": "application/json; charset=utf-8"})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"Привет"`) {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
}
func TestDecodeJSONFailures(t *testing.T) {
jsonCT := map[string]string{"Content-Type": "application/json"}
cases := []struct {
name string
body string
headers map[string]string
status int
code string
contain string
}{
{"no content type", `{"text":"x"}`, nil, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
{"wrong content type", `{"text":"x"}`, map[string]string{"Content-Type": "text/plain"}, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
{"empty body", "", jsonCT, http.StatusBadRequest, "invalid_request", "body"},
{"malformed", `{"text":`, jsonCT, http.StatusBadRequest, "invalid_request", "malformed"},
{"invalid utf-8", "{\"text\":\"bad \xff byte\"}", jsonCT, http.StatusBadRequest, "invalid_request", "UTF-8"},
{"unknown field", `{"text":"x","extra":1}`, jsonCT, http.StatusBadRequest, "invalid_request", "extra"},
{"wrong type", `{"text":123}`, jsonCT, http.StatusBadRequest, "invalid_request", "text"},
{"trailing data", `{"text":"x"} {"text":"y"}`, jsonCT, http.StatusBadRequest, "invalid_request", "after"},
{"array instead of object", `[1,2]`, jsonCT, http.StatusBadRequest, "invalid_request", ""},
{"too large", `{"text":"` + strings.Repeat("x", 100) + `"}`, jsonCT, http.StatusRequestEntityTooLarge, "payload_too_large", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodPost, "/decode", tc.body, tc.headers)
assertError(t, rec, eb, tc.status, tc.code)
if tc.contain != "" && !strings.Contains(eb.Error.Message, tc.contain) {
t.Fatalf("message %q must mention %q", eb.Error.Message, tc.contain)
}
if strings.Contains(eb.Error.Message, "httpx_test") || strings.Contains(eb.Error.Message, "payload") {
t.Fatalf("message must not leak Go type names: %q", eb.Error.Message)
}
})
}
}
func TestAccessLogHasRequestFieldsButNoBody(t *testing.T) {
logs := &bytes.Buffer{}
e := newEngine(t, logs)
rec, _ := do(t, e, http.MethodPost, "/decode", `{"text":"confidential"}`, map[string]string{"Content-Type": "application/json"})
var entry map[string]any
line := lastLine(logs.String())
if err := json.Unmarshal([]byte(line), &entry); err != nil {
t.Fatalf("log line is not JSON: %v: %s", err, line)
}
for _, key := range []string{"request_id", "method", "path", "status", "duration_ms"} {
if _, ok := entry[key]; !ok {
t.Errorf("log entry missing %q: %s", key, line)
}
}
if entry["request_id"] != rec.Header().Get("X-Request-Id") {
t.Errorf("log request_id %v != header %q", entry["request_id"], rec.Header().Get("X-Request-Id"))
}
if strings.Contains(logs.String(), "confidential") {
t.Fatal("request body must never be logged")
}
}
func TestAccessLogLevelFollowsStatus(t *testing.T) {
logs := &bytes.Buffer{}
e := newEngineAt(t, logs, slog.LevelInfo)
do(t, e, http.MethodGet, "/ok", "", nil)
if strings.Contains(logs.String(), `"msg":"request"`) {
t.Fatalf("successful requests must be logged at debug level only, got %s", logs.String())
}
do(t, e, http.MethodGet, "/notfound", "", nil)
if entry := logEntry(t, logs); entry["level"] != "INFO" || entry["status"] != float64(404) {
t.Fatalf("client error must be logged at info level with its status, got %v", entry)
}
do(t, e, http.MethodGet, "/fail", "", nil)
if entry := logEntry(t, logs); entry["level"] != "ERROR" || entry["status"] != float64(500) {
t.Fatalf("server error must be logged at error level with its status, got %v", entry)
}
verbose := &bytes.Buffer{}
do(t, newEngineAt(t, verbose, slog.LevelDebug), http.MethodGet, "/ok", "", nil)
if entry := logEntry(t, verbose); entry["level"] != "DEBUG" || entry["status"] != float64(200) {
t.Fatalf("at debug level successful requests must be logged, got %v", entry)
}
}
func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) {
logs := &bytes.Buffer{}
rec, _ := do(t, newEngine(t, logs), http.MethodGet, "/who", "", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) {
t.Fatalf("UserID must return what SetUserID stored: %d %s", rec.Code, rec.Body.String())
}
if entry := logEntry(t, logs); entry["user_id"] != "11111111-1111-4111-8111-111111111111" {
t.Fatalf("access log must attribute the request to the user, got %v", entry)
}
anonymous := &bytes.Buffer{}
do(t, newEngine(t, anonymous), http.MethodGet, "/ok", "", nil)
if _, present := logEntry(t, anonymous)["user_id"]; present {
t.Fatal("anonymous requests must not carry user_id")
}
}
func TestWithUserPassesTheIdentifiedCaller(t *testing.T) {
actor := uuid.MustParse("22222222-2222-4222-8222-222222222222")
e := newEngine(t, nil)
e.GET("/actor",
func(c *gin.Context) { httpx.SetUserID(c, actor) },
httpx.WithUser(func(c *gin.Context, got uuid.UUID) {
httpx.JSON(c, http.StatusOK, gin.H{"id": got.String()})
}))
rec, _ := do(t, e, http.MethodGet, "/actor", "", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), actor.String()) {
t.Fatalf("handler did not receive the caller: %d %s", rec.Code, rec.Body.String())
}
}
// Reaching WithUser without an authentication middleware in front is a
// wiring mistake, so it must not be blamed on the client with a 401.
func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) {
e := newEngine(t, nil)
e.GET("/actor", httpx.WithUser(func(c *gin.Context, _ uuid.UUID) {
httpx.JSON(c, http.StatusOK, gin.H{})
}))
rec, eb := do(t, e, http.MethodGet, "/actor", "", nil)
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
}
// A 5xx tells the client only the safe message; the operator must still see
// why the dependency failed, so the cause goes to the log.
func TestUnavailableCauseIsLoggedButNotReturned(t *testing.T) {
logs := &bytes.Buffer{}
e := newEngine(t, logs)
e.GET("/down", func(c *gin.Context) {
cause := errors.New("dial tcp 10.0.0.7:5432: connect: connection refused")
httpx.Error(c, fmt.Errorf("select user: %w", apperr.Wrap(apperr.KindUnavailable, "database unavailable", cause)))
})
rec, eb := do(t, e, http.MethodGet, "/down", "", nil)
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
// Neither the cause nor the wrapping context of internal operations
// ("select user: ...") may reach the client.
if eb.Error.Message != "database unavailable" {
t.Fatalf("client message = %q, want only the application message", eb.Error.Message)
}
if !strings.Contains(logs.String(), "connection refused") || !strings.Contains(logs.String(), eb.Error.RequestID) {
t.Fatalf("log must carry the cause and the request id, got:\n%s", logs.String())
}
}
// Everything below Timeout sees one deadline, so waiting on a dependency
// ends with the request instead of holding the client.
func TestTimeoutBoundsTheRequestContext(t *testing.T) {
e := newEngine(t, nil)
e.GET("/slow", httpx.Timeout(50*time.Millisecond), func(c *gin.Context) {
select {
case <-c.Request.Context().Done():
httpx.Error(c, apperr.Wrap(apperr.KindUnavailable, "gave up", c.Request.Context().Err()))
case <-time.After(5 * time.Second):
httpx.JSON(c, http.StatusOK, gin.H{})
}
})
start := time.Now()
rec, eb := do(t, e, http.MethodGet, "/slow", "", nil)
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("request took %v, want it cut at the 50ms deadline", elapsed)
}
}
func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any {
t.Helper()
var entry map[string]any
line := lastLine(logs.String())
if err := json.Unmarshal([]byte(line), &entry); err != nil {
t.Fatalf("log line is not JSON: %v: %s", err, line)
}
return entry
}
func TestTimestampFormat(t *testing.T) {
ts := time.Date(2026, 9, 1, 12, 0, 0, 0, time.FixedZone("MSK", 3*3600))
if got := httpx.Timestamp(ts); got != "2026-09-01T09:00:00.000Z" {
t.Fatalf("Timestamp = %q", got)
}
ts = time.Date(2026, 9, 1, 12, 0, 0, 7_000_000, time.UTC)
if got := httpx.Timestamp(ts); got != "2026-09-01T12:00:00.007Z" {
t.Fatalf("Timestamp = %q", got)
}
}
func lastLine(s string) string {
lines := strings.Split(strings.TrimSpace(s), "\n")
return lines[len(lines)-1]
}
+42
View File
@@ -0,0 +1,42 @@
package httpx
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const keyUserID = "messenger.user_id"
// SetUserID records the authenticated caller for the handlers behind the
// authentication middleware and for the access log.
func SetUserID(c *gin.Context, id uuid.UUID) {
c.Set(keyUserID, id)
}
func UserID(c *gin.Context) (uuid.UUID, bool) {
v, ok := c.Get(keyUserID)
if !ok {
return uuid.Nil, false
}
id, ok := v.(uuid.UUID)
return id, ok
}
// UserHandler is a handler that needs the authenticated caller.
type UserHandler func(c *gin.Context, actor uuid.UUID)
// WithUser adapts a UserHandler to gin. Reaching it without the
// authentication middleware in front is a wiring mistake, so it is reported
// as an internal error rather than blamed on the client with a 401.
func WithUser(h UserHandler) gin.HandlerFunc {
return func(c *gin.Context) {
actor, ok := UserID(c)
if !ok {
Error(c, errors.New("route is missing the authentication middleware"))
return
}
h(c, actor)
}
}
+136
View File
@@ -0,0 +1,136 @@
package httpx
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"regexp"
"runtime/debug"
"time"
"github.com/gin-gonic/gin"
)
// instance names the process that answered, so a client behind the load
// balancer can tell the replicas apart.
func instance(id string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("X-Instance-Id", id)
c.Next()
}
}
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`)
// requestID keeps the X-Request-Id set by the load balancer, which overwrites
// any value a client sends; a malformed value is replaced, so a direct caller
// cannot inject into the logs.
func requestID(log *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.GetHeader("X-Request-Id")
if !requestIDPattern.MatchString(id) {
id = newRequestID()
}
c.Set(keyRequestID, id)
c.Set(keyLogger, log)
c.Writer.Header().Set("X-Request-Id", id)
c.Next()
}
}
func newRequestID() string {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("httpx: random source unavailable: " + err.Error())
}
return hex.EncodeToString(raw[:])
}
// accessLog writes one line per request at a level that follows the
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
// how much traffic is recorded. Headers, query strings and bodies are never
// recorded. time.Since uses the monotonic clock, so wall clock adjustments
// cannot distort the duration.
func accessLog() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
status := c.Writer.Status()
level := slog.LevelDebug
switch {
case status >= http.StatusInternalServerError:
level = slog.LevelError
case status >= http.StatusBadRequest:
level = slog.LevelInfo
}
log := logger(c)
ctx := c.Request.Context()
if !log.Enabled(ctx, level) {
return
}
attrs := []any{
"request_id", RequestID(c),
"method", c.Request.Method,
"path", c.Request.URL.Path,
"status", status,
"duration_ms", float64(time.Since(start).Microseconds()) / 1000,
"bytes", c.Writer.Size(),
}
if id, ok := UserID(c); ok {
attrs = append(attrs, "user_id", id.String())
}
log.Log(ctx, level, "request", attrs...)
}
}
// recovery turns a panic into a contract 500; the stack goes to the log only.
func recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
logger(c).Error("panic recovered",
"request_id", RequestID(c),
"panic", fmt.Sprint(r),
"stack", string(debug.Stack()),
)
if !c.Writer.Written() {
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
}
c.Abort()
}
}()
c.Next()
}
}
// Timeout bounds the whole request with one deadline: waiting for a pooled
// connection, SQL statements and session lookups all observe it, so a hung
// dependency ends in a 503 within d instead of holding the client.
func Timeout(d time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), d)
defer cancel()
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}
// bodyLimit caps request bodies; exceeding it surfaces from the JSON
// decoder as *http.MaxBytesError.
func bodyLimit(maxBytes int64) gin.HandlerFunc {
return func(c *gin.Context) {
// The authenticated binary handler installs its own 10 MiB limit.
if c.Request.Method == http.MethodPost && c.FullPath() == "/api/v1/chats/:chat_id/attachments" {
c.Next()
return
}
if c.Request.Body != nil {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
}
c.Next()
}
}
+87
View File
@@ -0,0 +1,87 @@
package httpx
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
type errorEnvelope struct {
Error errorDetail `json:"error"`
}
type errorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type statusCode struct {
status int
code string
}
var kinds = map[apperr.Kind]statusCode{
apperr.KindInvalid: {http.StatusBadRequest, "invalid_request"},
apperr.KindUnauthorized: {http.StatusUnauthorized, "unauthorized"},
apperr.KindNotFound: {http.StatusNotFound, "not_found"},
apperr.KindConflict: {http.StatusConflict, "conflict"},
apperr.KindPayloadTooLarge: {http.StatusRequestEntityTooLarge, "payload_too_large"},
apperr.KindUnsupportedMedia: {http.StatusUnsupportedMediaType, "unsupported_media_type"},
apperr.KindUnavailable: {http.StatusServiceUnavailable, "unavailable"},
}
// JSON is the single place that fixes the response media type; PureJSON
// keeps non-ASCII and HTML characters verbatim.
func JSON(c *gin.Context, status int, body any) {
c.PureJSON(status, body)
}
// Fail writes the contract error body and stops the handler chain.
func Fail(c *gin.Context, status int, code, message string) {
JSON(c, status, errorEnvelope{Error: errorDetail{
Code: code,
Message: message,
RequestID: RequestID(c),
}})
c.Abort()
}
// Error maps an application error to its status. Anything that is not an
// application error is logged with its text and reported as an opaque 500,
// so internal details never reach the client. An application error shows the
// client only its own message, never the context it was wrapped in on the
// way up; when it is answered with a 5xx (a dependency outage) the full
// chain and the cause go to the log for the operator.
func Error(c *gin.Context, err error) {
appErr, isApp := errors.AsType[*apperr.Error](err)
var mapped statusCode
known := false
if isApp {
mapped, known = kinds[appErr.Kind]
}
if !known {
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
return
}
if mapped.status >= http.StatusInternalServerError {
attrs := []any{"request_id", RequestID(c), "error", err.Error()}
if appErr.Cause != nil {
attrs = append(attrs, "cause", appErr.Cause.Error())
}
logger(c).Error("request failed", attrs...)
}
Fail(c, mapped.status, mapped.code, appErr.Message)
}
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
// (the oldest version the public tests support) only parses 3 or 6 fractional
// digits, and RFC3339Nano would trim trailing zeros to a variable width.
func Timestamp(t time.Time) string {
return t.UTC().Format("2006-01-02T15:04:05.000Z")
}