-
Notifications
You must be signed in to change notification settings - Fork 6
/
manager.go
90 lines (83 loc) · 1.75 KB
/
manager.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Package control 控制插件的启用与优先级等
package control
import (
"os"
"strings"
"sync"
"time"
sql "github.com/FloatTech/sqlite"
)
// Manager 管理
type Manager[CTX any] struct {
sync.RWMutex
M map[string]*Control[CTX]
D sql.Sqlite
banCache map[uint64]bool
blockCache map[int64]bool
}
// NewManager 打开管理数据库
func NewManager[CTX any](dbpath string) (m Manager[CTX]) {
switch {
case dbpath == "":
dbpath = "ctrl.db"
case strings.HasSuffix(dbpath, "/"):
err := os.MkdirAll(dbpath, 0755)
if err != nil {
panic(err)
}
dbpath += "ctrl.db"
default:
i := strings.LastIndex(dbpath, "/")
if i > 0 {
err := os.MkdirAll(dbpath[:i], 0755)
if err != nil {
panic(err)
}
}
}
m = Manager[CTX]{
M: map[string]*Control[CTX]{},
D: sql.New(dbpath),
banCache: make(map[uint64]bool, 8),
blockCache: make(map[int64]bool, 8),
}
err := m.D.Open(time.Hour)
if err != nil {
panic(err)
}
err = m.initBlock()
if err != nil {
panic(err)
}
err = m.initResponse()
if err != nil {
panic(err)
}
return
}
// Lookup returns a Manager by the service name, if
// not exist, it will return nil.
func (manager *Manager[CTX]) Lookup(service string) (*Control[CTX], bool) {
manager.RLock()
m, ok := manager.M[service]
manager.RUnlock()
return m, ok
}
// ForEach iterates through managers.
func (manager *Manager[CTX]) ForEach(iterator func(key string, manager *Control[CTX]) bool) {
manager.RLock()
m := cpmp(manager.M)
manager.RUnlock()
for k, v := range m {
if !iterator(k, v) {
return
}
}
}
func cpmp[CTX any](m map[string]*Control[CTX]) map[string]*Control[CTX] {
ret := make(map[string]*Control[CTX], len(m))
for k, v := range m {
ret[k] = v
}
return ret
}