forked from mtusi2026/mtusi2026lab5
134 lines
4.0 KiB
Go
134 lines
4.0 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
type Dependencies struct {
|
|
Users UserRepository
|
|
Chats ChatRepository
|
|
Messages MessageRepository
|
|
Attachments AttachmentService
|
|
Sessions SessionStore
|
|
Passwords PasswordService
|
|
Database HealthChecker
|
|
Objects HealthChecker
|
|
}
|
|
|
|
type Config struct {
|
|
SessionTTL time.Duration
|
|
IdempotencyTTL time.Duration
|
|
RequestTTL time.Duration
|
|
InstanceID string
|
|
SwaggerPort string
|
|
}
|
|
|
|
type Server struct {
|
|
userRepository UserRepository
|
|
chatRepository ChatRepository
|
|
messageRepository MessageRepository
|
|
attachments AttachmentService
|
|
sessions SessionStore
|
|
passwords PasswordService
|
|
database HealthChecker
|
|
objects HealthChecker
|
|
sessionTTL time.Duration
|
|
idempotencyTTL time.Duration
|
|
requestTTL time.Duration
|
|
instanceID string
|
|
logger *slog.Logger
|
|
swaggerPort string
|
|
metrics *metrics
|
|
ready atomic.Bool
|
|
}
|
|
|
|
type statusWriter struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (w *statusWriter) WriteHeader(status int) {
|
|
w.status = status
|
|
w.ResponseWriter.WriteHeader(status)
|
|
}
|
|
|
|
func NewServer(
|
|
logger *slog.Logger,
|
|
dependencies Dependencies,
|
|
config Config,
|
|
) *Server {
|
|
s := &Server{
|
|
userRepository: dependencies.Users, chatRepository: dependencies.Chats,
|
|
messageRepository: dependencies.Messages,
|
|
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
|
|
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
|
|
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
|
|
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort, metrics: newMetrics(),
|
|
}
|
|
s.ready.Store(true)
|
|
return s
|
|
}
|
|
|
|
func (s *Server) SetReady(ready bool) {
|
|
s.ready.Store(ready)
|
|
}
|
|
|
|
func (s *Server) Handler() http.Handler {
|
|
return http.HandlerFunc(s.serve)
|
|
}
|
|
|
|
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Instance-Id", s.instanceID)
|
|
requestID, err := newID()
|
|
if err != nil {
|
|
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
|
started := time.Now()
|
|
s.metrics.inFlight.Inc()
|
|
defer func() {
|
|
s.metrics.inFlight.Dec()
|
|
if recovered := recover(); recovered != nil {
|
|
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
|
|
if wrapped.status == http.StatusOK {
|
|
writeError(wrapped, requestID, internalError())
|
|
}
|
|
}
|
|
s.metrics.observe(r, wrapped.status, started)
|
|
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
|
}()
|
|
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
|
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
|
|
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Idempotency-Key")
|
|
wrapped.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
|
|
defer cancel()
|
|
r = r.WithContext(ctx)
|
|
if apiErr := s.route(wrapped, r); apiErr != nil {
|
|
if apiErr.status == http.StatusUnauthorized {
|
|
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
|
|
}
|
|
writeError(wrapped, requestID, apiErr)
|
|
}
|
|
}
|
|
|
|
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
|
|
origin := r.Header.Get("Origin")
|
|
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
|
|
return false
|
|
}
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Instance-Id")
|
|
w.Header().Add("Vary", "Origin")
|
|
return true
|
|
}
|