-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
319 lines (280 loc) · 7.41 KB
/
Copy pathclient.go
File metadata and controls
319 lines (280 loc) · 7.41 KB
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
package nerimity
import (
"context"
"encoding/json"
"math"
"math/rand"
"net/http"
"sync"
"time"
)
// Default endpoints and cache sizes.
const (
defaultAPIURL = "https://nerimity.com"
defaultWSURL = "https://nerimity.com"
defaultMessageCacheLimit = 1000
)
// Socket.IO event names sent by the client to the gateway.
const (
eventAuthenticate = "user:authenticate"
eventUpdateActivity = "user:update_activity"
)
// Options configures a Client. The zero value is valid and uses Nerimity's
// production endpoints with a 1000-message cache.
type Options struct {
// WSURLOverride overrides the gateway (WebSocket) base URL. Defaults to
// https://nerimity.com.
WSURLOverride string
// APIURLOverride overrides the REST API base URL. Defaults to
// https://nerimity.com.
APIURLOverride string
// MessageCacheLimit caps the number of cached messages (LRU). Defaults to
// 1000. Set to -1 for unbounded.
MessageCacheLimit int
// HTTPClient is used for all REST and CDN requests. Defaults to a client
// with a 30-second timeout.
HTTPClient *http.Client
}
// Client is a connection to Nerimity. Register event handlers with the On*
// methods, then call Login to connect. A Client must not be copied.
type Client struct {
apiBase string
wsURL string
httpClient *http.Client
token string
reconnect bool
users *userStore
servers *serverStore
channels *channelStore
messages *messageStore
handlers *eventHandlers
mu sync.RWMutex
user *ClientUser
sock *socket
cancel context.CancelFunc
inbound chan incomingEvent
}
type incomingEvent struct {
name string
payload json.RawMessage
}
// New creates a Client with the given options.
func New(opts Options) *Client {
apiURL := opts.APIURLOverride
if apiURL == "" {
apiURL = defaultAPIURL
}
wsURL := opts.WSURLOverride
if wsURL == "" {
wsURL = defaultWSURL
}
limit := opts.MessageCacheLimit
switch {
case limit == 0:
limit = defaultMessageCacheLimit
case limit < 0:
limit = 0 // unbounded
}
httpClient := opts.HTTPClient
if httpClient == nil {
httpClient = &http.Client{Timeout: 30 * time.Second}
}
c := &Client{
apiBase: apiURL + "/api",
wsURL: wsURL,
httpClient: httpClient,
reconnect: true,
handlers: &eventHandlers{},
inbound: make(chan incomingEvent, 128),
}
c.users = &userStore{cache: newCache[*User](0), client: c}
c.servers = &serverStore{cache: newCache[*Server](0), client: c}
c.channels = &channelStore{cache: newCache[*Channel](0), client: c}
c.messages = &messageStore{cache: newCache[*Message](limit), client: c}
return c
}
// User returns the bot's own user. It is nil until the Ready event fires.
func (c *Client) User() *ClientUser {
c.mu.RLock()
defer c.mu.RUnlock()
return c.user
}
func (c *Client) selfID() string {
c.mu.RLock()
defer c.mu.RUnlock()
if c.user != nil {
return c.user.ID
}
return ""
}
// Servers returns a snapshot of the cached servers.
func (c *Client) Servers() []*Server { return c.servers.values() }
// Server returns the cached server with the given ID, or nil.
func (c *Client) Server(id string) *Server { s, _ := c.servers.get(id); return s }
// Channel returns the cached channel with the given ID, or nil.
func (c *Client) Channel(id string) *Channel { ch, _ := c.channels.get(id); return ch }
// GetUser returns the cached user with the given ID, or nil.
func (c *Client) GetUser(id string) *User { u, _ := c.users.get(id); return u }
// SetActivity updates the bot's activity. Pass nil to clear it. Requires an
// active connection.
func (c *Client) SetActivity(activity *Activity) error {
c.mu.RLock()
sock := c.sock
c.mu.RUnlock()
if sock == nil {
return nil
}
if activity == nil {
return sock.emit(eventUpdateActivity, nil)
}
return sock.emit(eventUpdateActivity, activity)
}
// Activity is the bot's rich-presence activity, set with SetActivity.
type Activity struct {
Action string `json:"action"`
Name string `json:"name"`
StartedAt int64 `json:"startedAt"`
EndsAt int64 `json:"endsAt,omitempty"`
ImgSrc string `json:"imgSrc,omitempty"`
Title string `json:"title,omitempty"`
Subtitle string `json:"subtitle,omitempty"`
Link string `json:"link,omitempty"`
}
// Login connects to Nerimity with the given bot token and blocks, dispatching
// events to registered handlers and reconnecting automatically, until Close is
// called or the context is cancelled. It is equivalent to LoginWithContext with
// a background context.
func (c *Client) Login(token string) error {
return c.LoginWithContext(context.Background(), token)
}
// LoginWithContext is Login with a caller-supplied context. When ctx is
// cancelled the connection is torn down and the returned error is ctx.Err().
func (c *Client) LoginWithContext(ctx context.Context, token string) error {
c.token = token
ctx, cancel := context.WithCancel(ctx)
c.mu.Lock()
c.cancel = cancel
c.mu.Unlock()
defer cancel()
go c.dispatchLoop(ctx)
return c.connectLoop(ctx)
}
// Close disconnects the client and causes Login to return.
func (c *Client) Close() {
c.mu.Lock()
if c.cancel != nil {
c.cancel()
}
sock := c.sock
c.mu.Unlock()
if sock != nil {
sock.close()
}
}
func (c *Client) connectLoop(ctx context.Context) error {
attempt := 0
for {
if err := ctx.Err(); err != nil {
return err
}
sock := &socket{}
err := sock.connect(ctx, c.wsURL)
if err == nil {
attempt = 0
c.mu.Lock()
c.sock = sock
c.mu.Unlock()
err = c.runSession(ctx, sock)
}
sock.close()
if err := ctx.Err(); err != nil {
return err
}
if !c.reconnect {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoffDelay(attempt)):
}
attempt++
}
}
// runSession authenticates and pumps gateway events into the inbound channel
// until the connection fails.
func (c *Client) runSession(ctx context.Context, sock *socket) error {
if err := sock.emit(eventAuthenticate, map[string]string{"token": c.token}); err != nil {
return err
}
for {
name, payload, err := sock.read()
if err != nil {
return err
}
select {
case c.inbound <- incomingEvent{name: name, payload: payload}:
case <-ctx.Done():
return ctx.Err()
}
}
}
func (c *Client) dispatchLoop(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case ev := <-c.inbound:
c.handleEvent(ev)
}
}
}
// backoffDelay mirrors socket.io-client's reconnection timing: base 1s,
// doubling, capped at 5s, with +/-50% jitter.
func backoffDelay(attempt int) time.Duration {
const base = float64(time.Second)
const max = float64(5 * time.Second)
d := base * math.Pow(2, float64(attempt))
if d > max {
d = max
}
jitter := d * 0.5 * (rand.Float64()*2 - 1)
return time.Duration(d + jitter)
}
// ---- cache stores ----
type userStore struct {
*cache[*User]
client *Client
}
func (s *userStore) setUser(raw rawUser) *User {
u := newUser(s.client, raw)
s.set(raw.ID, u)
return u
}
type serverStore struct {
*cache[*Server]
client *Client
}
func (s *serverStore) setServer(raw rawServer) *Server {
srv := newServer(s.client, raw)
s.set(raw.ID, srv)
return srv
}
type channelStore struct {
*cache[*Channel]
client *Client
}
func (s *channelStore) setChannel(raw rawChannel) *Channel {
ch := newChannel(s.client, raw)
s.set(raw.ID, ch)
return ch
}
type messageStore struct {
*cache[*Message]
client *Client
}
func (s *messageStore) setMessage(raw rawMessage) *Message {
m := newMessage(s.client, raw)
s.set(raw.ID, m)
return m
}