Files
isp-admin-service/service/inactive_worker/service.go
T

99 lines
2.5 KiB
Go

package inactive_worker
import (
"context"
"time"
"isp-admin-service/conf"
"isp-admin-service/entity"
"github.com/txix-open/bgjob"
"github.com/txix-open/isp-kit/bgjobx/handler"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
const (
defaultRetryTimeout = 5 * time.Minute
)
type AuditRepo interface {
SaveAuditAsync(ctx context.Context, userId int64, message string, event string)
}
type UserRepo interface {
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
Block(ctx context.Context, userId int) (*entity.User, error)
}
type UserRoleRepo interface {
UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int) error
}
type Service struct {
userRepo UserRepo
auditRepo AuditRepo
userRoleRepo UserRoleRepo
threshold time.Duration
syncPeriod time.Duration
logger log.Logger
}
func NewInactiveBlocker(
userRepo UserRepo,
auditRepo AuditRepo,
userRoleRepo UserRoleRepo,
config conf.BlockInactiveWorker,
logger log.Logger,
) Service {
return Service{
userRepo: userRepo,
auditRepo: auditRepo,
userRoleRepo: userRoleRepo,
threshold: time.Duration(config.DaysThreshold) * 24 * time.Hour,
syncPeriod: time.Minute * time.Duration(config.RunIntervalInMinutes),
logger: logger,
}
}
func (w Service) Handle(ctx context.Context, _ bgjob.Job) handler.Result {
ctx = log.ToContext(ctx, log.String("worker", "inactiveBlocker"))
w.logger.Debug(ctx, "begin work")
err := w.do(ctx)
if err != nil {
return handler.Retry(defaultRetryTimeout, errors.WithMessage(err, "sync state with worker"))
}
w.logger.Debug(ctx, "end work")
return handler.Reschedule(handler.ByAfterTime(w.syncPeriod, time.Now()))
}
func (w Service) do(ctx context.Context) error {
lastAccess, err := w.userRepo.LastAccessNotBlockedUsers(ctx)
if err != nil {
return errors.WithMessage(err, "get last access times")
}
now := time.Now().UTC()
for userId, lastAccess := range lastAccess {
dur := now.Sub(lastAccess)
if dur < w.threshold {
continue
}
w.logger.Info(ctx, "block inactive user", log.Int64("userId", userId), log.Any("lastAccessTime", lastAccess))
_, err := w.userRepo.Block(ctx, int(userId))
if err != nil {
return errors.WithMessagef(err, "block user %d", userId)
}
err = w.userRoleRepo.UpsertUserRoleLinks(ctx, int(userId), []int{})
if err != nil {
return errors.WithMessage(err, "empty user roles links")
}
w.auditRepo.SaveAuditAsync(ctx, userId, "Блокировка неактивной УЗ", entity.EventUserChanged)
}
return nil
}