forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleaderboard_rank_cache.go
398 lines (342 loc) · 10.6 KB
/
leaderboard_rank_cache.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
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"database/sql"
"sort"
"sync"
"time"
"github.com/heroiclabs/nakama-common/api"
"github.com/gofrs/uuid"
"go.uber.org/zap"
)
type LeaderboardRankCache interface {
Get(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) int64
Fill(leaderboardId string, expiryUnix int64, records []*api.LeaderboardRecord)
Insert(leaderboardId string, expiryUnix int64, sortOrder int, ownerID uuid.UUID, score, subscore int64) int64
Delete(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) bool
DeleteLeaderboard(leaderboardId string, expiryUnix int64) bool
TrimExpired(nowUnix int64) bool
}
type RankData struct {
OwnerId uuid.UUID
Score int64
Subscore int64
Rank int64
}
type RankMap struct {
sync.RWMutex
Ranks []*RankData
Haystack map[uuid.UUID]*RankData
SortOrder int
}
func (r *RankMap) Len() int {
return len(r.Ranks)
}
func (r *RankMap) Swap(i, j int) {
rank1 := r.Ranks[i]
rank2 := r.Ranks[j]
r.Ranks[i], r.Ranks[j] = rank2, rank1
rank1.Rank, rank2.Rank = rank2.Rank, rank1.Rank
}
func (r *RankMap) Less(i, j int) bool {
rank1 := r.Ranks[i]
rank2 := r.Ranks[j]
if r.SortOrder == LeaderboardSortOrderDescending {
rank1, rank2 = rank2, rank1
}
if rank1.Score < rank2.Score {
return true
} else if rank2.Score < rank1.Score {
return false
}
return rank1.Subscore <= rank2.Subscore
}
type LeaderboardWithExpiry struct {
LeaderboardId string
Expiry int64
}
type LocalLeaderboardRankCache struct {
sync.RWMutex
cache map[LeaderboardWithExpiry]*RankMap
blacklistAll bool
blacklistIds map[string]struct{}
}
func NewLocalLeaderboardRankCache(startupLogger *zap.Logger, db *sql.DB, config *LeaderboardConfig, leaderboardCache LeaderboardCache) LeaderboardRankCache {
cache := &LocalLeaderboardRankCache{
blacklistIds: make(map[string]struct{}, len(config.BlacklistRankCache)),
blacklistAll: len(config.BlacklistRankCache) == 1 && config.BlacklistRankCache[0] == "*",
cache: make(map[LeaderboardWithExpiry]*RankMap, 0),
}
// If caching is disabled completely do not preload any records.
if cache.blacklistAll {
startupLogger.Info("Skipping leaderboard rank cache initialization")
return cache
}
startupLogger.Info("Initializing leaderboard rank cache")
skippedLeaderboards := make([]string, 0)
cachedLeaderboards := make([]string, 0)
nowTime := time.Now().UTC()
leaderboards := leaderboardCache.GetAllLeaderboards()
for _, leaderboard := range leaderboards {
if _, ok := cache.blacklistIds[leaderboard.Id]; ok {
startupLogger.Debug("Skip caching leaderboard ranks", zap.String("leaderboard_id", leaderboard.Id))
skippedLeaderboards = append(skippedLeaderboards, leaderboard.Id)
continue
}
cachedLeaderboards = append(cachedLeaderboards, leaderboard.Id)
startupLogger.Debug("Caching leaderboard ranks", zap.String("leaderboard_id", leaderboard.Id))
// Current expiry for this leaderboard.
// This matches calculateTournamentDeadlines
var expiryUnix int64
if leaderboard.ResetSchedule != nil {
expiryUnix = leaderboard.ResetSchedule.Next(nowTime).UTC().Unix()
if leaderboard.EndTime > 0 && expiryUnix > leaderboard.EndTime {
expiryUnix = leaderboard.EndTime
}
} else {
expiryUnix = leaderboard.EndTime
}
// Prepare structure to receive rank data.
rankEntries := &RankMap{
Ranks: make([]*RankData, 0),
Haystack: make(map[uuid.UUID]*RankData),
SortOrder: leaderboard.SortOrder,
}
key := LeaderboardWithExpiry{LeaderboardId: leaderboard.Id, Expiry: expiryUnix}
cache.cache[key] = rankEntries
// Look up all active records for this leaderboard.
query := `
SELECT owner_id, score, subscore
FROM leaderboard_record
WHERE leaderboard_id = $1 AND expiry_time = $2`
rows, err := db.Query(query, leaderboard.Id, time.Unix(expiryUnix, 0).UTC())
if err != nil {
startupLogger.Fatal("Failed to caching leaderboard ranks", zap.String("leaderboard_id", leaderboard.Id), zap.Error(err))
return nil
}
// Process the records.
for rows.Next() {
var ownerID string
rankData := &RankData{Rank: int64(len(rankEntries.Ranks) + 1)}
if err = rows.Scan(&ownerID, &rankData.Score, &rankData.Subscore); err != nil {
startupLogger.Fatal("Failed to scan leaderboard rank data", zap.String("leaderboard_id", leaderboard.Id), zap.Error(err))
return nil
}
rankData.OwnerId = uuid.Must(uuid.FromString(ownerID))
rankEntries.Ranks = append(rankEntries.Ranks, rankData)
rankEntries.Haystack[rankData.OwnerId] = rankData
}
rows.Close()
}
for k, v := range cache.cache {
startupLogger.Debug("Sorting leaderboard ranks", zap.String("leaderboard_id", k.LeaderboardId), zap.Int("count", len(v.Ranks)))
sort.Sort(v)
}
startupLogger.Info("Leaderboard rank cache initialization completed successfully", zap.Strings("cached", cachedLeaderboards), zap.Strings("skipped", skippedLeaderboards))
return cache
}
func (l *LocalLeaderboardRankCache) Get(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) int64 {
if l.blacklistAll {
// If all rank caching is disabled.
return 0
}
if _, ok := l.blacklistIds[leaderboardId]; ok {
// If rank caching is disabled for this particular leaderboard.
return 0
}
// Find rank map for this leaderboard/expiry pair.
key := LeaderboardWithExpiry{LeaderboardId: leaderboardId, Expiry: expiryUnix}
l.RLock()
rankMap, ok := l.cache[key]
l.RUnlock()
if !ok {
return 0
}
// Find rank data for this owner.
rankMap.RLock()
rankData, ok := rankMap.Haystack[ownerID]
if !ok {
rankMap.RUnlock()
return 0
}
rank := rankData.Rank
rankMap.RUnlock()
return rank
}
func (l *LocalLeaderboardRankCache) Fill(leaderboardId string, expiryUnix int64, records []*api.LeaderboardRecord) {
if l.blacklistAll {
// If all rank caching is disabled.
return
}
if _, ok := l.blacklistIds[leaderboardId]; ok {
// If rank caching is disabled for this particular leaderboard.
return
}
if len(records) == 0 {
// Nothing to do.
return
}
// Find rank map for this leaderboard/expiry pair.
key := LeaderboardWithExpiry{LeaderboardId: leaderboardId, Expiry: expiryUnix}
l.RLock()
rankMap, ok := l.cache[key]
l.RUnlock()
if !ok {
return
}
// Find rank data for each owner.
rankMap.RLock()
for _, record := range records {
rankData, ok := rankMap.Haystack[uuid.Must(uuid.FromString(record.OwnerId))]
if ok {
record.Rank = rankData.Rank
}
}
rankMap.RUnlock()
}
func (l *LocalLeaderboardRankCache) Insert(leaderboardId string, expiryUnix int64, sortOrder int, ownerID uuid.UUID, score, subscore int64) int64 {
if l.blacklistAll {
// If all rank caching is disabled.
return 0
}
if _, ok := l.blacklistIds[leaderboardId]; ok {
// If rank caching is disabled for this particular leaderboard.
return 0
}
// Find the rank map for this leaderboard/expiry pair.
key := LeaderboardWithExpiry{LeaderboardId: leaderboardId, Expiry: expiryUnix}
l.RLock()
rankMap, ok := l.cache[key]
l.RUnlock()
if !ok {
// No existing rank map for this leaderboard/expiry pair, prepare to create a new one.
newRankMap := &RankMap{
Ranks: make([]*RankData, 0),
Haystack: make(map[uuid.UUID]*RankData),
SortOrder: sortOrder,
}
l.Lock()
// Last check if rank map was created by another writer just after last read.
rankMap, ok = l.cache[key]
if !ok {
rankMap = newRankMap
l.cache[key] = rankMap
}
l.Unlock()
}
// Insert or update the score.
rankMap.Lock()
rankData, ok := rankMap.Haystack[ownerID]
if !ok {
rankData = &RankData{
OwnerId: ownerID,
Score: score,
Subscore: subscore,
Rank: int64(len(rankMap.Ranks) + 1),
}
rankMap.Haystack[ownerID] = rankData
rankMap.Ranks = append(rankMap.Ranks, rankData)
} else {
rankData.Score = score
rankData.Subscore = subscore
}
// Re-sort the rank map then check the rank number assigned.
sort.Sort(rankMap)
rank := rankData.Rank
rankMap.Unlock()
return rank
}
func (l *LocalLeaderboardRankCache) Delete(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) bool {
if l.blacklistAll {
// If all rank caching is disabled.
return false
}
if _, ok := l.blacklistIds[leaderboardId]; ok {
// If rank caching is disabled for this particular leaderboard.
return false
}
// Find the rank map for this leaderboard/expiry pair.
key := LeaderboardWithExpiry{LeaderboardId: leaderboardId, Expiry: expiryUnix}
l.RLock()
rankMap, ok := l.cache[key]
l.RUnlock()
if !ok {
// No rank map.
return true
}
// Delete rank data for this owner.
rankMap.Lock()
rankData, ok := rankMap.Haystack[ownerID]
if !ok {
// No rank data.
rankMap.Unlock()
return true
}
delete(rankMap.Haystack, ownerID)
rank := rankData.Rank
totalRanks := len(rankMap.Ranks)
switch {
case rank == 1:
// Dropping the first rank.
rankMap.Ranks = rankMap.Ranks[1:]
case rank == int64(totalRanks):
// Dropping the last rank.
rankMap.Ranks = rankMap.Ranks[:rank-1]
// No need to reshuffle ranks.
rankMap.Unlock()
return true
default:
// Dropping a rank somewhere in the middle.
rankMap.Ranks = append(rankMap.Ranks[:rank-1], rankMap.Ranks[rank:]...)
}
// Shift ranks that were after the deleted record down by one rank number to fill the gap.
for i := int(rank) - 1; i < totalRanks-1; i++ {
rankMap.Ranks[i].Rank--
}
// No need to sort, ranks are still in order.
rankMap.Unlock()
return true
}
func (l *LocalLeaderboardRankCache) DeleteLeaderboard(leaderboardId string, expiryUnix int64) bool {
if l.blacklistAll {
// If all rank caching is disabled.
return false
}
if _, ok := l.blacklistIds[leaderboardId]; ok {
// If rank caching is disabled for this particular leaderboard.
return false
}
// Delete the rank map for this leaderboard/expiry pair.
key := LeaderboardWithExpiry{LeaderboardId: leaderboardId, Expiry: expiryUnix}
l.Lock()
delete(l.cache, key)
l.Unlock()
return true
}
func (l *LocalLeaderboardRankCache) TrimExpired(nowUnix int64) bool {
if l.blacklistAll {
// If all rank caching is disabled.
return false
}
// Used for the timer.
l.Lock()
for k := range l.cache {
if k.Expiry <= nowUnix {
delete(l.cache, k)
}
}
l.Unlock()
return true
}