-
Notifications
You must be signed in to change notification settings - Fork 287
/
SessionStore.kt
73 lines (62 loc) · 2.06 KB
/
SessionStore.kt
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
package maestro.cli.session
import maestro.cli.db.KeyValueStore
import maestro.cli.device.Platform
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
object SessionStore {
private val keyValueStore by lazy {
KeyValueStore(
dbFile = Paths
.get(System.getProperty("user.home"), ".maestro", "sessions")
.toFile()
.also { it.parentFile.mkdirs() }
)
}
fun heartbeat(sessionId: String, platform: Platform) {
synchronized(keyValueStore) {
keyValueStore.set(
key = key(sessionId, platform),
value = System.currentTimeMillis().toString(),
)
pruneInactiveSessions()
}
}
private fun pruneInactiveSessions() {
keyValueStore.keys()
.forEach { key ->
val lastHeartbeat = keyValueStore.get(key)?.toLongOrNull()
if (lastHeartbeat != null && System.currentTimeMillis() - lastHeartbeat >= TimeUnit.SECONDS.toMillis(21)) {
keyValueStore.delete(key)
}
}
}
fun delete(sessionId: String, platform: Platform) {
synchronized(keyValueStore) {
keyValueStore.delete(
key(sessionId, platform)
)
}
}
fun activeSessions(): List<String> {
synchronized(keyValueStore) {
return keyValueStore
.keys()
.filter { key ->
val lastHeartbeat = keyValueStore.get(key)?.toLongOrNull()
lastHeartbeat != null && System.currentTimeMillis() - lastHeartbeat < TimeUnit.SECONDS.toMillis(21)
}
}
}
fun hasActiveSessions(
sessionId: String,
platform: Platform
): Boolean {
synchronized(keyValueStore) {
return activeSessions()
.any { it != key(sessionId, platform) }
}
}
private fun key(sessionId: String, platform: Platform): String {
return "${platform}_$sessionId"
}
}