-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
leaderboard_scheduler.go
352 lines (306 loc) · 9.33 KB
/
leaderboard_scheduler.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
// 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 (
"context"
"database/sql"
"sync"
"time"
"go.uber.org/atomic"
"go.uber.org/zap"
)
type LeaderboardScheduler interface {
Start(runtime *Runtime)
Pause()
Resume()
Stop()
Update()
}
type LocalLeaderboardScheduler struct {
sync.Mutex
logger *zap.Logger
db *sql.DB
cache LeaderboardCache
rankCache LeaderboardRankCache
runtime *Runtime
endActiveTimer *time.Timer
expiryTimer *time.Timer
nearEndActiveIds []string
nearExpiryIds []string
active *atomic.Uint32
ctx context.Context
ctxCancelFn context.CancelFunc
}
func NewLocalLeaderboardScheduler(logger *zap.Logger, db *sql.DB, cache LeaderboardCache, rankCache LeaderboardRankCache) LeaderboardScheduler {
ctx, ctxCancelFn := context.WithCancel(context.Background())
return &LocalLeaderboardScheduler{
logger: logger,
db: db,
cache: cache,
rankCache: rankCache,
active: atomic.NewUint32(1),
ctx: ctx,
ctxCancelFn: ctxCancelFn,
}
}
func (ls *LocalLeaderboardScheduler) Start(runtime *Runtime) {
ls.runtime = runtime
ls.Update()
}
func (ls *LocalLeaderboardScheduler) Pause() {
if !ls.active.CAS(1, 0) {
// Already paused.
return
}
ls.Lock()
if ls.endActiveTimer != nil {
if !ls.endActiveTimer.Stop() {
select {
case <-ls.endActiveTimer.C:
default:
}
}
}
if ls.expiryTimer != nil {
if !ls.expiryTimer.Stop() {
select {
case <-ls.expiryTimer.C:
default:
}
}
}
ls.Unlock()
}
func (ls *LocalLeaderboardScheduler) Resume() {
if !ls.active.CAS(0, 1) {
// Already active.
return
}
ls.Update()
}
func (ls *LocalLeaderboardScheduler) Stop() {
ls.Lock()
ls.ctxCancelFn()
if ls.endActiveTimer != nil {
if !ls.endActiveTimer.Stop() {
select {
case <-ls.endActiveTimer.C:
default:
}
}
}
if ls.expiryTimer != nil {
if !ls.expiryTimer.Stop() {
select {
case <-ls.expiryTimer.C:
default:
}
}
}
ls.Unlock()
}
func (ls *LocalLeaderboardScheduler) Update() {
if ls.runtime == nil {
// In case the update is called during runtime VM init, skip setting timers until ready.
return
}
if ls.active.Load() != 1 {
// Not active.
return
}
now := time.Now().UTC()
nowUnix := now.Unix()
// Grab the set of known leaderboards.
leaderboards := ls.cache.GetAllLeaderboards()
earliestEndActive := int64(-1)
earliestExpiry := int64(-1)
endActiveLeaderboardIds := make([]string, 0)
expiryLeaderboardIds := make([]string, 0)
for _, l := range leaderboards {
if l.Duration > 0 {
// Tournament.
_, endActive, expiry := calculateTournamentDeadlines(l.StartTime, l.EndTime, int64(l.Duration), l.ResetSchedule, now)
if l.EndTime > 0 && l.EndTime < nowUnix {
// Tournament has ended permanently.
continue
}
// Check tournament end.
if endActive > 0 && nowUnix < endActive {
if earliestEndActive == -1 || endActive < earliestEndActive {
earliestEndActive = endActive
endActiveLeaderboardIds = []string{l.Id}
} else if endActive == earliestEndActive {
endActiveLeaderboardIds = append(endActiveLeaderboardIds, l.Id)
}
}
// Check tournament expiry.
if expiry > 0 {
if earliestExpiry == -1 || expiry < earliestExpiry {
earliestExpiry = expiry
expiryLeaderboardIds = []string{l.Id}
} else if expiry == earliestExpiry {
expiryLeaderboardIds = append(expiryLeaderboardIds, l.Id)
}
}
} else {
// Leaderboard.
if l.ResetSchedule != nil {
// Leaderboards don't end, only check for expiry.
expiry := l.ResetSchedule.Next(now).UTC().Unix()
if earliestExpiry == -1 || expiry < earliestExpiry {
earliestExpiry = expiry
expiryLeaderboardIds = []string{l.Id}
} else if expiry == earliestExpiry {
expiryLeaderboardIds = append(expiryLeaderboardIds, l.Id)
}
}
}
}
endActiveDuration := time.Duration(-1)
if earliestEndActive > -1 {
endActiveDuration = time.Unix(earliestEndActive, 0).UTC().Sub(now) + time.Second
}
expiryDuration := time.Duration(-1)
if earliestExpiry > -1 {
expiryDuration = time.Unix(earliestExpiry, 0).UTC().Sub(now) + time.Second
}
// Replace IDs earmarked for end and expiry, and restart timers as needed.
ls.Lock()
ls.nearEndActiveIds = endActiveLeaderboardIds
ls.nearExpiryIds = expiryLeaderboardIds
if ls.endActiveTimer != nil {
if !ls.endActiveTimer.Stop() {
select {
case <-ls.endActiveTimer.C:
default:
}
}
}
if ls.expiryTimer != nil {
if !ls.expiryTimer.Stop() {
select {
case <-ls.expiryTimer.C:
default:
}
}
}
if endActiveDuration > -1 {
ls.logger.Debug("Setting timer to run end active function", zap.Duration("end_active", endActiveDuration), zap.Strings("ids", ls.nearEndActiveIds))
ls.endActiveTimer = time.AfterFunc(endActiveDuration, func() {
ls.invokeEndActiveElapse(time.Unix(earliestEndActive-1, 0).UTC())
})
}
if expiryDuration > -1 {
ls.logger.Debug("Setting timer to run expiry function", zap.Duration("expiry", expiryDuration), zap.Strings("ids", ls.nearExpiryIds))
ls.expiryTimer = time.AfterFunc(expiryDuration, func() {
ls.invokeExpiryElapse(time.Unix(earliestExpiry-1, 0).UTC())
})
}
ls.Unlock()
}
func (ls *LocalLeaderboardScheduler) invokeEndActiveElapse(t time.Time) {
if ls.active.Load() != 1 {
// Not active.
return
}
// Skip processing if there is no tournament end callback registered.
fn := ls.runtime.TournamentEnd()
if fn == nil {
return
}
ls.Lock()
ids := ls.nearEndActiveIds
ls.Unlock()
// Immediately schedule the next invocation to avoid any gaps caused by time spent processing below.
ls.Update()
// Process the current set of tournament ends.
for _, id := range ids {
query := `SELECT
id, sort_order, reset_schedule, metadata, create_time,
category, description, duration, end_time, max_size, max_num_score, title, size, start_time
FROM leaderboard
WHERE id = $1`
row := ls.db.QueryRowContext(ls.ctx, query, id)
tournament, err := parseTournament(row, t)
if err != nil {
ls.logger.Error("Error retrieving tournament to invoke end callback", zap.Error(err), zap.String("id", id))
continue
}
// Trigger callback on a goroutine so any extended processing does not block future scheduling.
go func() {
if err := fn(ls.ctx, tournament, int64(tournament.EndActive), int64(tournament.NextReset)); err != nil {
ls.logger.Warn("Failed to invoke tournament end callback", zap.Error(err))
}
}()
}
}
func (ls *LocalLeaderboardScheduler) invokeExpiryElapse(t time.Time) {
if ls.active.Load() != 1 {
// Not active.
return
}
fnLeaderboardReset := ls.runtime.LeaderboardReset()
fnTournamentReset := ls.runtime.TournamentReset()
ls.Lock()
ids := ls.nearExpiryIds
ls.Unlock()
// Immediately schedule the next invocation to avoid any gaps caused by time spent processing below.
ls.rankCache.TrimExpired(t.Unix())
ls.Update()
// Process the current set of leaderboard and tournament resets.
for _, id := range ids {
leaderboardOrTournament := ls.cache.Get(id)
if leaderboardOrTournament.IsTournament() {
// Tournament, fetch most up to date info for size etc.
// Some processing is needed even if there is no runtime callback registered for tournament reset.
query := `SELECT
id, sort_order, reset_schedule, metadata, create_time,
category, description, duration, end_time, max_size, max_num_score, title, size, start_time
FROM leaderboard
WHERE id = $1`
row := ls.db.QueryRowContext(ls.ctx, query, id)
tournament, err := parseTournament(row, t)
if err != nil {
ls.logger.Error("Error retrieving tournament to invoke reset callback", zap.Error(err), zap.String("id", id))
continue
}
// Reset tournament size in DB to make it immediately usable for the next active period.
if _, err := ls.db.ExecContext(ls.ctx, "UPDATE leaderboard SET size = 0 WHERE id = $1", id); err != nil {
ls.logger.Error("Could not reset leaderboard size", zap.Error(err), zap.String("id", id))
}
if fnTournamentReset != nil {
// Trigger callback on a goroutine so any extended processing does not block future scheduling.
go func() {
if err := fnTournamentReset(ls.ctx, tournament, int64(tournament.EndActive), int64(tournament.NextReset)); err != nil {
ls.logger.Warn("Failed to invoke tournament reset callback", zap.Error(err))
}
}()
}
} else {
// Leaderboard.
if fnLeaderboardReset != nil {
nextReset := int64(0)
if leaderboardOrTournament.ResetSchedule != nil {
nextReset = leaderboardOrTournament.ResetSchedule.Next(t).UTC().Unix()
}
// Trigger callback on a goroutine so any extended processing does not block future scheduling.
go func() {
if err := fnLeaderboardReset(ls.ctx, leaderboardOrTournament, nextReset); err != nil {
ls.logger.Warn("Failed to invoke leaderboard reset callback", zap.Error(err))
}
}()
}
}
}
}