-
Notifications
You must be signed in to change notification settings - Fork 1
/
construct.go
113 lines (96 loc) · 2.59 KB
/
construct.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package cron
import (
"context"
"log"
"sync"
"syscall"
"github.com/pkg/errors"
"github.com/wfusion/gofusion/common/di"
"github.com/wfusion/gofusion/common/utils"
"github.com/wfusion/gofusion/config"
_ "github.com/wfusion/gofusion/log/customlogger"
)
var (
locker sync.RWMutex
routers map[string]map[string]IRouter
)
func Construct(ctx context.Context, confs map[string]*Conf, opts ...utils.OptionExtender) func() {
opt := utils.ApplyOptions[config.InitOption](opts...)
optU := utils.ApplyOptions[useOption](opts...)
if opt.AppName == "" {
opt.AppName = optU.appName
}
for name, conf := range confs {
addInstance(ctx, name, conf, opt)
}
return func() {
locker.Lock()
defer locker.Unlock()
pid := syscall.Getpid()
app := config.Use(opt.AppName).AppName()
if routers != nil {
for name, router := range routers[opt.AppName] {
log.Printf("%v [Gofusion] %s %s %s exiting...", pid, app, config.ComponentCron, name)
if err := router.shutdown(); err == nil {
log.Printf("%v [Gofusion] %s %s %s exited", pid, app, config.ComponentCron, name)
} else {
log.Printf("%v [Gofusion] %s %s %s exit failed: %s", pid, app, config.ComponentCron, name, err)
}
}
delete(routers, opt.AppName)
}
}
}
func addInstance(ctx context.Context, name string, conf *Conf, opt *config.InitOption) {
var r IRouter
switch conf.Type {
case schedulerTypeAsynq:
r = newAsynq(ctx, opt.AppName, name, conf)
default:
panic(ErrUnsupportedSchedulerType)
}
locker.Lock()
defer locker.Unlock()
if routers == nil {
routers = make(map[string]map[string]IRouter)
}
if routers[opt.AppName] == nil {
routers[opt.AppName] = make(map[string]IRouter)
}
if _, ok := routers[opt.AppName][name]; ok {
panic(errors.Errorf("duplicated cron name: %s", name))
}
routers[opt.AppName][name] = r
// ioc
if opt.DI != nil {
opt.DI.MustProvide(
func() IRouter { return Use(name, AppName(opt.AppName)) },
di.Name(name),
)
}
}
type useOption struct {
appName string
}
func AppName(name string) utils.OptionFunc[useOption] {
return func(o *useOption) {
o.appName = name
}
}
func Use(name string, opts ...utils.OptionExtender) IRouter {
opt := utils.ApplyOptions[useOption](opts...)
locker.RLock()
defer locker.RUnlock()
routers, ok := routers[opt.appName]
if !ok {
panic(errors.Errorf("cron router instance not found for app: %s", opt.appName))
}
router, ok := routers[name]
if !ok {
panic(errors.Errorf("cron router instance not found for name: %s", name))
}
return router
}
func init() {
config.AddComponent(config.ComponentCron, Construct, config.WithFlag(&flagString))
}