Files
mtusi2026lab5/src/internal/api/router.go
T

93 lines
2.8 KiB
Go

package api
import (
"log/slog"
"net/http"
"sync/atomic"
"time"
"golang.org/x/sync/semaphore"
"mtusi-messenger/internal/auth"
"mtusi-messenger/internal/objstore"
"mtusi-messenger/internal/relay"
"mtusi-messenger/internal/store"
)
type Server struct {
store *store.Store
objects *objstore.Store
sessions *auth.Sessions
hasher *auth.Hasher
log *slog.Logger
ready *atomic.Bool
timeout time.Duration
instanceID string
idempotencyTTL time.Duration
uploadTimeout time.Duration
s3Timeout time.Duration
maxUpload int64
maxPixels int64
uploadSem *semaphore.Weighted
relay *relay.Relay
maxActiveJobs int
pipelineVersion int
maxAttempts int
faultInjection bool
}
type Options struct {
InstanceID string
IdempotencyTTL time.Duration
MaxUploadBytes int64
MaxImagePixels int64
UploadConcurrency int64
UploadTimeout time.Duration
S3Timeout time.Duration
Relay *relay.Relay
MaxActiveJobs int
PipelineVersion int
MaxAttempts int
FaultInjection bool
}
func NewServer(st *store.Store, objects *objstore.Store, sessions *auth.Sessions, hasher *auth.Hasher, log *slog.Logger, ready *atomic.Bool, opt Options) *Server {
return &Server{store: st, objects: objects, sessions: sessions, hasher: hasher, log: log, ready: ready, timeout: 8 * time.Second,
instanceID: opt.InstanceID, idempotencyTTL: opt.IdempotencyTTL,
uploadTimeout: opt.UploadTimeout, s3Timeout: opt.S3Timeout,
maxUpload: opt.MaxUploadBytes, maxPixels: opt.MaxImagePixels,
uploadSem: semaphore.NewWeighted(opt.UploadConcurrency),
relay: opt.Relay, maxActiveJobs: opt.MaxActiveJobs, pipelineVersion: opt.PipelineVersion,
maxAttempts: opt.MaxAttempts, faultInjection: opt.FaultInjection}
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/health/live", s.healthLive)
mux.HandleFunc("/health/ready", s.healthReady)
mux.HandleFunc("/api/v1/users", s.usersRoute)
mux.HandleFunc("/api/v1/auth/sessions", s.createSession)
mux.HandleFunc("/api/v1/auth/sessions/current", s.auth(s.revokeSession))
mux.HandleFunc("/api/v1/users/me", s.auth(s.me))
mux.HandleFunc("/api/v1/chats", s.auth(s.chatsRoute))
mux.HandleFunc("/api/v1/chats/{chat_id}", s.auth(s.chatRoute))
mux.HandleFunc("/api/v1/chats/{chat_id}/messages", s.auth(s.messagesRoute))
mux.HandleFunc("/api/v1/chats/{chat_id}/attachments", s.auth(s.uploadAttachment))
mux.HandleFunc("/api/v1/attachments/{attachment_id}", s.auth(s.getAttachment))
mux.HandleFunc("/api/v1/attachments/{attachment_id}/content", s.auth(s.downloadAttachment))
mux.HandleFunc("/", s.notFound)
var h http.Handler = mux
h = timeoutMiddleware(s.timeout, s.uploadTimeout, h)
h = recoverMiddleware(s.log, h)
h = loggingMiddleware(s.log, h)
h = requestIDMiddleware(h)
h = instanceIDMiddleware(s.instanceID, h)
return h
}