Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/uuid"
|
||||
)
|
||||
|
||||
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
|
||||
// safe human-readable message and an optional authentication challenge. The
|
||||
// request id is filled from the request context at write time.
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
challenge string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.code + ": " + e.message }
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
var (
|
||||
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
|
||||
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
|
||||
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
|
||||
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
|
||||
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
|
||||
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
|
||||
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
|
||||
)
|
||||
|
||||
func invalidRequest(message string) *apiError {
|
||||
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
|
||||
}
|
||||
|
||||
func unauthorizedBasic() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
|
||||
}
|
||||
|
||||
func unauthorizedBearer() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
|
||||
}
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// writeError writes a JSON error whose request_id matches X-Request-Id. The
|
||||
// message never contains SQL, stack traces, credentials or object existence
|
||||
// details for foreign resources.
|
||||
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
|
||||
requestID := requestIDFromContext(r.Context())
|
||||
if requestID == "" {
|
||||
requestID = w.Header().Get("X-Request-Id")
|
||||
}
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
if problem.challenge != "" {
|
||||
w.Header().Set("WWW-Authenticate", problem.challenge)
|
||||
}
|
||||
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
|
||||
Code: problem.code,
|
||||
Message: problem.message,
|
||||
RequestID: requestID,
|
||||
}})
|
||||
}
|
||||
|
||||
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
}
|
||||
|
||||
type requestIDContextKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
value, _ := ctx.Value(requestIDContextKey{}).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
// statusWriter records the status code and byte count for logs and for the
|
||||
// panic path, so a partially written response is not written twice.
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
if w.wrote {
|
||||
return
|
||||
}
|
||||
w.wrote = true
|
||||
w.status = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(data []byte) (int, error) {
|
||||
if !w.wrote {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
written, err := w.ResponseWriter.Write(data)
|
||||
w.bytes += written
|
||||
return written, err
|
||||
}
|
||||
|
||||
func (a *App) withObservability(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
requestID := uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
// Stable for the life of the process and unique per container. lab3
|
||||
// uses the container hostname: it is the actual process identity, so
|
||||
// stop-one can map a response to exactly one container. lab7 will
|
||||
// replace it with an opaque alias.
|
||||
w.Header().Set("X-Instance-Id", a.instanceID)
|
||||
// Extra, non-contract header used only to observe an image replacement
|
||||
// during the rolling-update experiment. The mandatory contract does
|
||||
// not define or require it.
|
||||
w.Header().Set("X-App-Version", a.version)
|
||||
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
|
||||
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
a.log.Error("panic while handling request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"panic", recovered,
|
||||
)
|
||||
if !writer.wrote {
|
||||
a.writeError(writer, r, statusInternal)
|
||||
}
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
|
||||
level = slog.LevelDebug
|
||||
}
|
||||
a.log.Log(r.Context(), level, "http request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", writer.status,
|
||||
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
|
||||
"bytes", writer.bytes,
|
||||
)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
|
||||
// atomicBool keeps the readiness flag readable from the signal goroutine
|
||||
// without importing sync/atomic into every handler file.
|
||||
type atomicBool struct{ value atomic.Bool }
|
||||
|
||||
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
|
||||
func (b *atomicBool) Load() bool { return b.value.Load() }
|
||||
Reference in New Issue
Block a user