-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregistry.go
69 lines (59 loc) · 1.43 KB
/
registry.go
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
package workering
import (
"context"
"sync"
)
// WorkerFunction is the main workload function that is executed by a Worker
type WorkerFunction func(ctx context.Context, done chan<- any)
type waiter chan any
// RegisterSet describes a Worker used for registration with Register
type RegisterSet struct {
Name string
Worker WorkerFunction
}
var workers = make(map[string]*Worker)
func init() {
workers = make(map[string]*Worker)
}
// Worker represents a single Worker
type Worker struct {
name string
workerFunction WorkerFunction
status WorkerStatus
ctx *context.Context
cancelFunc *context.CancelFunc
waiters []waiter
stoppedChan chan any
}
var mux sync.RWMutex
// Register registers one or more workers to the registry represented by RegisterSet
func Register(sets ...RegisterSet) {
mux.Lock()
defer mux.Unlock()
for _, set := range sets {
if set.Name == "" {
panic("Worker name must not be empty")
}
if set.Worker == nil {
panic("Worker must not be nil")
}
if _, ok := workers[set.Name]; ok {
panic("Worker already registered")
}
workers[set.Name] = &Worker{
name: set.Name,
workerFunction: set.Worker,
status: Stopped,
waiters: []waiter{},
stoppedChan: make(chan any),
}
}
}
// Get returns a workerFunction by name
func Get(name string) *Worker {
worker, found := workers[name]
if !found {
return nil
}
return worker
}