Stonks/app/src/main/kotlin/xyz/etztech/stonks/App.kt

88 lines
2.8 KiB
Kotlin

package xyz.etztech.stonks
import kotlinx.coroutines.*
import org.h2.tools.Server
import org.jetbrains.exposed.exceptions.ExposedSQLException
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import xyz.etztech.stonks.api.initApiServer
import xyz.etztech.stonks.dsl.Statistics
import xyz.etztech.stonks.statisticsimporter.StatisticsImporter
fun main() =
runBlocking {
println("Starting Stonks...")
val h2StartWebServer = true
val h2tWebServerPort = 8082
val h2TcpServerPort = 9092
val database = initH2Server(h2TcpServerPort, h2StartWebServer, h2tWebServerPort)
val apiServerPort = 7000
initApiServer(apiServerPort, database)
val periodicFetchingInterval = 15 * 60 * 1000L
val statisticsFolder = "../test_data"
initPeriodicFetching(periodicFetchingInterval, statisticsFolder, database)
delay(60 * 1000L)
println("END")
}
fun initH2Server(h2TcpServerPort: Int, h2StartWebServer: Boolean, h2WebServerPort: Int): Database {
val webServer =
Server.createWebServer(
"-trace", "-baseDir", "./databases", "-webPort", h2WebServerPort.toString())
val tcpServer =
Server.createTcpServer(
"-trace", "-baseDir", "./databases", "-webPort", h2TcpServerPort.toString())
if (h2StartWebServer) {
webServer.start()
println("H2 web interface started: ${webServer.getURL()}")
}
tcpServer.start()
println("H2 TCP endpoint started: ${tcpServer.getURL()}")
val database = Database.connect("jdbc:h2:./databases/test", "org.h2.Driver")
Statistics.index(false, Statistics.playerId)
Statistics.index("idx_type_name", false, Statistics.type, Statistics.name)
Statistics.index("idx_timestamp", false, Statistics.timestamp)
Statistics.index("idx_value", false, Statistics.value)
transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(Statistics)
try {
TransactionManager.current()
.exec("CREATE INDEX idx_playerid ON Statistics (\"PlayerId\")")
} catch (e: ExposedSQLException) {}
try {
TransactionManager.current()
.exec("CREATE INDEX idx_type_name ON Statistics (\"Type\", \"Name\")")
} catch (e: ExposedSQLException) {}
}
return database
}
suspend fun initPeriodicFetching(interval: Long, folder: String, db: Database) =
coroutineScope {
launch {
while (true) {
StatisticsImporter.importStatistics(folder, db)
delay(interval)
}
}
}