forked from ProtonMail/go-proton-api
-
Notifications
You must be signed in to change notification settings - Fork 4
/
manager.go
140 lines (106 loc) · 2.39 KB
/
manager.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
package proton
import (
"context"
"errors"
"net"
"sync"
"github.com/ProtonMail/gluon/async"
"github.com/go-resty/resty/v2"
)
type Manager struct {
rc *resty.Client
status Status
observers []StatusObserver
statusLock sync.Mutex
errHandlers map[Code][]Handler
verifyProofs bool
panicHandler async.PanicHandler
}
func New(opts ...Option) *Manager {
builder := newManagerBuilder()
for _, opt := range opts {
opt.config(builder)
}
return builder.build()
}
func (m *Manager) AddStatusObserver(observer StatusObserver) {
m.statusLock.Lock()
defer m.statusLock.Unlock()
m.observers = append(m.observers, observer)
}
func (m *Manager) AddPreRequestHook(hook resty.RequestMiddleware) {
m.rc.OnBeforeRequest(hook)
}
func (m *Manager) AddPostRequestHook(hook resty.ResponseMiddleware) {
m.rc.OnAfterResponse(hook)
}
func (m *Manager) AddErrorHandler(code Code, handler Handler) {
m.errHandlers[code] = append(m.errHandlers[code], handler)
}
func (m *Manager) Close() {
m.rc.GetClient().CloseIdleConnections()
}
func (m *Manager) r(ctx context.Context) *resty.Request {
return m.rc.R().SetContext(ctx)
}
func (m *Manager) handleError(req *resty.Request, err error) {
resErr, ok := err.(*resty.ResponseError)
if !ok {
return
}
apiErr, ok := resErr.Response.Error().(*APIError)
if !ok {
return
}
for _, handler := range m.errHandlers[apiErr.Code] {
handler()
}
}
func (m *Manager) checkConnUp(_ *resty.Client, res *resty.Response) error {
m.onConnUp()
return nil
}
func (m *Manager) checkConnDown(req *resty.Request, err error) {
switch {
case errors.Is(err, context.Canceled):
return
}
if res, ok := err.(*resty.ResponseError); ok {
if res.Response.RawResponse == nil {
m.onConnDown()
} else if netErr := new(net.OpError); errors.As(res.Err, &netErr) {
m.onConnDown()
} else {
m.onConnUp()
}
} else {
m.onConnDown()
}
}
func (m *Manager) onConnDown() {
m.statusLock.Lock()
defer m.statusLock.Unlock()
if m.status == StatusDown {
return
}
m.status = StatusDown
for _, observer := range m.observers {
observer(m.status)
}
}
func (m *Manager) onConnUp() {
m.statusLock.Lock()
defer m.statusLock.Unlock()
if m.status == StatusUp {
return
}
m.status = StatusUp
for _, observer := range m.observers {
observer(m.status)
}
}
func (m *Manager) GetStatus() Status {
m.statusLock.Lock()
defer m.statusLock.Unlock()
return m.status
}