-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
client.go
427 lines (387 loc) · 10.3 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Package gocent is a Go language client for Centrifugo real-time messaging server HTTP API.
package gocent
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
var (
// ErrMalformedResponse can be returned when server replied with invalid response.
ErrMalformedResponse = errors.New("malformed response returned from server")
// ErrPipeEmpty returned when no commands found in Pipe.
ErrPipeEmpty = errors.New("no commands in pipe")
)
// ErrStatusCode can be returned in case request to server resulted in wrong status code.
type ErrStatusCode struct {
Code int
}
func (e ErrStatusCode) Error() string {
return fmt.Sprintf("wrong status code: %d", e.Code)
}
// Config of client.
type Config struct {
// Addr is Centrifugo API endpoint.
Addr string
// GetAddr when set will be used before every API call to extract
// Centrifugo API endpoint. In this case Addr field of Config will be
// ignored. Nil value means using static Config.Addr field.
GetAddr func() (string, error)
// Key is Centrifugo API key.
Key string
// HTTPClient is a custom HTTP client to be used.
// If nil DefaultHTTPClient will be used.
HTTPClient *http.Client
}
// Client is API client for project registered in server.
type Client struct {
endpoint string
getEndpoint func() (string, error)
apiKey string
httpClient *http.Client
}
// DefaultHTTPClient will be used by default for HTTP requests.
var DefaultHTTPClient = &http.Client{Transport: &http.Transport{
MaxIdleConnsPerHost: 100,
}, Timeout: time.Second}
// New returns initialized client instance based on provided config.
func New(c Config) *Client {
var httpClient *http.Client
if c.HTTPClient != nil {
httpClient = c.HTTPClient
} else {
httpClient = DefaultHTTPClient
}
return &Client{
endpoint: c.Addr,
getEndpoint: c.GetAddr,
apiKey: c.Key,
httpClient: httpClient,
}
}
// SetHTTPClient allows to set custom http Client to use for requests. Not goroutine-safe.
func (c *Client) SetHTTPClient(httpClient *http.Client) {
c.httpClient = httpClient
}
// Pipe allows to create new Pipe to send several commands in one HTTP request.
func (c *Client) Pipe() *Pipe {
return &Pipe{
commands: make([]Command, 0),
}
}
// Publish allows to publish data to channel.
func (c *Client) Publish(ctx context.Context, channel string, data []byte, opts ...PublishOption) (PublishResult, error) {
pipe := c.Pipe()
err := pipe.AddPublish(channel, data, opts...)
if err != nil {
return PublishResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return PublishResult{}, err
}
resp := result[0]
if resp.Error != nil {
return PublishResult{}, resp.Error
}
return decodePublish(resp.Result)
}
// Broadcast allows to broadcast the same data into many channels..
func (c *Client) Broadcast(ctx context.Context, channels []string, data []byte, opts ...PublishOption) (BroadcastResult, error) {
pipe := c.Pipe()
err := pipe.AddBroadcast(channels, data, opts...)
if err != nil {
return BroadcastResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return BroadcastResult{}, err
}
resp := result[0]
if resp.Error != nil {
return BroadcastResult{}, resp.Error
}
return decodeBroadcast(resp.Result)
}
// Subscribe allow subscribing user to a channel (using server-side subscriptions).
func (c *Client) Subscribe(ctx context.Context, channel, user string, opts ...SubscribeOption) error {
pipe := c.Pipe()
err := pipe.AddSubscribe(channel, user, opts...)
if err != nil {
return err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return err
}
resp := result[0]
if resp.Error != nil {
return resp.Error
}
return nil
}
// Unsubscribe allows to unsubscribe user from channel.
func (c *Client) Unsubscribe(ctx context.Context, channel, user string, opts ...UnsubscribeOption) error {
pipe := c.Pipe()
err := pipe.AddUnsubscribe(channel, user, opts...)
if err != nil {
return err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return err
}
resp := result[0]
if resp.Error != nil {
return resp.Error
}
return nil
}
// Disconnect allows to close all connections of user to server.
func (c *Client) Disconnect(ctx context.Context, user string, opts ...DisconnectOption) error {
pipe := c.Pipe()
err := pipe.AddDisconnect(user, opts...)
if err != nil {
return err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return err
}
resp := result[0]
if resp.Error != nil {
return resp.Error
}
return nil
}
// Presence returns channel presence information.
func (c *Client) Presence(ctx context.Context, channel string) (PresenceResult, error) {
pipe := c.Pipe()
err := pipe.AddPresence(channel)
if err != nil {
return PresenceResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return PresenceResult{}, err
}
resp := result[0]
if resp.Error != nil {
return PresenceResult{}, resp.Error
}
return decodePresence(resp.Result)
}
// PresenceStats returns short channel presence information (only counters).
func (c *Client) PresenceStats(ctx context.Context, channel string) (PresenceStatsResult, error) {
pipe := c.Pipe()
err := pipe.AddPresenceStats(channel)
if err != nil {
return PresenceStatsResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return PresenceStatsResult{}, err
}
resp := result[0]
if resp.Error != nil {
return PresenceStatsResult{}, resp.Error
}
return decodePresenceStats(resp.Result)
}
// History returns channel history.
func (c *Client) History(ctx context.Context, channel string, opts ...HistoryOption) (HistoryResult, error) {
pipe := c.Pipe()
err := pipe.AddHistory(channel, opts...)
if err != nil {
return HistoryResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return HistoryResult{}, err
}
resp := result[0]
if resp.Error != nil {
return HistoryResult{}, resp.Error
}
return decodeHistory(resp.Result)
}
// HistoryRemove removes channel history.
func (c *Client) HistoryRemove(ctx context.Context, channel string) error {
pipe := c.Pipe()
err := pipe.AddHistoryRemove(channel)
if err != nil {
return err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return err
}
resp := result[0]
if resp.Error != nil {
return resp.Error
}
return nil
}
// Channels returns information about active channels (with one or more subscribers) on server.
func (c *Client) Channels(ctx context.Context, opts ...ChannelsOption) (ChannelsResult, error) {
pipe := c.Pipe()
err := pipe.AddChannels(opts...)
if err != nil {
return ChannelsResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return ChannelsResult{}, err
}
resp := result[0]
if resp.Error != nil {
return ChannelsResult{}, resp.Error
}
return decodeChannels(resp.Result)
}
// Info returns information about server nodes.
func (c *Client) Info(ctx context.Context) (InfoResult, error) {
pipe := c.Pipe()
err := pipe.AddInfo()
if err != nil {
return InfoResult{}, err
}
result, err := c.SendPipe(ctx, pipe)
if err != nil {
return InfoResult{}, err
}
resp := result[0]
if resp.Error != nil {
return InfoResult{}, resp.Error
}
return decodeInfo(resp.Result)
}
func decodePublish(result []byte) (PublishResult, error) {
var r PublishResult
err := json.Unmarshal(result, &r)
if err != nil {
return PublishResult{}, err
}
return r, nil
}
func decodeBroadcast(result []byte) (BroadcastResult, error) {
var r BroadcastResult
err := json.Unmarshal(result, &r)
if err != nil {
return BroadcastResult{}, err
}
return r, nil
}
// decodeHistory allows to decode history reply result to get a slice of messages.
func decodeHistory(result []byte) (HistoryResult, error) {
var r HistoryResult
err := json.Unmarshal(result, &r)
if err != nil {
return HistoryResult{}, err
}
return r, nil
}
// decodeChannels allows to decode channels command reply result to get a slice of channels.
func decodeChannels(result []byte) (ChannelsResult, error) {
var r ChannelsResult
err := json.Unmarshal(result, &r)
if err != nil {
return ChannelsResult{}, err
}
return r, nil
}
// decodeInfo allows to decode info command response result.
func decodeInfo(result []byte) (InfoResult, error) {
var info InfoResult
err := json.Unmarshal(result, &info)
if err != nil {
return InfoResult{}, err
}
return info, nil
}
// decodePresence allows to decode presence reply result to get a map of clients.
func decodePresence(result []byte) (PresenceResult, error) {
var r PresenceResult
err := json.Unmarshal(result, &r)
if err != nil {
return PresenceResult{}, err
}
return r, nil
}
// decodePresenceStats allows to decode presence stats reply result to get a map of clients.
func decodePresenceStats(result []byte) (PresenceStatsResult, error) {
var r PresenceStatsResult
err := json.Unmarshal(result, &r)
if err != nil {
return PresenceStatsResult{}, err
}
return r, nil
}
// SendPipe sends Commands collected in Pipe to Centrifugo. Using this method you
// should manually inspect all replies.
func (c *Client) SendPipe(ctx context.Context, pipe *Pipe) ([]Reply, error) {
if len(pipe.commands) == 0 {
return nil, ErrPipeEmpty
}
result, err := c.send(ctx, pipe.commands)
if err != nil {
return nil, err
}
if len(result) != len(pipe.commands) {
return nil, ErrMalformedResponse
}
return result, nil
}
func (c *Client) send(ctx context.Context, commands []Command) ([]Reply, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
for _, cmd := range commands {
err := enc.Encode(cmd)
if err != nil {
return nil, err
}
}
var endpoint string
if c.getEndpoint != nil {
e, err := c.getEndpoint()
if err != nil {
return nil, err
}
endpoint = e
} else {
endpoint = c.endpoint
}
req, err := http.NewRequest(http.MethodPost, endpoint, &buf)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
if c.apiKey != "" {
req.Header.Set("Authorization", "apikey "+c.apiKey)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, ErrStatusCode{resp.StatusCode}
}
var replies []Reply
dec := json.NewDecoder(resp.Body)
for {
var rep Reply
if err := dec.Decode(&rep); err == io.EOF {
break
} else if err != nil {
return nil, err
}
replies = append(replies, rep)
}
return replies, err
}