Add cleanup, minor fixes
This commit is contained in:
1 parent
97dc0a3570
commit
284e4e7080
7 files changed
+107
-15
No files matched your search
@@ -149,6 +149,46 @@ func (h *Handler) Close() error {
|
||||
return h.db.Close()
|
||||
}
|
||||
|
||||
// Cleanup purges expired sessions, spent/expired invites and never-activated
|
||||
// users. Each target is cleaned independently so a single failure does not
|
||||
// prevent the others from running.
|
||||
func (h *Handler) Cleanup(ctx context.Context) {
|
||||
if err := h.sessions.CleanupSessions(ctx); err != nil {
|
||||
slog.Error("cleanup sessions", slog.String("op", "rest.Cleanup"), slog.Any("error", err))
|
||||
}
|
||||
if err := h.invites.CleanupInvites(ctx); err != nil {
|
||||
slog.Error("cleanup invites", slog.String("op", "rest.Cleanup"), slog.Any("error", err))
|
||||
}
|
||||
if err := h.users.CleanupUsers(ctx); err != nil {
|
||||
slog.Error("cleanup users", slog.String("op", "rest.Cleanup"), slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
|
||||
// runCleanupLoop runs Cleanup immediately and then on every tick until ctx is
|
||||
// cancelled. It is a no-op when the configured interval is non-positive.
|
||||
func (h *Handler) runCleanupLoop(ctx context.Context) {
|
||||
interval := h.cfg.CleanupInterval
|
||||
if interval <= 0 {
|
||||
slog.Info("background cleanup disabled", slog.String("op", "rest.runCleanupLoop"))
|
||||
return
|
||||
}
|
||||
|
||||
slog.Info("background cleanup started", slog.String("op", "rest.runCleanupLoop"), slog.Duration("interval", interval))
|
||||
h.Cleanup(ctx)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
h.Cleanup(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Router() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h.registerRoutes(mux)
|
||||
@@ -156,6 +196,8 @@ func (h *Handler) Router() http.Handler {
|
||||
}
|
||||
|
||||
func (h *Handler) Serve(ctx context.Context) error {
|
||||
go h.runCleanupLoop(ctx)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: h.cfg.Addr,
|
||||
Handler: h.Router(),
|
||||
|
||||
Reference in new issue
Block a user