Files
mtusi2026lab4/cmd/server/main.go
T

373 lines
10 KiB
Go

package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
_ "github.com/lib/pq"
"mtusi2026lab3/internal/config"
"mtusi2026lab3/internal/ident"
"mtusi2026lab3/internal/password"
)
const (
sessionTTL = 24 * time.Hour
shutdownTimeout = 15 * time.Second
readHeaderTimeout = 5 * time.Second
idleTimeout = 60 * time.Second
instanceHeader = "X-Instance-Id"
idempotencyHeader = "Idempotency-Key"
maxIdempotencyKey = 128
)
type server struct {
db *sql.DB
instance string
}
type credentials struct {
Login string `json:"login"`
Password string `json:"password"`
}
type newMessage struct {
Recipient string `json:"recipient"`
Body string `json:"body"`
}
type message struct {
ID int64 `json:"id"`
SenderID int64 `json:"sender_id"`
Recipient string `json:"recipient"`
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
}
type session struct {
UserID int64
Login string
}
var errNoSession = errors.New("no valid session")
func main() {
cfg := config.Load()
db, err := sql.Open("postgres", cfg.DatabaseURL)
if err != nil {
log.Fatalf("open database: %v", err)
}
defer db.Close()
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(5 * time.Minute)
if err := db.Ping(); err != nil {
log.Fatalf("ping database: %v", err)
}
srv := &server{db: db, instance: cfg.InstanceID}
httpServer := &http.Server{
Addr: ":" + cfg.Port,
Handler: srv.routes(),
ReadHeaderTimeout: readHeaderTimeout,
IdleTimeout: idleTimeout,
}
go func() {
log.Printf("instance %s listening on %s", cfg.InstanceID, httpServer.Addr)
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
<-stop
log.Printf("instance %s shutting down", cfg.InstanceID)
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Printf("shutdown: %v", err)
}
}
func (s *server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("POST /api/auth/login", s.handleLogin)
mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
mux.HandleFunc("GET /api/messages", s.handleListMessages)
mux.HandleFunc("POST /api/messages", s.handleCreateMessage)
return s.addInstanceID(mux)
}
func (s *server) addInstanceID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(instanceHeader, s.instance)
next.ServeHTTP(w, r)
})
}
func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{
"status": "ok",
"instance": s.instance,
})
}
func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
var in credentials
if err := decodeJSON(w, r, &in); err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "malformed json body")
return
}
in.Login = strings.TrimSpace(in.Login)
if in.Login == "" || in.Password == "" {
writeError(w, http.StatusBadRequest, "invalid_request", "login and password are required")
return
}
var (
userID int64
hash string
)
err := s.db.QueryRowContext(r.Context(),
`SELECT id, password_hash FROM users WHERE login = $1`, in.Login).Scan(&userID, &hash)
if errors.Is(err, sql.ErrNoRows) || (err == nil && !password.Check(in.Password, hash)) {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid credentials")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "login failed")
return
}
token := ident.GenerateToken()
expiresAt := time.Now().Add(sessionTTL).UTC()
if _, err := s.db.ExecContext(r.Context(),
`INSERT INTO sessions (user_id, token, expires_at) VALUES ($1, $2, $3)`,
userID, token, expiresAt); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "session create failed")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"token": token,
"token_type": "Bearer",
"expires_at": expiresAt,
})
}
func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) {
token, ok := bearerToken(r)
if !ok {
writeError(w, http.StatusUnauthorized, "unauthorized", "bearer token required")
return
}
if _, err := s.authenticate(r); err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
return
}
if _, err := s.db.ExecContext(r.Context(), `DELETE FROM sessions WHERE token = $1`, token); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "logout failed")
return
}
w.WriteHeader(http.StatusOK)
}
func (s *server) handleListMessages(w http.ResponseWriter, r *http.Request) {
sess, err := s.authenticate(r)
if err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
return
}
rows, err := s.db.QueryContext(r.Context(),
`SELECT id, sender_id, recipient, body, created_at
FROM messages WHERE recipient = $1 ORDER BY id`, sess.Login)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "query failed")
return
}
defer rows.Close()
items := make([]message, 0)
for rows.Next() {
var m message
if err := rows.Scan(&m.ID, &m.SenderID, &m.Recipient, &m.Body, &m.CreatedAt); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "scan failed")
return
}
items = append(items, m)
}
if err := rows.Err(); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "read failed")
return
}
writeJSON(w, http.StatusOK, items)
}
func (s *server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
sess, err := s.authenticate(r)
if err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
return
}
key := strings.TrimSpace(r.Header.Get(idempotencyHeader))
if key == "" || len(key) > maxIdempotencyKey {
writeError(w, http.StatusBadRequest, "invalid_request", "Idempotency-Key header is required")
return
}
var in newMessage
if err := decodeJSON(w, r, &in); err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "malformed json body")
return
}
in.Recipient = strings.TrimSpace(in.Recipient)
if in.Recipient == "" || strings.TrimSpace(in.Body) == "" {
writeError(w, http.StatusBadRequest, "invalid_request", "recipient and body are required")
return
}
ctx := r.Context()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "begin transaction failed")
return
}
defer tx.Rollback()
var stored []byte
err = tx.QueryRowContext(ctx,
`SELECT response FROM idempotency_keys WHERE key = $1 FOR UPDATE`, key).Scan(&stored)
switch {
case err == nil:
if err := tx.Commit(); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "commit failed")
return
}
writeRawJSON(w, http.StatusOK, stored)
return
case !errors.Is(err, sql.ErrNoRows):
writeError(w, http.StatusInternalServerError, "internal_error", "idempotency lookup failed")
return
}
var msg message
err = tx.QueryRowContext(ctx,
`INSERT INTO messages (sender_id, recipient, body)
VALUES ($1, $2, $3)
RETURNING id, sender_id, recipient, body, created_at`,
sess.UserID, in.Recipient, in.Body,
).Scan(&msg.ID, &msg.SenderID, &msg.Recipient, &msg.Body, &msg.CreatedAt)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "message insert failed")
return
}
payload, err := json.Marshal(msg)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "response encode failed")
return
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO idempotency_keys (key, response) VALUES ($1, $2::jsonb)`, key, payload); err != nil {
// A concurrent request on another replica won the race for this key.
tx.Rollback()
var existing []byte
if readErr := s.db.QueryRowContext(ctx,
`SELECT response FROM idempotency_keys WHERE key = $1`, key).Scan(&existing); readErr == nil {
writeRawJSON(w, http.StatusOK, existing)
return
}
writeError(w, http.StatusInternalServerError, "internal_error", "idempotency store failed")
return
}
if err := tx.Commit(); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "commit failed")
return
}
writeRawJSON(w, http.StatusCreated, payload)
}
func (s *server) authenticate(r *http.Request) (*session, error) {
token, ok := bearerToken(r)
if !ok {
return nil, errNoSession
}
var sess session
err := s.db.QueryRowContext(r.Context(),
`SELECT s.user_id, u.login
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token = $1 AND s.expires_at > NOW()`, token).Scan(&sess.UserID, &sess.Login)
if err != nil {
return nil, errNoSession
}
return &sess, nil
}
func bearerToken(r *http.Request) (string, bool) {
header := r.Header.Get("Authorization")
const prefix = "Bearer "
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
return "", false
}
token := strings.TrimSpace(header[len(prefix):])
if token == "" {
return "", false
}
return token, true
}
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
decoder := json.NewDecoder(r.Body)
return decoder.Decode(dst)
}
func writeJSON(w http.ResponseWriter, status int, body any) {
payload, err := json.Marshal(body)
if err != nil {
http.Error(w, "response encode failed", http.StatusInternalServerError)
return
}
writeRawJSON(w, status, payload)
}
func writeRawJSON(w http.ResponseWriter, status int, payload []byte) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(payload)
}
func writeError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, map[string]any{
"error": map[string]string{
"code": code,
"message": message,
},
})
}