@@ -7,9 +7,7 @@ import org.eclipse.egit.github.core.service.RepositoryService
7
7
import org.eclipse.egit.github.core.service.UserService
8
8
import org.eclipse.egit.github.core.service.WatcherService
9
9
import org.slf4j.LoggerFactory
10
- import java.io.IOException
11
- import java.util.concurrent.ConcurrentHashMap
12
- import java.util.concurrent.Executors
10
+ import java.util.*
13
11
import java.util.concurrent.TimeUnit
14
12
15
13
object GhService {
@@ -18,11 +16,8 @@ object GhService {
18
16
19
17
private val log = LoggerFactory .getLogger(GhService .javaClass)
20
18
21
- // Allows for parallel iteration and O(1) put/remove
22
- private val clientSessions = ConcurrentHashMap <WsSession , Boolean >()
23
-
24
19
private val tokens = Config .getApiTokens()?.split(" ," ) ? : listOf (" " ) // empty token is limited to 60 requests
25
- private val clients = tokens.map { GitHubClient ().apply { setOAuth2Token(it ) } }
20
+ private val clients = tokens.map { token -> GitHubClient ().apply { setOAuth2Token(token ) } }
26
21
private val repoServices = clients.map { RepositoryService (it) }
27
22
private val commitServices = clients.map { CommitService (it) }
28
23
private val userServices = clients.map { UserService (it) }
@@ -35,15 +30,9 @@ object GhService {
35
30
36
31
val remainingRequests: Int get() = clients.sumBy { it.remainingRequests }
37
32
38
- fun registerClient (ws : WsSession ) = clientSessions.put(ws, true ) == true
39
-
40
- fun unregisterClient (ws : WsSession ) = clientSessions.remove(ws) == true
41
-
42
- init {
43
- Executors .newScheduledThreadPool(2 ).apply {
44
-
45
- // ping clients every other minute to make sure remainingRequests is correct
46
- scheduleAtFixedRate({
33
+ init { // create timer to ping clients every other minute to make sure remainingRequests is correct
34
+ Timer ().scheduleAtFixedRate(object : TimerTask () {
35
+ override fun run () {
47
36
repoServices.forEach {
48
37
try {
49
38
it.getRepository(" tipsy" , " github-profile-summary" )
@@ -52,22 +41,18 @@ object GhService {
52
41
log.info(" Pinged client ${clients.indexOf(it.client)} - was rate-limited" )
53
42
}
54
43
}
55
- }, 0 , 2 , TimeUnit .MINUTES )
56
-
57
- // update all connected clients with remainingRequests twice per second
58
- scheduleAtFixedRate({
59
- val payload = remainingRequests.toString()
60
- clientSessions.forEachKey(1 ) {
61
- try {
62
- if (it.isOpen)
63
- it.send(payload)
64
- } catch (e: IOException ) {
65
- log?.error(e.toString())
66
- }
67
- }
68
- }, 0 , 500 , TimeUnit .MILLISECONDS )
44
+ }
45
+ }, 0 , TimeUnit .MILLISECONDS .convert(2 , TimeUnit .MINUTES ))
46
+ }
69
47
48
+ fun broadcastRemainingRequests (session : WsSession ) = object : TimerTask () {
49
+ override fun run () {
50
+ if (session.isOpen) {
51
+ return session.send(GhService .remainingRequests.toString())
52
+ }
53
+ this .cancel()
70
54
}
71
55
}
72
56
73
57
}
58
+
0 commit comments