package taskservice import ( "os" "path" "strconv" "gorm.io/gorm" "code.aides.space/aides-infra/aides-repo-api/internal/models" ) type Config interface { GetUploadDir() string } type Service struct { db *gorm.DB config Config } func New(db *gorm.DB, config Config) *Service { return &Service{ db: db, config: config, } } func (s *Service) onTaskComplete(task *models.Task) error { if err := s.db.Save(&task).Error; err != nil { return err } grart := models.GitRepoAltRepoTask{ ALTRepoID: 1, RepoID: task.RepoID, } s.db. Where(&grart). FirstOrCreate(&grart) grart.LastTaskID = &task.ID if err := s.db.Save(&grart).Error; err != nil { return err } s.tasksCleanup(&grart, 0) return nil } func (s *Service) tasksCleanup(r *models.GitRepoAltRepoTask, n int) { excludedTaskIDs := []uint{} if r.CurrentTaskID != nil { excludedTaskIDs = append(excludedTaskIDs, *r.CurrentTaskID) } if r.LastTaskID != nil { excludedTaskIDs = append(excludedTaskIDs, *r.LastTaskID) } var lastNTaskIDs []uint s.db. Table("tasks"). Select("id"). Where("repo_id = ?", r.ID). Where("status = ?", models.StatusCompleted). Where("id NOT IN ?", excludedTaskIDs). Order("created_at DESC"). Limit(n). Pluck("id", &lastNTaskIDs) excludedTaskIDs = append(excludedTaskIDs, lastNTaskIDs...) var taskIDsToDelete []int s.db. Model(&models.Task{}). Select("id"). Where("repo_id = ?", r.RepoID). Where("files_removed = ?", false). Where("id NOT IN ?", excludedTaskIDs). Pluck("id", &taskIDsToDelete) if len(taskIDsToDelete) > 0 { s.db. Model(&models.Task{}). Where("id IN ?", taskIDsToDelete). Update("files_removed", true) for _, id := range taskIDsToDelete { s.removeTaskFiles(id) } } } func (s *Service) removeTaskFiles(taskId int) { taskFolderPath := path.Join( s.config.GetUploadDir(), "tasks", strconv.Itoa(taskId), ) os.RemoveAll(taskFolderPath) }