Debian Codegraph @

internal/job/queue.go

raw symbols SCIP
1 package job
2
3 import (
4 "context"
5 "fmt"
6 "runtime"
7 "sync"
8
9 "github.com/isacikgoz/gitbatch/internal/git"
10 "golang.org/x/sync/semaphore"
11 )
12
13 // Queue holds the slice of Jobs
14 type Queue struct {
15 series []*Job
16 }
17
18 // CreateJobQueue creates a jobqueue struct and initialize its slice then return
19 // its pointer
20 func CreateJobQueue() (jq *Queue) {
21 s := make([]*Job, 0)
22 return &Queue{
23 series: s,
24 }
25 }
26
27 // AddJob adds a job to the queue
28 func (jq *Queue) AddJob(j *Job) error {
29 for _, job := range jq.series {
30 if job.Repository.RepoID == j.Repository.RepoID && job.JobType == j.JobType {
31 return fmt.Errorf("same job already is in the queue")
32 }
33 }
34 jq.series = append(jq.series, nil)
35 copy(jq.series[1:], jq.series[0:])
36 jq.series[0] = j
37 return nil
38 }
39
40 // StartNext starts the next job in the queue
41 func (jq *Queue) StartNext() (j *Job, finished bool, err error) {
42 finished = false
43 if len(jq.series) < 1 {
44 finished = true
45 return nil, finished, nil
46 }
47 i := len(jq.series) - 1
48 lastJob := jq.series[i]
49 jq.series = jq.series[:i]
50 if err = lastJob.start(); err != nil {
51 return lastJob, finished, err
52 }
53 return lastJob, finished, nil
54 }
55
56 // RemoveFromQueue deletes the given entity and its job from the queue
57 // TODO: it is not safe if the job has been started
58 func (jq *Queue) RemoveFromQueue(r *git.Repository) error {
59 removed := false
60 for i, job := range jq.series {
61 if job.Repository.RepoID == r.RepoID {
62 jq.series = append(jq.series[:i], jq.series[i+1:]...)
63 removed = true
64 }
65 }
66 if !removed {
67 return fmt.Errorf("there is no job with given repoID")
68 }
69 return nil
70 }
71
72 // IsInTheQueue function; since the job and entity is not tied with its own
73 // struct, this function returns true if that entity is in the queue along with
74 // the jobs type
75 func (jq *Queue) IsInTheQueue(r *git.Repository) (inTheQueue bool, j *Job) {
76 inTheQueue = false
77 for _, job := range jq.series {
78 if job.Repository.RepoID == r.RepoID {
79 inTheQueue = true
80 j = job
81 }
82 }
83 return inTheQueue, j
84 }
85
86 // StartJobsAsync start he jobs in the queue asynchronously
87 func (jq *Queue) StartJobsAsync() map[*Job]error {
88
89 ctx := context.TODO()
90
91 var (
92 maxWorkers = runtime.GOMAXPROCS(0)
93 sem = semaphore.NewWeighted(int64(maxWorkers))
94 fails = make(map[*Job]error)
95 )
96
97 var mx sync.Mutex
98 for range jq.series {
99
100 if err := sem.Acquire(ctx, 1); err != nil {
101 break
102 }
103
104 go func() {
105
106 defer sem.Release(1)
107 j, _, err := jq.StartNext()
108 if err != nil {
109 mx.Lock()
110 fails[j] = err
111 mx.Unlock()
112 }
113 }()
114 }
115 _ = sem.Acquire(ctx, int64(maxWorkers))
116 return fails
117 }