/
LeaderboardBuffer.scala
233 lines (195 loc) · 7.52 KB
/
LeaderboardBuffer.scala
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
package net.itadinanta.rnkr.engine
import scala.collection.mutable.Map
import akka.util.ByteString
import net.itadinanta.rnkr.backend.Replay
import net.itadinanta.rnkr.core.tree.Ordering
import net.itadinanta.rnkr.core.tree.RankedTreeMap
import net.itadinanta.rnkr.core.tree.Row
import net.itadinanta.rnkr.backend.ReplayMode
import Leaderboard._
import Leaderboard.UpdateMode._
trait LeaderboardBuffer {
def replay(entries: Iterable[Replay]): Iterable[Update]
def append(entries: Iterable[Entry]): Iterable[Update]
def ->[T](cmd: Leaderboard.Command[T]): T
}
trait LeaderboardBufferSupport extends LeaderboardBuffer {
protected def size: Int
protected def isEmpty: Boolean
protected def lookup(entrant: String*): Seq[Entry]
protected def get(score: Long, timestamp: Long): Option[Entry]
protected def at(rank: Long): Option[Entry]
protected def estimatedRank(score: Long): Long
protected def nearby(entrant: String, length: Int): Seq[Entry]
protected def around(score: Long, length: Int): Seq[Entry]
protected def page(start: Long, length: Int): Seq[Entry]
protected def export(): Snapshot
protected def remove(entrant: String): Update
protected def post(post: Post, updateMode: UpdateMode.Value = BestWins): Update
protected def clear(): Update
override final def ->[T](cmd: Leaderboard.Command[T]): T = cmd match {
case Size() => size
case IsEmpty() => isEmpty
case Lookup(entrant @ _*) => lookup(entrant: _*)
case Get(score, timestamp) => get(score, timestamp)
case At(rank) => at(rank)
case EstimatedRank(score) => estimatedRank(score)
case Nearby(entrant, length) => nearby(entrant, length)
case Around(score, length) => around(score, length)
case Page(start, length) => page(start, length)
case Export() => export()
case Remove(entrant) => remove(entrant)
case PostScore(p, updateMode) => post(p, updateMode)
case Clear() => clear()
}
}
object LeaderboardBuffer {
val TIMESTAMP_SCALE = 1000000L
trait Factory {
def build(): LeaderboardBuffer = new LeaderboardTreeImpl()
}
}
protected case class TimedScore(
val score: Long,
val timestamp: Long,
val attachments: Option[Attachments] = None) {
override def hashCode = ((31 * score) + timestamp).intValue
override def equals(o: Any) = o match {
case t: TimedScore => t.score == score && t.timestamp == timestamp
}
}
protected object TimedScoreOrdering extends Ordering[TimedScore] {
override def lt(a: TimedScore, b: TimedScore): Boolean =
a.score < b.score || (a.score == b.score && a.timestamp < b.timestamp)
}
private class LeaderboardTreeImpl extends LeaderboardBufferSupport {
val ordering = TimedScoreOrdering
val scoreIndex = RankedTreeMap[TimedScore, ByteString](ordering)
val entrantIndex = Map[ByteString, TimedScore]()
def asByteString(s: String): ByteString = ByteString(s)
def asString(s: ByteString): String = s.utf8String
private[this] var _lastTime: Long = System.currentTimeMillis
private[this] var _lastCount: Long = 0
override def size = scoreIndex.size
override def isEmpty = scoreIndex.isEmpty
override def lookup(entrants: String*) =
for {
e <- entrants
s <- entrantIndex.get(asByteString(e))
r <- scoreIndex.get(s)
} yield Entry(s.score, s.timestamp, e, r.rank, s.attachments)
override def get(score: Long, timestamp: Long) =
for {
r <- scoreIndex.get(TimedScore(score, timestamp))
s <- entrantIndex.get(r.value)
} yield Entry(score, timestamp, asString(r.value), r.rank, s.attachments)
override def estimatedRank(score: Long): Long =
scoreIndex.rank(TimedScore(score, 0))
protected def better(newScore: TimedScore, oldScore: TimedScore) =
ordering.lt(newScore, oldScore)
override def post(p: Post, updateMode: UpdateMode.Value = BestWins): Update =
post(TimedScore(p.score, timestamp, p.attachments), p.entrant, updateMode)
private[this] def post(newScore: TimedScore, entrant: String, updateMode: UpdateMode.Value): Update = {
import UpdateMode._
val entrantKey = asByteString(entrant)
val (isBetter, oldEntry) = entrantIndex.get(entrantKey) match {
case Some(oldScore) =>
if (updateMode == LastWins || better(newScore, oldScore))
(true, scoreIndex.remove(oldScore) map { o =>
Entry(o.key.score, o.key.timestamp, asString(o.value), o.rank, o.key.attachments)
})
else
(false, scoreIndex.get(oldScore) map { o =>
Entry(o.key.score, o.key.timestamp, asString(o.value), o.rank, o.key.attachments)
})
case None => (true, None)
}
if (isBetter) {
val newRow = scoreIndex.put(newScore, entrantKey)
entrantIndex.put(entrantKey, newScore)
Update(newScore.timestamp,
true,
oldEntry,
Some(Entry(newScore.score, newScore.timestamp, entrant, newRow.rank, newScore.attachments)))
} else {
Update(newScore.timestamp,
false,
oldEntry,
oldEntry)
}
}
override def clear() = {
if (entrantIndex.isEmpty) {
Update(timestamp(), false, None, None)
} else {
entrantIndex.clear()
scoreIndex.clear()
Update(timestamp(), true, None, None)
}
}
override def remove(entrant: String) = {
val entrantKey = asByteString(entrant)
val deleted =
for {
oldScore <- entrantIndex.remove(entrantKey)
o <- scoreIndex.remove(oldScore)
} yield Entry(o.key.score, o.key.timestamp, asString(o.value), o.rank, o.key.attachments)
Update(timestamp(), !deleted.isEmpty, deleted, None)
}
private def updownrange(s: TimedScore, length: Int) =
(scoreIndex.range(s, -length - 1).tail.reverse ++ scoreIndex.range(s, length + 1)) map { r =>
Entry(r.key.score, r.key.timestamp, asString(r.value), r.rank, r.key.attachments)
}
override def nearby(entrant: String, length: Int): Seq[Entry] =
entrantIndex.get(asByteString(entrant)) match {
case Some(s) => updownrange(s, length)
case None => Seq()
}
override def around(score: Long, length: Int): Seq[Entry] =
scoreIndex.range(TimedScore(score, 0), 1).headOption match {
case Some(Row(s, value, rank)) => updownrange(s, length)
case None => Seq()
}
override def at(rank: Long): Option[Entry] = page(rank, 1).headOption
override def toString() =
page(0, 10).toString()
override def page(start: Long, length: Int): Seq[Entry] =
for {
r <- scoreIndex.page(start, length)
s <- entrantIndex.get(r.value)
} yield Entry(s.score, s.timestamp, asString(r.value), r.rank, s.attachments)
override def export() = Snapshot(timestamp(),
for {
((k, value), rank) <- scoreIndex.entries().zipWithIndex
s <- entrantIndex.get(value)
} yield Entry(s.score, s.timestamp, asString(value), rank + 1, s.attachments))
override def replay(entries: Iterable[Replay]): Iterable[Update] = entries map {
_ match {
case Replay(ReplayMode.LastWins, score, timestamp, entrant, attachments) =>
post(TimedScore(score, timestamp, attachments), entrant, UpdateMode.LastWins)
case Replay(ReplayMode.BestWins, score, timestamp, entrant, attachments) =>
post(TimedScore(score, timestamp, attachments), entrant, UpdateMode.BestWins)
case Replay(ReplayMode.Delete, _, _, entrant, _) =>
remove(entrant)
case Replay(ReplayMode.Clear, timestamp, _, _, _) =>
clear()
}
}
override def append(entries: Iterable[Entry]): Iterable[Update] = entries map { e =>
val key = TimedScore(e.score, e.timestamp, e.attachments)
val value = asByteString(e.entrant)
scoreIndex.append(key, value)
entrantIndex.put(value, key)
Update(e.timestamp, true, None, Some(e))
}
private[this] def timestamp(): Long = {
val now = System.currentTimeMillis()
if (now > _lastTime) {
_lastTime = now
_lastCount = 0
} else {
_lastCount += 1
}
_lastTime * LeaderboardBuffer.TIMESTAMP_SCALE + _lastCount
}
}