package jobs import ( "context" "time" "github.com/rs/zerolog/log" "github.com/creativenoz/aurganize-v62/backend/internal/repositories" ) type SesssionCleanUpJob struct { sessionRep *repositories.SessionRepository interval time.Duration stopChannel chan struct{} } func NewSessionCleanUpJob(sessionRepo *repositories.SessionRepository) *SesssionCleanUpJob { return &SesssionCleanUpJob{ sessionRep: sessionRepo, interval: 12 * time.Hour, stopChannel: make(chan struct{}), } } func (j *SesssionCleanUpJob) Start(ctx context.Context) { log.Info().Msg("session cleanup job started") ticker := time.NewTicker(j.interval) defer ticker.Stop() for { select { case <-ticker.C: j.run(ctx) case <-j.stopChannel: log.Info().Msg("stop cleanup session command recieved") return case <-ctx.Done(): log.Info().Msg("session cleanup job cancelled") return } } } func (j *SesssionCleanUpJob) Stop() { close(j.stopChannel) } func (j *SesssionCleanUpJob) run(ctx context.Context) { startTime := time.Now() deleted, err := j.sessionRep.DeleteExpired(ctx) if err != nil { log.Info().Msg("failed to clean up sessions") log.Error(). Err(err). Dur("duration", time.Since(startTime)). Msg("failed to clean up sessions") return } log.Info(). Int64("deleted_count", deleted). Dur("duration", time.Since(startTime)). Msg("session clean up completed") } func (j *SesssionCleanUpJob) RunOnce(ctx context.Context) error { startTime := time.Now() log.Info().Msg("manually triggered session cleanup") deleted, err := j.sessionRep.DeleteExpired(ctx) if err != nil { log.Error(). Err(err). Dur("duration", time.Since(startTime)). Msg("Failed to cleanup sessions") return err } log.Info(). Int64("deleted_count", deleted). Dur("duration", time.Since(startTime)). Msg("Manual session cleanup completed") return nil }