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

100 lines
1.9 KiB
Go
Raw Normal View History

2024-12-12 13:27:07 +00:00
package taskservice
import (
2024-12-13 10:52:15 +00:00
"os"
"path"
"strconv"
2024-12-12 13:27:07 +00:00
2024-12-12 20:36:38 +00:00
"code.alt-gnome.ru/aides-infra/aides-repo-api/internal/app"
2024-12-13 10:52:15 +00:00
"code.alt-gnome.ru/aides-infra/aides-repo-api/internal/models"
2024-12-12 13:27:07 +00:00
)
type Service struct {
2024-12-12 20:36:38 +00:00
app *app.App
2024-12-12 13:27:07 +00:00
}
2024-12-12 20:36:38 +00:00
func New(app *app.App) *Service {
2024-12-12 13:27:07 +00:00
return &Service{
2024-12-12 20:36:38 +00:00
app: app,
2024-12-12 13:27:07 +00:00
}
}
2024-12-13 10:52:15 +00:00
func (s *Service) onTaskComplete(task *models.Task) error {
if err := s.app.Db.Save(&task).Error; err != nil {
return err
}
grart := models.GitRepoAltRepoTask{
ALTRepoID: 1,
Repo: task.Repo,
}
s.app.Db.Debug().Where(
&grart,
).FirstOrCreate(&grart)
grart.LastTaskID = task.ID
if err := s.app.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 != 0 {
excludedTaskIDs = append(excludedTaskIDs, r.CurrentTaskID)
}
if r.LastTaskID != 0 {
excludedTaskIDs = append(excludedTaskIDs, r.LastTaskID)
}
var lastNTaskIDs []uint
s.app.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)
excludedTaskIDs = append(excludedTaskIDs, lastNTaskIDs...)
var taskIDsToDelete []int
s.app.Db.
Debug().
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.app.Db.
Debug().
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.app.Config.UploadDir,
"tasks",
strconv.Itoa(taskId),
)
os.RemoveAll(taskFolderPath)
}