Debian Codegraph @

client.go

raw
1 package proton
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "net"
8 "net/http"
9 "sync"
10 "sync/atomic"
11
12 "github.com/go-resty/resty/v2"
13 )
14
15 // clientID is a unique identifier for a client.
16 var clientID uint64
17
18 // AuthHandler is given any new auths that are returned from the API due to an unexpected auth refresh.
19 type AuthHandler func(Auth)
20
21 // Handler is a generic function that can be registered for a certain event (e.g. deauth, API code).
22 type Handler func()
23
24 // Client is the proton client.
25 type Client struct {
26 m *Manager
27
28 // clientID is this client's unique ID.
29 clientID uint64
30
31 uid string
32 acc string
33 ref string
34 authLock sync.RWMutex
35
36 authHandlers []AuthHandler
37 deauthHandlers []Handler
38 hookLock sync.RWMutex
39
40 deauthOnce sync.Once
41 }
42
43 func newClient(m *Manager, uid string) *Client {
44 c := &Client{
45 m: m,
46 uid: uid,
47 clientID: atomic.AddUint64(&clientID, 1),
48 }
49
50 return c
51 }
52
53 func (c *Client) AddAuthHandler(handler AuthHandler) {
54 c.hookLock.Lock()
55 defer c.hookLock.Unlock()
56
57 c.authHandlers = append(c.authHandlers, handler)
58 }
59
60 func (c *Client) AddDeauthHandler(handler Handler) {
61 c.hookLock.Lock()
62 defer c.hookLock.Unlock()
63
64 c.deauthHandlers = append(c.deauthHandlers, handler)
65 }
66
67 func (c *Client) AddPreRequestHook(hook resty.RequestMiddleware) {
68 c.hookLock.Lock()
69 defer c.hookLock.Unlock()
70
71 c.m.rc.OnBeforeRequest(func(rc *resty.Client, r *resty.Request) error {
72 if clientID, ok := ClientIDFromContext(r.Context()); !ok || clientID != c.clientID {
73 return nil
74 }
75
76 return hook(rc, r)
77 })
78 }
79
80 func (c *Client) AddPostRequestHook(hook resty.ResponseMiddleware) {
81 c.hookLock.Lock()
82 defer c.hookLock.Unlock()
83
84 c.m.rc.OnAfterResponse(func(rc *resty.Client, r *resty.Response) error {
85 if clientID, ok := ClientIDFromContext(r.Request.Context()); !ok || clientID != c.clientID {
86 return nil
87 }
88
89 return hook(rc, r)
90 })
91 }
92
93 func (c *Client) Close() {
94 c.authLock.Lock()
95 defer c.authLock.Unlock()
96
97 c.uid = ""
98 c.acc = ""
99 c.ref = ""
100
101 c.hookLock.Lock()
102 defer c.hookLock.Unlock()
103
104 c.authHandlers = nil
105 c.deauthHandlers = nil
106 }
107
108 func (c *Client) withAuth(acc, ref string) *Client {
109 c.acc = acc
110 c.ref = ref
111
112 return c
113 }
114
115 func (c *Client) do(ctx context.Context, fn func(*resty.Request) (*resty.Response, error)) error {
116 if _, err := c.doRes(ctx, fn); err != nil {
117 return err
118 }
119
120 return nil
121 }
122
123 func (c *Client) doRes(ctx context.Context, fn func(*resty.Request) (*resty.Response, error)) (*resty.Response, error) {
124 c.hookLock.RLock()
125 defer c.hookLock.RUnlock()
126
127 res, err := c.exec(ctx, fn)
128
129 if res != nil {
130 // If we receive no response, we can't do anything.
131 if res.RawResponse == nil {
132 return nil, newNetError(err, "received no response from API")
133 }
134
135 // If we receive a net error, we can't do anything.
136 if resErr, ok := err.(*resty.ResponseError); ok {
137 if netErr := new(net.OpError); errors.As(resErr.Err, &netErr) {
138 return nil, newNetError(netErr, "network error while communicating with API")
139 }
140 }
141
142 // If we receive a 401, we need to refresh the auth.
143 if res.StatusCode() == http.StatusUnauthorized {
144 if err := c.authRefresh(ctx); err != nil {
145 return nil, fmt.Errorf("failed to refresh auth: %w", err)
146 }
147
148 if res, err = c.exec(ctx, fn); err != nil {
149 return nil, fmt.Errorf("failed to retry request: %w", err)
150 }
151 }
152 }
153
154 return res, err
155 }
156
157 func (c *Client) exec(ctx context.Context, fn func(*resty.Request) (*resty.Response, error)) (*resty.Response, error) {
158 c.authLock.RLock()
159 defer c.authLock.RUnlock()
160
161 r := c.m.r(WithClient(ctx, c.clientID))
162
163 if c.uid != "" {
164 r.SetHeader("x-pm-uid", c.uid)
165 }
166
167 if c.acc != "" {
168 r.SetAuthToken(c.acc)
169 }
170
171 return fn(r)
172 }
173
174 func (c *Client) authRefresh(ctx context.Context) error {
175 c.authLock.Lock()
176 defer c.authLock.Unlock()
177
178 c.hookLock.RLock()
179 defer c.hookLock.RUnlock()
180
181 auth, err := c.m.authRefresh(ctx, c.uid, c.ref)
182
183 if err != nil {
184 if respErr, ok := err.(*resty.ResponseError); ok {
185
186 switch respErr.Response.StatusCode() {
187 case http.StatusBadRequest, http.StatusUnprocessableEntity:
188 c.deauthOnce.Do(func() {
189 for _, handler := range c.deauthHandlers {
190 handler()
191 }
192 })
193
194 return fmt.Errorf("failed to refresh auth, de-auth: %w", err)
195 case http.StatusConflict, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusServiceUnavailable:
196 return fmt.Errorf("failed to refresh auth, server issues: %w", err)
197 default:
198 //
199 }
200 }
201
202 return fmt.Errorf("failed to refresh auth: %w", err)
203 }
204
205 c.acc = auth.AccessToken
206 c.ref = auth.RefreshToken
207
208 for _, handler := range c.authHandlers {
209 handler(auth)
210 }
211
212 return nil
213 }