aides-repo-api/internal/services/taskservice/service.go

106 lines
1.9 KiB
Go
Raw Normal View History

2024-12-12 13:27:07 +00:00
package taskservice
import (
"os"
"path"
"strconv"
2024-12-12 13:27:07 +00:00
"code.alt-gnome.ru/aides-infra/aides-repo-api/internal/models"
2024-12-15 06:16:51 +00:00
"gorm.io/gorm"
2024-12-12 13:27:07 +00:00
)
2024-12-15 06:16:51 +00:00
type Config interface {
GetUploadDir() string
}
2024-12-12 13:27:07 +00:00
type Service struct {
2024-12-15 06:16:51 +00:00
db *gorm.DB
config Config
2024-12-12 13:27:07 +00:00
}
2024-12-15 06:16:51 +00:00
func New(db *gorm.DB, config Config) *Service {
return &Service{
2024-12-15 06:16:51 +00:00
db: db,
config: config,
}
2024-12-12 13:27:07 +00:00
}
func (s *Service) onTaskComplete(task *models.Task) error {
2024-12-15 06:16:51 +00:00
if err := s.db.Save(&task).Error; err != nil {
return err
}
grart := models.GitRepoAltRepoTask{
ALTRepoID: 1,
RepoID: task.RepoID,
2024-12-12 13:27:07 +00:00
}
2024-12-15 06:16:51 +00:00
s.db.Debug().
Where(&grart).
FirstOrCreate(&grart)
grart.LastTaskID = &task.ID
2024-12-15 06:16:51 +00:00
if err := s.db.Save(&grart).Error; err != nil {
return err
}
s.tasksCleanup(&grart, 0)
return nil
2024-12-12 13:27:07 +00:00
}
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)
}
2024-12-12 13:27:07 +00:00
var lastNTaskIDs []uint
2024-12-15 06:16:51 +00:00
s.db.
Debug().
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)
2024-12-12 13:27:07 +00:00
excludedTaskIDs = append(excludedTaskIDs, lastNTaskIDs...)
2024-12-12 13:27:07 +00:00
var taskIDsToDelete []int
2024-12-15 06:16:51 +00:00
s.db.
Debug().
Model(&models.Task{}).
Select("id").
Where("repo_id = ?", r.RepoID).
Where("files_removed = ?", false).
Where("id NOT IN ?", excludedTaskIDs).
Pluck("id", &taskIDsToDelete)
2024-12-12 13:27:07 +00:00
if len(taskIDsToDelete) > 0 {
2024-12-15 06:16:51 +00:00
s.db.
Debug().
Model(&models.Task{}).
Where("id IN ?", taskIDsToDelete).
Update("files_removed", true)
2024-12-12 13:27:07 +00:00
for _, id := range taskIDsToDelete {
s.removeTaskFiles(id)
2024-12-12 13:27:07 +00:00
}
}
}
2024-12-12 13:27:07 +00:00
func (s *Service) removeTaskFiles(taskId int) {
taskFolderPath := path.Join(
2024-12-15 06:16:51 +00:00
s.config.GetUploadDir(),
"tasks",
strconv.Itoa(taskId),
)
os.RemoveAll(taskFolderPath)
2024-12-12 13:27:07 +00:00
}