-
Notifications
You must be signed in to change notification settings - Fork 1
/
svloc.go
574 lines (464 loc) · 12.5 KB
/
svloc.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package svloc
import (
"fmt"
"os"
"reflect"
"runtime"
"sync"
"sync/atomic"
)
// Universe represents a global service registry.
//
// Each newFn in a Locator[T] will be called once for each Universe.
// But different Universes can have different values of object created by *newFn* functions.
//
// The order of calls MUST be:
//
// Register* in global => PreventRegistering() => Wrap / Override / MustOverride => Get
//
// It will return errors or panic (with Must* functions) if Locator.Get happens before any of those functions
type Universe struct {
data *universeData
reg *registeredService
prev *Universe // linked list of Universe
}
// universeData is the real global structure
//
// Universe just a local context object
type universeData struct {
stackPrinted atomic.Bool
mut sync.Mutex
svcMap map[any]*registeredService
cleared bool
regList []*registeredService
shutdownFuncs []func() // list of shutdown funcs from earliest to latest
alreadyShutdown bool
}
// NewUniverse creates a new Universe
func NewUniverse() *Universe {
return &Universe{
data: &universeData{
svcMap: map[any]*registeredService{},
},
reg: nil,
prev: nil,
}
}
// CleanUp removes the data for wiring services. Help reduce GC overhead.
//
// After called, all other calls will panic, excepts for Shutdown
func (u *Universe) CleanUp() {
u.data.mut.Lock()
defer u.data.mut.Unlock()
u.data.svcMap = nil
u.data.regList = nil
u.data.cleared = true
}
type getLoc struct {
regType reflect.Type
loc string
}
func (u *Universe) getPrintTypeLocations() []getLoc {
d := u.data
d.mut.Lock()
cloneList := make([]*registeredService, len(d.regList))
copy(cloneList, d.regList)
d.mut.Unlock()
result := make([]getLoc, 0, len(cloneList))
for _, e := range cloneList {
result = append(result, e.getLastOverrideLoc())
}
return result
}
// PrintAllUsedTypes prints all types that have been initialized
func (u *Universe) PrintAllUsedTypes() {
locs := u.getPrintTypeLocations()
printSeparateLine()
for _, loc := range locs {
_, _ = fmt.Fprintf(os.Stderr, "%s %s\n", loc.regType.String(), loc.loc)
}
printSeparateLine()
}
type registeredService struct {
// constant values
loc *locatorData
mut sync.Mutex
onceDone atomic.Bool // similar to sync.Once, but add a mechanism for detecting deadlock
svc any
getCallLocation string
createUnv *Universe
overrideCallLocation string
regType reflect.Type
newFunc func(unv *Universe) any
wrappers []func(unv *Universe, svc any) any
wrapperLocs []string
onShutdown func()
}
func (s *registeredService) newService(unv *Universe) any {
if s.onceDone.Load() {
return s.svc
}
callLoc := getCallerLocationWithSkip(2)
svc := s.newServiceSlow(unv, callLoc)
unv.data.appendShutdownFunc(s)
return svc
}
// callNewFuncAndWrappers already locked
func (s *registeredService) callNewFuncAndWrappers(unv *Universe) {
newFunc := s.loc.newFn
if s.newFunc != nil {
newFunc = s.newFunc
}
newUnv := &Universe{
data: unv.data,
reg: s,
prev: unv,
}
defer func() {
if s.createUnv != nil {
return
}
if !newUnv.data.stackPrinted.Swap(true) {
newUnv.printGetCallTrace("Get calls stacktrace", "")
}
}()
newSvc := newFunc(newUnv)
regType := reflect.TypeOf(newSvc)
for _, wrapper := range s.wrappers {
newSvc = wrapper(newUnv, newSvc)
}
s.svc = newSvc
s.createUnv = newUnv
s.regType = regType
}
func (s *registeredService) newServiceSlow(unv *Universe, callLoc string) any {
ok := s.mut.TryLock()
if !ok {
if unv.detectedCircularDependency(s.loc.key, callLoc) {
panic("svloc: circular dependency detected")
}
s.mut.Lock()
}
defer s.mut.Unlock()
// double-checked locking
if s.onceDone.Load() {
return s.svc
}
s.getCallLocation = callLoc
s.callNewFuncAndWrappers(unv)
s.onceDone.Store(true)
return s.svc
}
func printSeparateLine() {
_, _ = fmt.Fprintln(os.Stderr, "==========================================================")
}
func (u *Universe) printGetCallTrace(problem string, callLoc string) {
printSeparateLine()
_, _ = fmt.Fprintf(os.Stderr, "%s:\n", problem)
if callLoc != "" {
_, _ = fmt.Fprintln(os.Stderr, "\t"+callLoc)
}
for current := u; current != nil; current = current.prev {
reg := current.reg
if reg == nil {
break
}
_, _ = fmt.Fprintln(os.Stderr, "\t"+reg.getCallLocation)
}
printSeparateLine()
}
func (u *Universe) detectedCircularDependency(newKey any, callLoc string) bool {
for currentUnv := u; currentUnv != nil; currentUnv = currentUnv.prev {
reg := currentUnv.reg
if reg == nil {
break
}
if reg.loc.key != newKey {
continue
}
u.data.stackPrinted.Store(true)
u.printGetCallTrace("Get calls stacktrace that causes circular dependency", callLoc)
return true
}
return false
}
func (u *universeData) getService(
locData *locatorData,
methodName string,
) (*registeredService, error) {
u.mut.Lock()
defer u.mut.Unlock()
if u.cleared {
return nil, fmt.Errorf("svloc: can NOT call '%s' after 'CleanUp'", methodName)
}
key := locData.key
svc, existed := u.svcMap[key]
if existed {
return svc, nil
}
svc = ®isteredService{
loc: locData,
}
u.svcMap[key] = svc
return svc, nil
}
func (u *universeData) appendShutdownFunc(s *registeredService) {
u.mut.Lock()
defer u.mut.Unlock()
if u.alreadyShutdown {
panic("svloc: can NOT call 'Get' after 'Shutdown'")
}
u.regList = append(u.regList, s)
fn := s.onShutdown
if fn == nil {
return
}
u.shutdownFuncs = append(u.shutdownFuncs, fn)
}
// Locator is an immutable object and can be called in multiple goroutines
type Locator[T any] struct {
data locatorData
}
type locatorData struct {
key *int
newFn func(unv *Universe) any
registerLoc string
}
// Get can be called multiple times but the newFn inside Register* will be called ONCE.
// It can panic if Universe.Shutdown already called
func (l *Locator[T]) Get(unv *Universe) T {
reg, err := unv.data.getService(&l.data, "Get")
if err != nil {
panic(err.Error())
}
svc := reg.newService(unv)
result, ok := svc.(T)
if !ok {
var empty T
return empty
}
return result
}
// Override the value returned by Get, it also prevents running of the function inside Register
func (l *Locator[T]) Override(unv *Universe, svc T) error {
return l.overrideFuncWithLoc(unv, func(unv *Universe) T {
return svc
}, getCallerLocation())
}
func (l *Locator[T]) doBeforeGet(
unv *Universe,
methodName string,
handler func(reg *registeredService),
) error {
reg, err := unv.data.getService(&l.data, methodName)
if err != nil {
return err
}
reg.mut.Lock()
defer reg.mut.Unlock()
if reg.onceDone.Load() {
reg.createUnv.printGetCallTrace("Get calls stacktrace", "")
return ErrGetAlreadyCalled
}
handler(reg)
return nil
}
// OverrideFunc ...
func (l *Locator[T]) OverrideFunc(unv *Universe, newFn func(unv *Universe) T) error {
return l.overrideFuncWithLoc(unv, newFn, getCallerLocation())
}
func (l *Locator[T]) overrideFuncWithLoc(
unv *Universe, newFn func(unv *Universe) T,
callLoc string,
) error {
if unv.prev != nil {
return errOverrideInsideNewFunctions
}
return l.doBeforeGet(unv, "Override", func(reg *registeredService) {
reg.overrideCallLocation = callLoc
reg.newFunc = func(unv *Universe) any {
return newFn(unv)
}
})
}
func (l *Locator[T]) panicOverrideError(err error) {
var val *T
svcType := reflect.TypeOf(val).Elem()
panic(fmt.Sprintf("Can NOT override service of type '%v', err: %v", svcType, err))
}
// MustOverride will panic if Override returns error
func (l *Locator[T]) MustOverride(unv *Universe, svc T) {
err := l.overrideFuncWithLoc(unv, func(unv *Universe) T {
return svc
}, getCallerLocation())
if err != nil {
l.panicOverrideError(err)
}
}
// MustOverrideFunc similar to OverrideFunc but panics if error returned
func (l *Locator[T]) MustOverrideFunc(unv *Universe, newFn func(unv *Universe) T) {
err := l.overrideFuncWithLoc(unv, newFn, getCallerLocation())
if err != nil {
l.panicOverrideError(err)
}
}
// Wrap the original implementation with the object created by wrapper
func (l *Locator[T]) Wrap(unv *Universe, wrapper func(unv *Universe, svc T) T) (err error) {
return l.wrapWithLoc(unv, wrapper, getCallerLocation())
}
func (l *Locator[T]) wrapWithLoc(
unv *Universe, wrapper func(unv *Universe, svc T) T,
callLoc string,
) (err error) {
return l.doBeforeGet(unv, "Wrap", func(reg *registeredService) {
reg.wrappers = append(reg.wrappers, func(unv *Universe, svc any) any {
return wrapper(unv, svc.(T))
})
reg.wrapperLocs = append(reg.wrapperLocs, callLoc)
})
}
// MustWrap similar to Wrap, but it will panic if not succeeded
func (l *Locator[T]) MustWrap(unv *Universe, wrapper func(unv *Universe, svc T) T) {
err := l.wrapWithLoc(unv, wrapper, getCallerLocation())
if err != nil {
var val *T
str := fmt.Sprintf(
"Failed to Wrap '%v', err: %v",
reflect.TypeOf(val).Elem(),
err,
)
panic(str)
}
}
// GetLastOverrideLocation returns the last location that Override* is called.
// If no Override* functions is called, returns the Register location
func (l *Locator[T]) GetLastOverrideLocation(unv *Universe) (string, error) {
reg, err := unv.data.getService(&l.data, "GetLastOverrideLocation")
if err != nil {
return "", err
}
return reg.getLastOverrideLoc().loc, nil
}
func (s *registeredService) getLastOverrideLoc() getLoc {
s.mut.Lock()
defer s.mut.Unlock()
if s.overrideCallLocation != "" {
return getLoc{
regType: s.regType,
loc: s.overrideCallLocation,
}
}
return getLoc{
regType: s.regType,
loc: s.loc.registerLoc,
}
}
// GetWrapLocations returns Wrap* call's locations
func (l *Locator[T]) GetWrapLocations(unv *Universe) ([]string, error) {
reg, err := unv.data.getService(&l.data, "GetWrapLocations")
if err != nil {
return nil, err
}
reg.mut.Lock()
defer reg.mut.Unlock()
locs := make([]string, len(reg.wrapperLocs))
copy(locs, reg.wrapperLocs)
return locs, nil
}
// OnShutdown must only be called inside 'new' functions.
// It will panic if called outside
func (u *Universe) OnShutdown(fn func()) {
if u.prev == nil {
panic("svloc: can NOT call OnShutdown outside new functions")
}
u.reg.onShutdown = fn
}
func (u *universeData) cloneShutdownFuncList() []func() {
u.mut.Lock()
defer u.mut.Unlock()
if u.alreadyShutdown {
return nil
}
funcList := make([]func(), len(u.shutdownFuncs))
copy(funcList, u.shutdownFuncs)
u.shutdownFuncs = nil
u.alreadyShutdown = true
return funcList
}
// Shutdown call each callback that registered by OnShutdown.
// This function must only be called outside the 'new' functions.
// It will panic if called inside
func (u *Universe) Shutdown() {
if u.prev != nil {
panic("svloc: can NOT call Shutdown inside new functions")
}
funcList := u.data.cloneShutdownFuncList()
for i := len(funcList) - 1; i >= 0; i-- {
fn := funcList[i]
fn()
}
}
var notAllowRegistering atomic.Bool
func checkAllowRegistering() {
if notAllowRegistering.Load() {
panic("Not allow Register* function being called after PreventRegistering")
}
}
func getCallerLocationWithSkip(skip int) string {
_, file, line, _ := runtime.Caller(skip + 1)
return fmt.Sprintf("%s:%d", file, line)
}
func getCallerLocation() string {
_, file, line, _ := runtime.Caller(2)
return fmt.Sprintf("%s:%d", file, line)
}
// Register creates a new Locator allow to call Locator.Get to create a new object
func Register[T any](newFn func(unv *Universe) T) *Locator[T] {
checkAllowRegistering()
key := new(int)
return &Locator[T]{
data: locatorData{
key: key,
newFn: func(unv *Universe) any {
return newFn(unv)
},
registerLoc: getCallerLocation(),
},
}
}
// RegisterSimple creates a new Locator with very simple newFn that returns the zero value
func RegisterSimple[T any]() *Locator[T] {
s := Register[T](func(unv *Universe) T {
var empty T
return empty
})
s.data.registerLoc = getCallerLocation()
return s
}
// RegisterEmpty does not init anything when calling Get, and must be Override
func RegisterEmpty[T any]() *Locator[T] {
checkAllowRegistering()
callLoc := getCallerLocation()
key := new(int)
var val *T
return &Locator[T]{
data: locatorData{
key: key,
newFn: func(unv *Universe) any {
printSeparateLine()
_, _ = fmt.Fprintln(os.Stderr, "'RegisterEmpty' location:", callLoc)
panic(
fmt.Sprintf(
"Not found registered object of type '%v'",
reflect.TypeOf(val).Elem(),
),
)
},
registerLoc: callLoc,
},
}
}
// PreventRegistering prevents Register* functions being called after main() is started
func PreventRegistering() {
notAllowRegistering.Store(true)
}