237 lines
6.6 KiB
Go
237 lines
6.6 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"mtusi.ru/messenger-lab3/internal/auth"
|
|
"mtusi.ru/messenger-lab3/internal/model"
|
|
"mtusi.ru/messenger-lab3/internal/session"
|
|
"mtusi.ru/messenger-lab3/internal/store"
|
|
)
|
|
|
|
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
|
|
|
|
type healthResponse struct {
|
|
Status string `json:"status"`
|
|
}
|
|
|
|
// identity is the authenticated principal derived only from the Bearer
|
|
// session. X-User-Id is not consulted anywhere in this package.
|
|
type identity struct {
|
|
user model.User
|
|
token string
|
|
}
|
|
|
|
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
|
|
// and messages; Valkey is the source of truth for sessions. App adds request
|
|
// validation, authentication and contract mapping.
|
|
type App struct {
|
|
store *store.Store
|
|
sessions *session.Store
|
|
log *slog.Logger
|
|
ready atomic.Bool
|
|
maxBody int64
|
|
instanceID string
|
|
version string
|
|
startedAt time.Time
|
|
dummyHash string
|
|
|
|
createdMessages atomic.Uint64
|
|
replayedMessages atomic.Uint64
|
|
conflictMessages atomic.Uint64
|
|
}
|
|
|
|
// New creates the HTTP application. The dummy Argon2id hash is generated once
|
|
// so login can spend the same work for an unknown username as for a known one.
|
|
func New(repository *store.Store, sessions *session.Store, logger *slog.Logger, instanceID, version string) (*App, error) {
|
|
dummy, err := auth.Hash("dummy-password-never-used-for-login")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
app := &App{
|
|
store: repository,
|
|
sessions: sessions,
|
|
log: logger,
|
|
maxBody: maxBodyBytes,
|
|
instanceID: instanceID,
|
|
version: version,
|
|
startedAt: time.Now(),
|
|
dummyHash: dummy,
|
|
}
|
|
app.ready.Store(true)
|
|
return app, nil
|
|
}
|
|
|
|
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
|
|
// received and before http.Server.Shutdown stops accepting connections.
|
|
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
|
|
|
|
// Handler returns the fully instrumented handler.
|
|
func (a *App) Handler() http.Handler {
|
|
return a.withObservability(a)
|
|
}
|
|
|
|
// ServeHTTP routes the lab3 API. Method mismatches become 404 in the contract
|
|
// error shape because the public error enum has no method_not_allowed code.
|
|
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/health/live":
|
|
if r.Method != http.MethodGet {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
|
case "/health/ready":
|
|
if r.Method != http.MethodGet {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.readiness(w, r)
|
|
case "/api/v1/users":
|
|
if r.Method != http.MethodPost {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.createUser(w, r)
|
|
case "/api/v1/auth/sessions":
|
|
if r.Method != http.MethodPost {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.createSession(w, r)
|
|
case "/api/v1/auth/sessions/current":
|
|
if r.Method != http.MethodDelete {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.withAuth(a.logout).ServeHTTP(w, r)
|
|
case "/api/v1/users/me":
|
|
if r.Method != http.MethodGet {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.withAuth(a.currentUser).ServeHTTP(w, r)
|
|
case "/api/v1/chats":
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
a.withAuth(a.listChats).ServeHTTP(w, r)
|
|
case http.MethodPost:
|
|
a.withAuth(a.createChat).ServeHTTP(w, r)
|
|
default:
|
|
a.notFound(w, r)
|
|
}
|
|
default:
|
|
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
|
|
// Authentication runs before resource resolution: an anonymous
|
|
// request must not learn whether a chat id exists.
|
|
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
|
|
a.chatRoutes(w, r, rest, actor)
|
|
}).ServeHTTP(w, r)
|
|
return
|
|
}
|
|
a.notFound(w, r)
|
|
}
|
|
}
|
|
|
|
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
|
|
parts := splitPath(rest)
|
|
if len(parts) == 1 {
|
|
if r.Method != http.MethodGet {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.getChat(w, r, parts[0], actor)
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "messages" {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
a.listMessages(w, r, parts[0], actor)
|
|
case http.MethodPost:
|
|
a.createMessage(w, r, parts[0], actor)
|
|
default:
|
|
a.notFound(w, r)
|
|
}
|
|
return
|
|
}
|
|
a.notFound(w, r)
|
|
}
|
|
|
|
// withAuth resolves the Bearer session before the wrapped handler runs.
|
|
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
actor, problem := a.authenticate(r)
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
next(w, r, actor)
|
|
}
|
|
}
|
|
|
|
// readiness reports whether the mandatory synchronous path can be served.
|
|
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
|
|
// answer, and without Valkey it cannot authenticate a single protected call.
|
|
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
|
|
if !a.ready.Load() {
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
|
dbErr := a.store.Ping(dbCtx)
|
|
dbCancel()
|
|
if dbErr != nil {
|
|
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
|
cacheErr := a.sessions.Ping(cacheCtx)
|
|
cacheCancel()
|
|
if cacheErr != nil {
|
|
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
|
}
|
|
|
|
// writeJSON encodes a success response. X-Request-Id is set by middleware
|
|
// before the handler runs, so even a marshal-time 500 keeps the header.
|
|
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
|
|
data, err := json.Marshal(value)
|
|
if err != nil {
|
|
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusInternal)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if _, err := w.Write(data); err != nil {
|
|
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
}
|
|
}
|
|
|
|
func trimPathPrefix(value, prefix string) (string, bool) {
|
|
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
|
|
return "", false
|
|
}
|
|
return value[len(prefix):], true
|
|
}
|
|
|
|
func splitPath(value string) []string {
|
|
parts := strings.Split(value, "/")
|
|
for _, part := range parts {
|
|
if part == "" {
|
|
return nil
|
|
}
|
|
}
|
|
return parts
|
|
}
|