This repository has been archived by the owner on Sep 24, 2022. It is now read-only.
forked from carousell/Orion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
62 lines (55 loc) · 1.45 KB
/
factory.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
package helpers
import (
"sync"
"sync/atomic"
"github.com/go-orion/Orion/orion"
)
type svcInfo struct {
refCount int32
svc interface{}
create sync.Once
destroy sync.Once
}
type svcFactory struct {
versions sync.Map
sf orion.ServiceFactoryV2
}
func (s *svcFactory) NewService(svr orion.Server, params orion.FactoryParams) interface{} {
// load or store this version
obj, _ := s.versions.LoadOrStore(params.Version, &svcInfo{})
info, _ := obj.(*svcInfo)
// init this obj if not already inited
info.create.Do(func() {
info.svc = s.sf.NewService(svr, params)
})
// increase object count
atomic.AddInt32(&info.refCount, 1)
return info.svc
}
func (s *svcFactory) DisposeService(svc interface{}, params orion.FactoryParams) {
obj, ok := s.versions.Load(params.Version)
if !ok {
// object is already closed
return
}
info, _ := obj.(*svcInfo)
// decrease object count
currentCount := atomic.AddInt32(&info.refCount, -1)
if currentCount < 1 {
info.destroy.Do(func() {
s.sf.DisposeService(svc, params)
})
s.versions.Delete(params.Version)
}
}
// NewSingleServiceFactory creates a new service factory that manages single instance from
// the given ServiceFactory across versions (NewService/DisposeService gets called once per version)
func NewSingleServiceFactory(sf interface{}) (orion.ServiceFactoryV2, error) {
f, err := orion.ToServiceFactoryV2(sf)
if err != nil {
return nil, err
}
return &svcFactory{
sf: f,
}, nil
}