-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
injector.go
311 lines (234 loc) · 6.35 KB
/
injector.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package do
import (
"fmt"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
var DefaultInjector = New()
func getInjectorOrDefault(i *Injector) *Injector {
if i != nil {
return i
}
return DefaultInjector
}
func New() *Injector {
return NewWithOpts(&InjectorOpts{})
}
type InjectorOpts struct {
HookAfterRegistration func(injector *Injector, serviceName string)
HookAfterShutdown func(injector *Injector, serviceName string)
Logf func(format string, args ...any)
}
func NewWithOpts(opts *InjectorOpts) *Injector {
logf := opts.Logf
if logf == nil {
logf = func(format string, args ...any) {}
}
logf("injector created")
return &Injector{
mu: sync.RWMutex{},
services: make(map[string]any),
orderedInvocation: map[string]int{},
orderedInvocationIndex: 0,
hookAfterRegistration: opts.HookAfterRegistration,
hookAfterShutdown: opts.HookAfterShutdown,
logf: logf,
}
}
type Injector struct {
mu sync.RWMutex
services map[string]any
// It should be a graph instead of simple ordered list.
orderedInvocation map[string]int // map is faster than slice
orderedInvocationIndex int
hookAfterRegistration func(injector *Injector, serviceName string)
hookAfterShutdown func(injector *Injector, serviceName string)
logf func(format string, args ...any)
}
func (i *Injector) ListProvidedServices() []string {
i.mu.RLock()
names := keys(i.services)
i.mu.RUnlock()
i.logf("exported list of services: %v", names)
return names
}
func (i *Injector) ListInvokedServices() []string {
i.mu.RLock()
names := keys(i.orderedInvocation)
i.mu.RUnlock()
i.logf("exported list of invoked services: %v", names)
return names
}
func (i *Injector) HealthCheck() map[string]error {
i.mu.RLock()
names := keys(i.services)
i.mu.RUnlock()
i.logf("requested healthcheck")
results := map[string]error{}
for _, name := range names {
results[name] = i.healthcheckImplem(name)
}
i.logf("got healthcheck results: %v", results)
return results
}
func (i *Injector) Shutdown() error {
i.mu.RLock()
invocations := invertMap(i.orderedInvocation)
invocationIndex := i.orderedInvocationIndex
i.mu.RUnlock()
i.logf("requested shutdown")
for index := invocationIndex; index >= 0; index-- {
name, ok := invocations[index]
if !ok {
continue
}
err := i.shutdownImplem(name)
if err != nil {
return err
}
}
i.logf("shutdowned services")
return nil
}
// ShutdownOnSIGTERM listens for sigterm signal in order to graceful stop service.
// It will block until receiving a sigterm signal.
func (i *Injector) ShutdownOnSIGTERM() error {
return i.ShutdownOnSignals(syscall.SIGTERM)
}
// ShutdownOnSignals listens for signals defined in signals parameter in order to graceful stop service.
// It will block until receiving any of these signal.
// If no signal is provided in signals parameter, syscall.SIGTERM will be added as default signal.
func (i *Injector) ShutdownOnSignals(signals ...os.Signal) error {
// Make sure there is at least syscall.SIGTERM as a signal
if len(signals) < 1 {
signals = append(signals, syscall.SIGTERM)
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, signals...)
<-ch
signal.Stop(ch)
close(ch)
return i.Shutdown()
}
func (i *Injector) healthcheckImplem(name string) error {
i.mu.Lock()
serviceAny, ok := i.services[name]
if !ok {
i.mu.Unlock()
return fmt.Errorf("DI: could not find service `%s`", name)
}
i.mu.Unlock()
service, ok := serviceAny.(healthcheckableService)
if ok {
i.logf("requested healthcheck for service %s", name)
err := service.healthcheck()
if err != nil {
return err
}
}
return nil
}
func (i *Injector) shutdownImplem(name string) error {
i.mu.Lock()
serviceAny, ok := i.services[name]
if !ok {
i.mu.Unlock()
return fmt.Errorf("DI: could not find service `%s`", name)
}
i.mu.Unlock()
service, ok := serviceAny.(shutdownableService)
if ok {
i.logf("requested shutdown for service %s", name)
err := service.shutdown()
if err != nil {
return err
}
}
i.mu.Lock()
delete(i.services, name)
delete(i.orderedInvocation, name)
i.mu.Unlock()
i.onServiceShutdown(name)
return nil
}
func (i *Injector) exists(name string) bool {
i.mu.RLock()
defer i.mu.RUnlock()
_, ok := i.services[name]
return ok
}
func (i *Injector) get(name string) (any, bool) {
i.mu.RLock()
defer i.mu.RUnlock()
s, ok := i.services[name]
return s, ok
}
func (i *Injector) set(name string, service any) {
i.mu.Lock()
defer i.mu.Unlock()
i.services[name] = service
// defering hook call will unlock mutex
defer i.onServiceRegistration(name)
}
func (i *Injector) remove(name string) {
i.mu.Lock()
defer i.mu.Unlock()
delete(i.services, name)
}
func (i *Injector) forEach(cb func(name string, service any)) {
i.mu.Lock()
defer i.mu.Unlock()
for name, service := range i.services {
cb(name, service)
}
}
func (i *Injector) serviceNotFound(name string) error {
// @TODO: use the Keys+Map functions from `golang.org/x/exp/maps` as
// soon as it is released in stdlib.
servicesNames := keys(i.services)
servicesNames = mAp(servicesNames, func(name string) string {
return fmt.Sprintf("`%s`", name)
})
return fmt.Errorf("DI: could not find service `%s`, available services: %s", name, strings.Join(servicesNames, ", "))
}
func (i *Injector) onServiceInvoke(name string) {
i.mu.Lock()
defer i.mu.Unlock()
if _, ok := i.orderedInvocation[name]; !ok {
i.orderedInvocation[name] = i.orderedInvocationIndex
i.orderedInvocationIndex++
}
}
func (i *Injector) onServiceRegistration(name string) {
if i.hookAfterRegistration != nil {
i.hookAfterRegistration(i, name)
}
}
func (i *Injector) onServiceShutdown(name string) {
if i.hookAfterShutdown != nil {
i.hookAfterShutdown(i, name)
}
}
// Clone clones injector with provided services but not with invoked instances.
func (i *Injector) Clone() *Injector {
return i.CloneWithOpts(&InjectorOpts{})
}
// CloneWithOpts clones injector with provided services but not with invoked instances, with options.
func (i *Injector) CloneWithOpts(opts *InjectorOpts) *Injector {
clone := NewWithOpts(opts)
i.mu.RLock()
defer i.mu.RUnlock()
for name, serviceAny := range i.services {
if service, ok := serviceAny.(cloneableService); ok {
clone.services[name] = service.clone()
} else {
clone.services[name] = service
}
defer clone.onServiceRegistration(name)
}
i.logf("injector cloned")
return clone
}