/
rest.go
361 lines (303 loc) · 8.79 KB
/
rest.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
package client
import (
"encoding/json"
"net/http"
"strconv"
"sync"
"time"
"github.com/alejzeis/vic2-multi-proxy/common"
"github.com/go-resty/resty/v2"
log "github.com/sirupsen/logrus"
)
type restClient struct {
rest *resty.Client
serverURL string
serverInfo common.InfoResponse
lastCheckin common.CheckinResponse
authToken string
lastRenewedAt time.Time
mutex *sync.Mutex
checkinChannel chan bool
relay GameDataRelay
}
func newRestClient(serverURL string, relay GameDataRelay) *restClient {
client := new(restClient)
client.checkinChannel = make(chan bool, 1) // Buffer channel so we have non-blocking send
client.checkinChannel <- false // Signal checkin goroutine to not attempt doing checkins
go client.continuousCheckin() // Start the checkin goroutine
client.serverURL = serverURL
client.rest = resty.New()
client.mutex = new(sync.Mutex)
client.relay = relay
return client
}
// goroutine that retrieves the latest checkin and renews token when applicable
func (rc *restClient) continuousCheckin() {
ticker := time.NewTicker(1 * time.Second)
sleeping := false
for range ticker.C {
select {
case doCheckin, notClosed := <-rc.checkinChannel:
if !notClosed {
return // We've been told to stop
} else {
sleeping = !doCheckin
}
default:
// Non blocking receive
}
if !sleeping {
rc.mutex.Lock()
success := rc.checkin()
if success {
if rc.lastRenewedAt.Add(30 * time.Second).Before(time.Now()) {
// It's been 30 seconds, time to renew the token
rc.renewToken()
}
} else {
// Something failed, most likely either the server died or our token expired
// Set our state to disconnected then:
rc.completeDisconnect()
}
rc.mutex.Unlock()
}
}
log.Debug("Checkin exited")
}
func (rc *restClient) GetStatus() (bool, common.CheckinResponse) {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if rc.authToken == "" {
return false, common.CheckinResponse{}
}
expireTime := rc.lastRenewedAt.Add(2 * time.Minute)
if time.Now().After(expireTime) {
// Token was expired, we're not connected anymore
rc.checkinChannel <- false // Stop checkins
rc.authToken = ""
return false, common.CheckinResponse{}
}
return true, rc.lastCheckin
}
func (rc *restClient) checkConnectedNoLock() bool {
if rc.authToken == "" {
return false
}
expireTime := rc.lastRenewedAt.Add(2 * time.Minute)
if time.Now().After(expireTime) {
// Token was expired, we're not connected anymore
rc.checkinChannel <- false // Stop checkins
rc.authToken = ""
return false
}
return true
}
// not thread safe, lock the mutex before calling this
func (rc *restClient) renewToken() {
url := rc.serverURL + "/renew/" + rc.authToken
response, err := rc.rest.R().Get(url)
if err != nil {
log.WithField("url", url).WithError(err).Warn("Failed to renew token.")
} else if response.StatusCode() != http.StatusOK {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).Warn("Failed to renew token")
} else {
log.Debug("Renewed token")
rc.authToken = response.String()
rc.lastRenewedAt = time.Now()
}
}
// not thread safe, lock the mutex before calling this
// Attempts to call /checkin on the REST server. Returns if the checkin was successful or not
func (rc *restClient) checkin() bool {
url := rc.serverURL + "/checkin/" + rc.authToken
response, err := rc.rest.R().Get(url)
if err != nil {
log.WithField("url", url).WithError(err).Error("Error while processing checkin (server not responding?)")
return false
} else if response.StatusCode() != http.StatusOK {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).Warn("Unexpected response while processing checkin (did our token expire?)")
return false
} else {
linkedToLobbyPrior := rc.lastCheckin.LinkedLobby > 0
decodeErr := json.Unmarshal(response.Body(), &rc.lastCheckin)
if decodeErr != nil {
log.WithFields(log.Fields{
"url": url,
"body": response.String(),
}).WithError(err).Error("Failed to decode JSON response while processing checkin.")
}
if linkedToLobbyPrior && rc.lastCheckin.LinkedLobby == 0 {
log.Error("Remote Lobby closed.")
rc.relay.OnStopLinked()
}
return true
}
}
func (rc *restClient) Connect(username string) bool {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if rc.checkConnectedNoLock() {
return false
}
url := rc.serverURL + "/login/" + username
response, err := rc.rest.R().Post(url)
if err != nil {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).WithError(err).Error("Failed to login")
return false
} else if response.StatusCode() != http.StatusCreated {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).Error("Failed to login")
return false
} else {
log.Info("Successfully logged into server.")
// Attempt relay connection
if rc.relay.OnConnectedToServer(rc.serverURL, rc.authToken) {
rc.checkinChannel <- true // Signal checkin goroutine to do checkins periodically
rc.authToken = response.String()
rc.lastRenewedAt = time.Now()
} else {
log.Error("Relay failed to connect to server, logging out.")
rc.Logout()
}
return true
}
}
func (rc *restClient) Logout() {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if !rc.checkConnectedNoLock() {
return
}
url := rc.serverURL + "/logout/" + rc.authToken
response, err := rc.rest.R().Get(url)
if err != nil {
log.WithField("url", url).WithError(err).Error("Failed to logout")
} else if response.StatusCode() != http.StatusNoContent {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).Error("Failed to logout")
} else {
log.Info("Successfully logged out of server.")
rc.completeDisconnect()
}
}
// Not thread safe
// TODO: rename to disconnect()
func (rc *restClient) completeDisconnect() {
rc.checkinChannel <- false // Stop periodic checkins
rc.authToken = ""
rc.relay.OnDisconnectedFromServer()
}
func (rc *restClient) Link(lobbyIdStr string) bool {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if !rc.checkConnectedNoLock() {
return false
}
url := rc.serverURL + "/link/" + rc.authToken + "/" + lobbyIdStr
response, err := rc.rest.R().Put(url)
if err != nil || response.StatusCode() != http.StatusNoContent {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
"lobbyId": lobbyIdStr,
}).WithError(err).Error("Failed to link to lobby")
return false
} else {
log.WithFields(log.Fields{
"id": lobbyIdStr,
"name": rc.lastCheckin.Lobbies[lobbyIdStr].Name,
}).Info("Successfully linked to lobby ")
lobbyId, _ := strconv.Atoi(lobbyIdStr)
rc.lastCheckin.LinkedLobby = uint64(lobbyId)
rc.relay.OnBeginLinked()
return true
}
}
func (rc *restClient) Unlink() bool {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if !rc.checkConnectedNoLock() {
return false
}
url := rc.serverURL + "/link/" + rc.authToken + "/0"
response, err := rc.rest.R().Put(url)
if err != nil || response.StatusCode() != http.StatusNoContent {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).WithError(err).Error("Failed to unlink")
return false
} else {
log.Info("Successfully unlinked from lobby")
rc.lastCheckin.LinkedLobby = 0
rc.relay.OnStopLinked()
return true
}
}
func (rc *restClient) Host(lobbyName string, password string) bool {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if !rc.checkConnectedNoLock() {
return false
}
url := rc.serverURL + "/host/" + rc.authToken
response, err := rc.rest.R().SetFormData(map[string]string{
"name": lobbyName,
"password": password,
}).Put(url)
if err != nil || response.StatusCode() != http.StatusNoContent {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).WithError(err).Error("Failed to create lobby")
return false
} else {
log.Info("Successfully created lobby and now hosting")
rc.lastCheckin.Hosting = true
rc.relay.OnBeginHosting()
return true
}
}
func (rc *restClient) StopHost() bool {
rc.mutex.Lock()
defer rc.mutex.Unlock()
if !rc.checkConnectedNoLock() {
return false
}
url := rc.serverURL + "/host/" + rc.authToken
response, err := rc.rest.R().Delete(url)
if err != nil || response.StatusCode() != http.StatusNoContent {
log.WithFields(log.Fields{
"url": url,
"status": response.StatusCode(),
"body": response.Body(),
}).WithError(err).Error("Failed to delete lobby")
return false
} else {
log.Info("Successfully deleted lobby and stopped hosting")
rc.lastCheckin.Hosting = false
rc.relay.OnStopHosting()
return true
}
}