|
| 1 | +import ExposedMode.* |
| 2 | +import com.zaxxer.hikari.HikariConfig |
| 3 | +import com.zaxxer.hikari.HikariDataSource |
| 4 | +import io.ktor.http.* |
| 5 | +import io.ktor.server.application.* |
| 6 | +import io.ktor.server.engine.* |
| 7 | +import io.ktor.server.html.* |
| 8 | +import io.ktor.server.netty.* |
| 9 | +import io.ktor.server.plugins.defaultheaders.* |
| 10 | +import io.ktor.server.response.* |
| 11 | +import io.ktor.server.routing.* |
| 12 | +import kotlinx.coroutines.Dispatchers |
| 13 | +import kotlinx.coroutines.withContext |
| 14 | +import kotlinx.html.* |
| 15 | +import kotlinx.serialization.Serializable |
| 16 | +import kotlinx.serialization.encodeToString |
| 17 | +import kotlinx.serialization.json.Json |
| 18 | +import org.jetbrains.exposed.dao.IntEntity |
| 19 | +import org.jetbrains.exposed.dao.IntEntityClass |
| 20 | +import org.jetbrains.exposed.dao.id.EntityID |
| 21 | +import org.jetbrains.exposed.dao.id.IdTable |
| 22 | +import org.jetbrains.exposed.sql.* |
| 23 | +import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq |
| 24 | +import org.jetbrains.exposed.sql.transactions.transaction |
| 25 | +import java.util.concurrent.ThreadLocalRandom |
| 26 | + |
| 27 | +@Serializable |
| 28 | +data class World(val id: Int, var randomNumber: Int) |
| 29 | + |
| 30 | +@Serializable |
| 31 | +data class Fortune(val id: Int, var message: String) |
| 32 | + |
| 33 | + |
| 34 | +// see "toolset/databases/postgres/create-postgres.sql" |
| 35 | + |
| 36 | +object WorldTable : IdTable<Int>("World") { |
| 37 | + override val id = integer("id").entityId() |
| 38 | + val randomNumber = integer("randomnumber").default(0) // The name is "randomNumber" in "create-postgres.sql". |
| 39 | +} |
| 40 | + |
| 41 | +object FortuneTable : IdTable<Int>("Fortune") { |
| 42 | + override val id = integer("id").entityId() |
| 43 | + val message = varchar("message", 2048) |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | +class WorldDao(id: EntityID<Int>) : IntEntity(id) { |
| 48 | + companion object : IntEntityClass<WorldDao>(WorldTable) |
| 49 | + |
| 50 | + var randomNumber by WorldTable.randomNumber |
| 51 | + fun toWorld() = |
| 52 | + World(id.value, randomNumber) |
| 53 | +} |
| 54 | + |
| 55 | +class FortuneDao(id: EntityID<Int>) : IntEntity(id) { |
| 56 | + companion object : IntEntityClass<FortuneDao>(FortuneTable) |
| 57 | + |
| 58 | + var message by FortuneTable.message |
| 59 | + fun toFortune() = |
| 60 | + Fortune(id.value, message) |
| 61 | +} |
| 62 | + |
| 63 | + |
| 64 | +enum class ExposedMode { |
| 65 | + Dsl, Dao |
| 66 | +} |
| 67 | + |
| 68 | +fun main(args: Array<String>) { |
| 69 | + val exposedMode = valueOf(args.first()) |
| 70 | + embeddedServer(Netty, port = 8080) { module(exposedMode) }.start(wait = true) |
| 71 | +} |
| 72 | + |
| 73 | +fun Application.module(exposedMode: ExposedMode) { |
| 74 | + val dbRows = 10000 |
| 75 | + val poolSize = 48 |
| 76 | + val pool = HikariDataSource(HikariConfig().apply { configurePostgres(poolSize) }) |
| 77 | + Database.connect(pool) |
| 78 | + suspend fun <T> withDatabaseContextAndTransaction(statement: Transaction.() -> T) = |
| 79 | + withContext(Dispatchers.IO) { transaction(statement = statement) } |
| 80 | + |
| 81 | + install(DefaultHeaders) |
| 82 | + |
| 83 | + routing { |
| 84 | + fun selectWorldsWithIdQuery(id: Int) = |
| 85 | + WorldTable.slice(WorldTable.id, WorldTable.randomNumber).select(WorldTable.id eq id) |
| 86 | + |
| 87 | + fun ResultRow.toWorld() = |
| 88 | + World(this[WorldTable.id].value, this[WorldTable.randomNumber]) |
| 89 | + |
| 90 | + fun ResultRow.toFortune() = |
| 91 | + Fortune(this[FortuneTable.id].value, this[FortuneTable.message]) |
| 92 | + |
| 93 | + fun ThreadLocalRandom.nextIntWithinRows() = |
| 94 | + nextInt(dbRows) + 1 |
| 95 | + |
| 96 | + fun selectSingleWorld(random: ThreadLocalRandom): World = |
| 97 | + selectWorldsWithIdQuery(random.nextIntWithinRows()).single().toWorld() |
| 98 | + |
| 99 | + fun selectWorlds(queries: Int, random: ThreadLocalRandom): List<World> = |
| 100 | + List(queries) { selectSingleWorld(random) } |
| 101 | + |
| 102 | + get("/db") { |
| 103 | + val random = ThreadLocalRandom.current() |
| 104 | + val result = withDatabaseContextAndTransaction { |
| 105 | + when (exposedMode) { |
| 106 | + Dsl -> selectSingleWorld(random) |
| 107 | + Dao -> WorldDao[random.nextIntWithinRows()].toWorld() |
| 108 | + } |
| 109 | + } |
| 110 | + call.respondText(Json.encodeToString(result), ContentType.Application.Json) |
| 111 | + } |
| 112 | + |
| 113 | + |
| 114 | + get("/queries") { |
| 115 | + val queries = call.queries() |
| 116 | + val random = ThreadLocalRandom.current() |
| 117 | + |
| 118 | + val result = withDatabaseContextAndTransaction { |
| 119 | + when (exposedMode) { |
| 120 | + Dsl -> selectWorlds(queries, random) |
| 121 | + Dao -> //List(queries) { WorldDao[random.nextIntWithinRows()].toWorld() } |
| 122 | + throw IllegalArgumentException("DAO not supported because it appears to cache results") |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + call.respondText(Json.encodeToString(result), ContentType.Application.Json) |
| 127 | + } |
| 128 | + |
| 129 | + get("/fortunes") { |
| 130 | + val result = withDatabaseContextAndTransaction { |
| 131 | + when (exposedMode) { |
| 132 | + Dsl -> FortuneTable.slice(FortuneTable.id, FortuneTable.message).selectAll() |
| 133 | + .asSequence().map { it.toFortune() } |
| 134 | + |
| 135 | + Dao -> FortuneDao.all().asSequence().map { it.toFortune() } |
| 136 | + }.toMutableList() |
| 137 | + } |
| 138 | + |
| 139 | + result.add(Fortune(0, "Additional fortune added at request time.")) |
| 140 | + result.sortBy { it.message } |
| 141 | + call.respondHtml { |
| 142 | + head { title { +"Fortunes" } } |
| 143 | + body { |
| 144 | + table { |
| 145 | + tr { |
| 146 | + th { +"id" } |
| 147 | + th { +"message" } |
| 148 | + } |
| 149 | + for (fortune in result) { |
| 150 | + tr { |
| 151 | + td { +fortune.id.toString() } |
| 152 | + td { +fortune.message } |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + get("/updates") { |
| 161 | + val queries = call.queries() |
| 162 | + val random = ThreadLocalRandom.current() |
| 163 | + lateinit var result: List<World> |
| 164 | + |
| 165 | + withDatabaseContextAndTransaction { |
| 166 | + when (exposedMode) { |
| 167 | + Dsl -> { |
| 168 | + result = selectWorlds(queries, random) |
| 169 | + result.forEach { it.randomNumber = random.nextInt(dbRows) + 1 } |
| 170 | + result |
| 171 | + // sort the data to avoid data race because all updates are in one transaction |
| 172 | + .sortedBy { it.id } |
| 173 | + .forEach { world -> |
| 174 | + WorldTable.update({ WorldTable.id eq world.id }) { |
| 175 | + it[randomNumber] = world.randomNumber |
| 176 | + } |
| 177 | + /* |
| 178 | + // An alternative approach: commit every change to avoid data race |
| 179 | + commit() |
| 180 | + */ |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + Dao -> /*{ |
| 185 | + val worldDaosAndNewRandomNumbers = |
| 186 | + List(queries) { WorldDao[random.nextIntWithinRows()] to random.nextIntWithinRows() } |
| 187 | + worldDaosAndNewRandomNumbers |
| 188 | + .sortedBy { (worldDao, _) -> worldDao.id.value } |
| 189 | + .forEach { (worldDao, newRandomNumber) -> |
| 190 | + worldDao.randomNumber = newRandomNumber |
| 191 | + } |
| 192 | + result = worldDaosAndNewRandomNumbers.map { (worldDao, _) -> worldDao.toWorld() } |
| 193 | + }*/ |
| 194 | + throw IllegalArgumentException("DAO not supported because it appears to cache results") |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + call.respondText(Json.encodeToString(result), ContentType.Application.Json) |
| 199 | + } |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +fun HikariConfig.configurePostgres(poolSize: Int) { |
| 204 | + jdbcUrl = "jdbc:postgresql://tfb-database/hello_world?useSSL=false" |
| 205 | + driverClassName = org.postgresql.Driver::class.java.name |
| 206 | + |
| 207 | + configureCommon(poolSize) |
| 208 | +} |
| 209 | + |
| 210 | +fun HikariConfig.configureCommon(poolSize: Int) { |
| 211 | + username = "benchmarkdbuser" |
| 212 | + password = "benchmarkdbpass" |
| 213 | + addDataSourceProperty("cacheServerConfiguration", true) |
| 214 | + addDataSourceProperty("cachePrepStmts", "true") |
| 215 | + addDataSourceProperty("useUnbufferedInput", "false") |
| 216 | + addDataSourceProperty("prepStmtCacheSize", "4096") |
| 217 | + addDataSourceProperty("prepStmtCacheSqlLimit", "2048") |
| 218 | + connectionTimeout = 10000 |
| 219 | + maximumPoolSize = poolSize |
| 220 | + minimumIdle = poolSize |
| 221 | +} |
| 222 | + |
| 223 | +fun ApplicationCall.queries() = |
| 224 | + request.queryParameters["queries"]?.toIntOrNull()?.coerceIn(1, 500) ?: 1 |
0 commit comments