feat: port lab4 implementation

This commit is contained in:
kk10
2026-11-13 15:52:39 +03:00
parent 276dbdad8a
commit 36d9b0c8f6
101 changed files with 8426 additions and 6 deletions
+165
View File
@@ -0,0 +1,165 @@
package app
import (
"context"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/joho/godotenv"
goredis "github.com/redis/go-redis/v9"
"mtusi2026-messenger/internal/config"
"mtusi2026-messenger/internal/db"
"mtusi2026-messenger/internal/logger"
"mtusi2026-messenger/internal/postgres"
"mtusi2026-messenger/internal/redis"
s3store "mtusi2026-messenger/internal/s3"
"mtusi2026-messenger/internal/service"
)
func Run() error {
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
return err
}
cfg := config.Load()
log := logger.New(cfg.Logging.Level).With("instance_id", cfg.Server.InstanceID)
dbURL, err := cfg.Database.URL()
if err != nil {
log.Error("read database url", "error", err)
return err
}
pool, err := postgres.New(context.Background(), dbURL)
if err != nil {
log.Error("connect to database", "error", err)
return err
}
defer pool.Close()
queries := db.New(pool)
var rdb *goredis.Client
if cfg.UseCache() {
cacheURL, err := cfg.Redis.URL()
if err != nil {
log.Error("read redis url", "error", err)
return err
}
rdb, err = redis.New(context.Background(), log, cacheURL)
if err != nil {
log.Error("create redis client", "error", err)
return err
}
defer rdb.Close()
}
log.Info("session store configured", "store", cfg.SessionStore)
s3Client, err := s3store.New(context.Background(), cfg.S3, log)
if err != nil {
log.Error("create s3 client", "error", err)
return err
}
ensureCtx, cancelEnsure := context.WithTimeout(context.Background(), 10*time.Second)
err = s3Client.EnsureBucket(ensureCtx)
cancelEnsure()
if err != nil {
log.Error("ensure s3 bucket", "error", err)
return err
}
log.Info("s3 storage ready", "endpoint", cfg.S3.Endpoint, "bucket", s3Client.Bucket())
cleanupCtx, stopCleanup := context.WithCancel(context.Background())
var cleanupWG sync.WaitGroup
cleanupWG.Go(func() {
runSessionCleanup(cleanupCtx, log, queries, sessionCleanupInterval)
})
cleanupWG.Go(func() {
runIdempotencyCleanup(cleanupCtx, log, queries, cfg.Server.IdempotencyTTL, idempotencyCleanupInterval)
})
cleanupWG.Go(func() {
runAttachmentCleanup(
cleanupCtx,
log,
queries,
s3Client,
attachmentOrphanGracePeriod,
attachmentCleanupInterval,
)
})
defer func() {
stopCleanup()
cleanupWG.Wait()
}()
authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log)
userService := service.NewUserService(queries)
chatService := service.NewChatService(pool, queries)
messageService := service.NewMessageService(pool, queries)
attachmentService := service.NewAttachmentService(queries, s3Client, cfg.S3.MaxUploadBytes, cfg.S3.MaxImagePixels)
router := NewRouter(
log,
cfg.Server.InstanceID,
cfg.Server.MaxInflightRequests,
cfg.S3.MaxUploadBytes,
pool,
s3Client,
authService,
userService,
chatService,
messageService,
attachmentService,
)
server := &http.Server{
Addr: cfg.Server.Host + ":" + cfg.Server.Port,
Handler: router,
}
serverErrors := make(chan error, 1)
go func() {
log.Info("server starting", "addr", server.Addr)
serverErrors <- server.ListenAndServe()
}()
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(signalCh)
select {
case err := <-serverErrors:
if err == http.ErrServerClosed {
return nil
}
log.Error("server failed", "error", err)
return err
case sig := <-signalCh:
log.Info("shutdown signal received", "signal", sig.String())
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Error("server shutdown failed", "error", err)
return err
}
log.Info("server stopped")
return nil
}
}
+149
View File
@@ -0,0 +1,149 @@
package app
import (
"context"
"log/slog"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/db"
)
const (
sessionCleanupInterval = time.Hour
idempotencyCleanupInterval = time.Hour
attachmentCleanupInterval = 10 * time.Minute
attachmentOrphanGracePeriod = time.Hour
)
type sessionCleaner interface {
DeleteExpiredSessions(ctx context.Context) (int64, error)
}
type idempotencyCleaner interface {
DeleteExpiredIdempotencyKeys(ctx context.Context, cutoff time.Time) (int64, error)
}
type staleUploadLister interface {
ListStaleAttachmentUploads(ctx context.Context, cutoff time.Time) ([]db.ListStaleAttachmentUploadsRow, error)
DeleteQueuedAttachment(ctx context.Context, id uuid.UUID) (int64, error)
}
type objectDeleter interface {
DeleteAdmin(ctx context.Context, key string) error
}
func runSessionCleanup(ctx context.Context, log *slog.Logger, q sessionCleaner, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
n, err := q.DeleteExpiredSessions(ctx)
if err != nil {
if ctx.Err() == nil {
log.Error("delete expired sessions", "error", err)
}
continue
}
if n > 0 {
log.Info("expired sessions deleted", "count", n)
}
}
}
}
func runIdempotencyCleanup(
ctx context.Context,
log *slog.Logger,
q idempotencyCleaner,
ttl time.Duration,
interval time.Duration,
) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
n, err := q.DeleteExpiredIdempotencyKeys(ctx, time.Now().Add(-ttl))
if err != nil {
if ctx.Err() == nil {
log.Error("delete expired idempotency keys", "error", err)
}
continue
}
if n > 0 {
log.Info("expired idempotency keys deleted", "count", n)
}
}
}
}
func runAttachmentCleanup(
ctx context.Context,
log *slog.Logger,
q staleUploadLister,
store objectDeleter,
grace time.Duration,
interval time.Duration,
) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
cleanupStaleUploads(ctx, log, q, store, grace)
}
}
}
func cleanupStaleUploads(
ctx context.Context,
log *slog.Logger,
q staleUploadLister,
store objectDeleter,
grace time.Duration,
) {
cutoff := time.Now().Add(-grace)
rows, err := q.ListStaleAttachmentUploads(ctx, cutoff)
if err != nil {
if ctx.Err() == nil {
log.Error("list stale attachment uploads", "error", err)
}
return
}
deleted := 0
for _, row := range rows {
removed, err := q.DeleteQueuedAttachment(ctx, row.ID)
if err != nil {
log.Error("delete stale upload row", "id", row.ID, "error", err)
continue
}
if removed == 0 {
continue
}
if err := store.DeleteAdmin(ctx, row.S3Key); err != nil {
log.Error("delete stale upload object", "key", row.S3Key, "error", err)
continue
}
deleted++
}
if deleted > 0 {
log.Info("stale attachment uploads deleted", "count", deleted)
}
}
+46
View File
@@ -0,0 +1,46 @@
package app
import (
"context"
"fmt"
"net/http"
"os"
"time"
"mtusi2026-messenger/internal/config"
"github.com/joho/godotenv"
)
func Healthcheck() int {
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
fmt.Fprintln(os.Stderr, "healthcheck: load env:", err)
return 1
}
cfg := config.Load()
url := fmt.Sprintf("http://localhost:%s/health/ready", cfg.Server.Port)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck: build request:", err)
return 1
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck: request failed:", err)
return 1
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintln(os.Stderr, "healthcheck: unexpected status", resp.StatusCode)
return 1
}
return 0
}
+72
View File
@@ -0,0 +1,72 @@
package app
import (
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"mtusi2026-messenger/internal/handler"
"mtusi2026-messenger/internal/middleware"
"mtusi2026-messenger/internal/service"
)
func NewRouter(
log *slog.Logger,
instanceID string,
maxInflightRequests int,
maxUploadBytes int,
db handler.Pinger,
storage handler.Pinger,
authService *service.AuthService,
userService *service.UserService,
chatService *service.ChatService,
messageService *service.MessageService,
attachmentService *service.AttachmentService,
) http.Handler {
router := chi.NewRouter()
healthHandler := handler.NewHealthHandler(log, db, storage)
authHandler := handler.NewAuthHandler(authService)
userHandler := handler.NewUserHandler(userService)
chatHandler := handler.NewChatHandler(chatService)
messageHandler := handler.NewMessageHandler(messageService)
attachmentHandler := handler.NewAttachmentHandler(attachmentService, maxUploadBytes)
router.Use(middleware.InstanceID(instanceID))
router.Use(middleware.RequestTimeout(5 * time.Second))
router.Use(middleware.RequestID)
router.Use(middleware.Logging(log))
router.Use(middleware.ConcurrencyLimit(maxInflightRequests))
router.Get("/health/live", healthHandler.Live)
router.Get("/health/ready", healthHandler.Ready)
router.Post("/api/v1/users", userHandler.Create)
router.Post("/api/v1/auth/sessions", authHandler.CreateSession)
router.Delete("/api/v1/auth/sessions/current", authHandler.RevokeSession)
router.Group(func(r chi.Router) {
r.Use(middleware.Auth(authService))
r.Get("/api/v1/users/me", userHandler.Me)
r.Post("/api/v1/chats", chatHandler.Create)
r.Get("/api/v1/chats", chatHandler.List)
r.Get("/api/v1/chats/{chat_id}", chatHandler.Get)
r.Post("/api/v1/chats/{chat_id}/messages", messageHandler.Create)
r.Get("/api/v1/chats/{chat_id}/messages", messageHandler.List)
r.Post("/api/v1/chats/{chat_id}/attachments", attachmentHandler.Upload)
r.Get("/api/v1/attachments/{attachment_id}", attachmentHandler.Get)
r.Get("/api/v1/attachments/{attachment_id}/content", attachmentHandler.GetContent)
})
router.Handle("/swagger/*", http.StripPrefix("/swagger/", http.FileServer(http.Dir("web/swagger"))))
router.Handle("/contracts/*", http.StripPrefix("/contracts/", http.FileServer(http.Dir("contracts"))))
return router
}