summaryrefslogtreecommitdiff
path: root/plugins/jobs/dispatcher/dispatcher.go
blob: e73e7b7488684de9f14d658a7c49d08c99581b5b (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
package dispatcher

import (
	"strings"

	"github.com/spiral/roadrunner/v2/plugins/jobs/structs"
)

var separators = []string{"/", "-", "\\"}

// Dispatcher provides ability to automatically locate the pipeline for the specific job
// and update job options (if none set).
type Dispatcher map[string]*structs.Options

// pre-compile patterns
func initDispatcher(routes map[string]*structs.Options) Dispatcher {
	dispatcher := make(Dispatcher)
	for pattern, opts := range routes {
		pattern = strings.ToLower(pattern)
		pattern = strings.Trim(pattern, "-.*")

		for _, s := range separators {
			pattern = strings.ReplaceAll(pattern, s, ".")
		}

		dispatcher[pattern] = opts
	}

	return dispatcher
}

// Match clarifies target job pipeline and other job options. Can return nil.
func (dispatcher Dispatcher) Match(job *structs.Job) (found *structs.Options) {
	var best = 0

	jobName := strings.ToLower(job.Job)
	for pattern, opts := range dispatcher {
		if strings.HasPrefix(jobName, pattern) && len(pattern) > best {
			found = opts
			best = len(pattern)
		}
	}

	if best == 0 {
		return nil
	}

	return found
}