-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
292 lines (236 loc) · 6.48 KB
/
client.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
// Copyright (c) Omlox Client Go Contributors
// SPDX-License-Identifier: MIT
package omlox
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"golang.org/x/sync/errgroup"
"nhooyr.io/websocket"
)
// Client manages communication with Omlox™ Hub client.
type Client struct {
mu sync.RWMutex
// the configuration object is immutable after the client has been initialized
configuration ClientConfiguration
baseAddress *url.URL
client *http.Client
Trackables TrackablesAPI
Providers ProvidersAPI
// websockets client fields
errg *errgroup.Group
cancel context.CancelFunc
// websockets connection
conn *websocket.Conn
closed bool
// subscriptions
subs map[int]*Subcription
// pending subscription awaiting for subscription ID from the server
// can only be one subscription per client awaiting for subscription.
pending chan chan struct {
sid int
err error
}
}
// New returns a new client decorated with the given configuration options
func New(addr string, options ...ClientOption) (*Client, error) {
configuration := DefaultConfiguration()
for _, opt := range options {
if opt != nil {
if err := opt(&configuration); err != nil {
return nil, err
}
}
}
return newClient(addr, configuration)
}
// newClient returns a new Omlox™ Hub client with a copy of the given configuration
func newClient(addr string, configuration ClientConfiguration) (*Client, error) {
address, err := url.Parse(addr)
if err != nil {
return nil, err
}
c := Client{
configuration: configuration,
// configured or default HTTP client
client: configuration.HTTPClient,
baseAddress: address,
closed: true,
pending: make(chan chan struct {
sid int
err error
}, 1),
subs: make(map[int]*Subcription),
}
c.Trackables = TrackablesAPI{
client: &c,
}
c.Providers = ProvidersAPI{
client: &c,
}
return &c, nil
}
// sendStructuredRequestParseResponse constructs a structured request, sends it, and parses the response
func sendStructuredRequestParseResponse[ResponseT any](
ctx context.Context,
client *Client,
method string,
path string,
body any,
parameters url.Values,
headers http.Header,
) (*ResponseT, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(body); err != nil {
return nil, fmt.Errorf("could not encode request body: %w", err)
}
return sendRequestParseResponse[ResponseT](
ctx,
client,
method,
path,
&buf,
parameters,
headers,
)
}
// sendRequestParseResponse constructs a request, sends it, and parses the response.
func sendRequestParseResponse[ResponseT any](
ctx context.Context,
client *Client,
method string,
path string,
body io.Reader,
parameters url.Values,
headers http.Header,
) (*ResponseT, error) {
// apply the client-level request timeout, if set
if client.configuration.RequestTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, client.configuration.RequestTimeout)
defer cancel()
}
// TODO: set User-Agent and Content-Type headers
req, err := client.newRequest(ctx, method, path, body, parameters, headers)
if err != nil {
return nil, err
}
resp, err := client.send(ctx, req)
if err != nil || resp == nil {
return nil, err
}
defer resp.Body.Close()
if err := isResponseError(resp); err != nil {
return nil, err
}
return parseResponse[ResponseT](resp.Body)
}
// sendRequestParseResponse constructs a request, sends it, and parses the response.
func sendRequestParseResponseList[ResponseT any](
ctx context.Context,
client *Client,
method string,
path string,
body io.Reader,
parameters url.Values,
headers http.Header,
) ([]ResponseT, error) {
// apply the client-level request timeout, if set
if client.configuration.RequestTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, client.configuration.RequestTimeout)
defer cancel()
}
// TODO: set User-Agent and Content-Type headers
req, err := client.newRequest(ctx, method, path, body, parameters, headers)
if err != nil {
return nil, err
}
resp, err := client.send(ctx, req)
if err != nil || resp == nil {
return nil, err
}
defer resp.Body.Close()
if err := isResponseError(resp); err != nil {
return nil, err
}
return parseResponseList[ResponseT](resp.Body)
}
// newRequest constructs a new request.
func (c *Client) newRequest(
ctx context.Context,
method string,
path string,
body io.Reader,
parameters url.Values,
headers http.Header,
) (*http.Request, error) {
// concatenate the base address with the given path
url := c.baseAddress.JoinPath(path)
// add query parameters (if any)
if len(parameters) != 0 {
url.RawQuery = parameters.Encode()
}
req, err := http.NewRequestWithContext(ctx, method, url.String(), body)
if err != nil {
return nil, fmt.Errorf("could not create '%s %s' request: %w", method, url.String(), err)
}
// populate request headers
if headers != nil {
req.Header = headers
}
return req, nil
}
// send sends the given request to Omlox.
func (c *Client) send(ctx context.Context, req *http.Request) (*http.Response, error) {
// block on the rate limiter, if set
if c.configuration.RateLimiter != nil {
c.configuration.RateLimiter.Wait(ctx)
}
return c.client.Do(req)
}
// parseResponse fully consumes the given response body without closing it and
// parses the data into a generic Response[T] structure. If the response body
// is empty, a nil value will be returned.
func parseResponse[T any](responseBody io.Reader) (*T, error) {
// First, read the data into a buffer. This is not super efficient but we
// want to know if we actually have a body or not.
var buf bytes.Buffer
_, err := buf.ReadFrom(responseBody)
if err != nil {
return nil, err
}
if buf.Len() == 0 {
return nil, nil
}
var response T
if err := json.Unmarshal(buf.Bytes(), &response); err != nil {
return nil, err
}
return &response, nil
}
// parseResponseList fully consumes the given response body without closing it and
// parses the data into a generic T structure list. If the response body
// is empty, a empty T list will be returned.
func parseResponseList[T any](responseBody io.Reader) ([]T, error) {
// First, read the data into a buffer. This is not super efficient but we
// want to know if we actually have a body or not.
var buf bytes.Buffer
_, err := buf.ReadFrom(responseBody)
if err != nil {
return nil, err
}
if buf.Len() == 0 {
return nil, nil
}
var response []T
if err := json.Unmarshal(buf.Bytes(), &response); err != nil {
return nil, err
}
return response, nil
}