-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
service_lazy.go
117 lines (92 loc) · 1.67 KB
/
service_lazy.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
114
115
116
117
package do
import (
"sync"
)
type Provider[T any] func(*Injector) (T, error)
type ServiceLazy[T any] struct {
mu sync.RWMutex
name string
instance T
// lazy loading
built bool
provider Provider[T]
}
func newServiceLazy[T any](name string, provider Provider[T]) Service[T] {
return &ServiceLazy[T]{
name: name,
built: false,
provider: provider,
}
}
//nolint:unused
func (s *ServiceLazy[T]) getName() string {
return s.name
}
//nolint:unused
func (s *ServiceLazy[T]) getInstance(i *Injector) (T, error) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.built {
err := s.build(i)
if err != nil {
return empty[T](), err
}
}
return s.instance, nil
}
//nolint:unused
func (s *ServiceLazy[T]) build(i *Injector) (err error) {
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok {
err = e
} else {
panic(r)
}
}
}()
instance, err := s.provider(i)
if err != nil {
return err
}
s.instance = instance
s.built = true
return nil
}
func (s *ServiceLazy[T]) healthcheck() error {
s.mu.RLock()
defer s.mu.RUnlock()
if !s.built {
return nil
}
instance, ok := any(s.instance).(Healthcheckable)
if ok {
return instance.HealthCheck()
}
return nil
}
func (s *ServiceLazy[T]) shutdown() error {
s.mu.Lock()
defer s.mu.Unlock()
if !s.built {
return nil
}
instance, ok := any(s.instance).(Shutdownable)
if ok {
err := instance.Shutdown()
if err != nil {
return err
}
}
s.built = false
s.instance = empty[T]()
return nil
}
func (s *ServiceLazy[T]) clone() any {
// reset `build` flag and instance
return &ServiceLazy[T]{
name: s.name,
built: false,
provider: s.provider,
}
}