This repository has been archived by the owner on Dec 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
registry.go
69 lines (54 loc) · 1.68 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
// Copyright 2020 Talhuang<talhuang1231@gmail.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package watcher
import (
"context"
"errors"
"sync"
"github.com/go-redsync/redsync/v4"
"github.com/robfig/cron/v3"
)
// IWatcher is the interface for watchers.
type IWatcher interface {
Init(ctx context.Context, rs *redsync.Mutex, config interface{}) error
Spec() string
cron.Job
}
var (
registryLock = new(sync.Mutex)
registry = make(map[string]IWatcher)
)
var (
// ErrRegistered will be returned when watcher is already been registered.
ErrRegistered = errors.New("watcher has already been registered")
// ErrConfigUnavailable will be returned when the configuration input is not the expected type.
ErrConfigUnavailable = errors.New("configuration is not available")
)
// Register registers a watcher and save in global variable `registry`.
func Register(name string, watcher IWatcher) {
registryLock.Lock()
defer registryLock.Unlock()
if _, ok := registry[name]; ok {
panic("duplicate watcher entry: " + name)
}
registry[name] = watcher
}
// FindMonitor looks up a watcher in the registry. If not found, nil is returned.
func FindMonitor(name string) IWatcher {
registryLock.Lock()
defer registryLock.Unlock()
return registry[name]
}
// Unregister removes a watcher from the registry. The watcher should have stopped.
func Unregister(name string) {
registryLock.Lock()
defer registryLock.Unlock()
delete(registry, name)
}
// ListWatchers returns registered watchers in map format.
func ListWatchers() map[string]IWatcher {
registryLock.Lock()
defer registryLock.Unlock()
return registry
}