/
service.go
117 lines (92 loc) · 2.55 KB
/
service.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 bertyaccount
import (
"context"
fmt "fmt"
"sync"
"go.uber.org/zap"
"berty.tech/berty/v2/go/internal/grpcutil"
"berty.tech/berty/v2/go/internal/initutil"
"berty.tech/berty/v2/go/internal/lifecycle"
"berty.tech/berty/v2/go/internal/notification"
)
// Servicex is AccountServiceServer
var _ AccountServiceServer = (*service)(nil)
type Service interface {
AccountServiceServer
// WakeUp should be used for background task or similar task
WakeUp(ctx context.Context) error
// Close the service
Close() error
}
type service struct {
rootCtx context.Context
rootCancel context.CancelFunc
streams map[string]*grpcutil.LazyStream
muStreams sync.RWMutex
notifManager notification.Manager
logger *zap.Logger
rootdir string
muService sync.RWMutex
initManager *initutil.Manager
lifecycleManager *lifecycle.Manager
servicesClient *grpcutil.LazyClient
}
type Options struct {
RootDirectory string
LifecycleManager *lifecycle.Manager
NotificationManager notification.Manager
Logger *zap.Logger
}
func (o *Options) applyDefault() {
if o.Logger == nil {
o.Logger = zap.NewNop()
}
if o.LifecycleManager == nil {
o.LifecycleManager = lifecycle.NewManager(lifecycle.State(0))
}
if o.NotificationManager == nil {
o.NotificationManager = notification.NewLoggerManager(o.Logger)
}
}
func NewService(opts *Options) (Service, error) {
opts.applyDefault()
rootCtx, rootCancelCtx := context.WithCancel(context.Background())
s := &service{
rootdir: opts.RootDirectory,
rootCtx: rootCtx,
rootCancel: rootCancelCtx,
logger: opts.Logger,
lifecycleManager: opts.LifecycleManager,
notifManager: opts.NotificationManager,
streams: make(map[string]*grpcutil.LazyStream),
}
go s.handleLifecycle(rootCtx)
// override grpc logger before manager start to avoid race condition
initutil.ReplaceGRPCLogger(opts.Logger.Named("grpc"))
return s, nil
}
func (s *service) Close() error {
s.muService.Lock()
defer s.muService.Unlock()
s.rootCancel()
if s.initManager != nil {
return s.initManager.Close()
}
return nil
}
func (s *service) getServiceClient() (c *grpcutil.LazyClient, err error) {
s.muService.RLock()
if c = s.servicesClient; c == nil {
err = fmt.Errorf("service client not initialized")
}
s.muService.RUnlock()
return
}
func (s *service) getInitManager() (m *initutil.Manager, err error) {
s.muService.RLock()
if m = s.initManager; m == nil {
err = fmt.Errorf("init manager not initialized")
}
s.muService.RUnlock()
return
}