summaryrefslogtreecommitdiff
path: root/plugins/jobs/brokers/ephemeral/broker.go
blob: 4bbb4095b55f79b51b0e25797a33f6215f9fadc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package ephemeral

import (
	"sync"

	"github.com/google/uuid"
	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/pkg/priorityqueue"
	"github.com/spiral/roadrunner/v2/plugins/jobs/pipeline"
	"github.com/spiral/roadrunner/v2/plugins/jobs/structs"
	"github.com/spiral/roadrunner/v2/utils"
)

type JobBroker struct {
	queues sync.Map
	pq     priorityqueue.Queue
}

func NewJobBroker(q priorityqueue.Queue) (*JobBroker, error) {
	jb := &JobBroker{
		queues: sync.Map{},
		pq:     q,
	}

	return jb, nil
}

func (j *JobBroker) Push(job *structs.Job) (*string, error) {
	const op = errors.Op("ephemeral_push")

	// check if the pipeline registered
	if b, ok := j.queues.Load(job.Options.Pipeline); ok {
		if !b.(bool) {
			return nil, errors.E(op, errors.Errorf("pipeline disabled: %s", job.Options.Pipeline))
		}
		if job.Options.Priority == nil {
			job.Options.Priority = utils.AsUint64Ptr(10)
		}
		job.Options.ID = utils.AsStringPtr(uuid.NewString())

		j.pq.Insert(job)

		return job.Options.ID, nil
	}

	return nil, errors.E(op, errors.Errorf("no such pipeline: %s", job.Options.Pipeline))
}

func (j *JobBroker) Register(pipeline string) error {
	const op = errors.Op("ephemeral_register")
	if _, ok := j.queues.Load(pipeline); ok {
		return errors.E(op, errors.Errorf("queue %s has already been registered", pipeline))
	}

	j.queues.Store(pipeline, true)

	return nil
}

func (j *JobBroker) PushBatch(job *[]structs.Job) (*string, error) {
	// Use a batch response
	// Add JobID to the payload to match responses
	panic("todo")
}

func (j *JobBroker) Stop(pipeline string) {
	if q, ok := j.queues.Load(pipeline); ok {
		if q == true {
			// mark pipeline as turned off
			j.queues.Store(pipeline, false)
		}
	}
}

func (j *JobBroker) StopAll() {
	j.queues.Range(func(key, value interface{}) bool {
		j.queues.Store(key, false)
		return true
	})
}

func (j *JobBroker) Resume(pipeline string) {
	if q, ok := j.queues.Load(pipeline); ok {
		if q == false {
			// mark pipeline as turned off
			j.queues.Store(pipeline, true)
		}
	}
}

func (j *JobBroker) ResumeAll() {
	j.queues.Range(func(key, value interface{}) bool {
		j.queues.Store(key, true)
		return true
	})
}

func (j *JobBroker) Stat() {
	panic("implement me")
}

func (j *JobBroker) Consume(pipe *pipeline.Pipeline) {
	panic("implement me")
}