feat(server): use lazy swappable database

This commit is contained in:
Cilly Leang 2026-04-11 21:59:26 +10:00
parent 959b022cf9
commit 0524eda5d2
Signed by: cilly
GPG key ID: 6500251E087653C9
5 changed files with 49 additions and 62 deletions

View file

@ -135,7 +135,7 @@ class GtfsParser(
.forEach { fd -> .forEach { fd ->
log.info("parsing stop times for ${fd.parent}...") log.info("parsing stop times for ${fd.parent}...")
parseStopTimes(fd, trips) { seq -> parseStopTimes(fd, trips) { seq ->
seq.chunked(10000) seq.chunked(1000000)
.forEach { emit(GtfsData.StopTimeChunk(it)) } .forEach { emit(GtfsData.StopTimeChunk(it)) }
} }
} }

View file

@ -28,7 +28,7 @@ import moe.lava.banksia.core.util.serialise
import moe.lava.banksia.server.di.ServerModules import moe.lava.banksia.server.di.ServerModules
import moe.lava.banksia.server.gtfsrt.GtfsrtService import moe.lava.banksia.server.gtfsrt.GtfsrtService
import org.koin.dsl.module import org.koin.dsl.module
import org.koin.ktor.ext.inject import org.koin.ktor.ext.get
import org.koin.ktor.plugin.Koin import org.koin.ktor.plugin.Koin
import kotlin.time.Clock import kotlin.time.Clock
@ -46,16 +46,14 @@ fun Application.module() {
modules(ServerModules) modules(ServerModules)
} }
val gtfsr by inject<GtfsrtService>()
@Suppress("KotlinConstantConditions") @Suppress("KotlinConstantConditions")
launch { gtfsr.start(this, !Constants.devMode) } launch { get<GtfsrtService>().start(this, !Constants.devMode) }
routing { routing {
if (Constants.devMode) { if (Constants.devMode) {
get("/fixup") { get("/fixup") {
call.respondText("received") call.respondText("received")
val fixer by inject<GtfsDataFixer>() get<GtfsDataFixer>().addParentsToStops()
fixer.addParentsToStops()
} }
} }
get("/update") { get("/update") {
@ -70,16 +68,13 @@ fun Application.module() {
?: "https://opendata.transport.vic.gov.au/dataset/3f4e292e-7f8a-4ffe-831f-1953be0fe448/resource/${datasetUuid}/download/gtfs.zip" ?: "https://opendata.transport.vic.gov.au/dataset/3f4e292e-7f8a-4ffe-831f-1953be0fe448/resource/${datasetUuid}/download/gtfs.zip"
call.respondText("received") call.respondText("received")
launch(context = Dispatchers.IO) { launch(context = Dispatchers.IO) {
val fixer by inject<GtfsDataFixer>() get<GtfsImporter>().import(datasetUrl)
val importer by inject<GtfsImporter>() get<GtfsDataFixer>().addParentsToStops()
importer.import(datasetUrl)
fixer.addParentsToStops()
} }
} }
get("/metadata/{type?}") { get("/metadata/{type?}") {
val dao by inject<VersionMetadataDao>() val dao = get<VersionMetadataDao>()
val type = call.parameters["type"] val type = call.parameters["type"]
if (type == null) { if (type == null) {
call.respond(dao.getAll().map { it.asModel() }) call.respond(dao.getAll().map { it.asModel() })
@ -96,7 +91,7 @@ fun Application.module() {
get("/routes") { get("/routes") {
val routes = withContext(context = Dispatchers.IO) { val routes = withContext(context = Dispatchers.IO) {
inject<RouteDao>().value.getAll() get<RouteDao>().getAll()
} }
val res = routes.map { it.asModel() } val res = routes.map { it.asModel() }
call.respond(res) call.respond(res)
@ -104,7 +99,7 @@ fun Application.module() {
get("/routes/{route_id}") { get("/routes/{route_id}") {
val routeId = call.parameters["route_id"]!! val routeId = call.parameters["route_id"]!!
val route = withContext(context = Dispatchers.IO) { val route = withContext(context = Dispatchers.IO) {
inject<RouteDao>().value.get(routeId) get<RouteDao>().get(routeId)
} }
if (route != null) if (route != null)
call.respond(route.asModel()) call.respond(route.asModel())
@ -113,7 +108,7 @@ fun Application.module() {
} }
get("/stops") { get("/stops") {
val routes = withContext(context = Dispatchers.IO) { val routes = withContext(context = Dispatchers.IO) {
inject<StopDao>().value.getAll() get<StopDao>().getAll()
} }
val res = routes.map { it.asModel() } val res = routes.map { it.asModel() }
call.respond(res) call.respond(res)
@ -121,7 +116,7 @@ fun Application.module() {
get("/stops/{stop_id}") { get("/stops/{stop_id}") {
val stopId = call.parameters["stop_id"]!! val stopId = call.parameters["stop_id"]!!
val stop = withContext(context = Dispatchers.IO) { val stop = withContext(context = Dispatchers.IO) {
inject<StopDao>().value.get(stopId) get<StopDao>().get(stopId)
} }
if (stop != null) if (stop != null)
call.respond(stop.asModel()) call.respond(stop.asModel())
@ -132,7 +127,7 @@ fun Application.module() {
val routeId = call.parameters["route_id"]!! val routeId = call.parameters["route_id"]!!
val useParent = call.queryParameters["parent"] !in listOf("false", "0") val useParent = call.queryParameters["parent"] !in listOf("false", "0")
val stops = withContext(Dispatchers.IO) { val stops = withContext(Dispatchers.IO) {
val routeDao by inject<RouteDao>() val routeDao = get<RouteDao>()
if (useParent) if (useParent)
routeDao.stopsParent(routeId) routeDao.stopsParent(routeId)
else else
@ -146,7 +141,7 @@ fun Application.module() {
?.let { LocalDate.parse(it, LocalDate.Formats.ISO) } ?.let { LocalDate.parse(it, LocalDate.Formats.ISO) }
?: Clock.System.todayIn(TimeZone.currentSystemDefault()) ?: Clock.System.todayIn(TimeZone.currentSystemDefault())
val times = withContext(context = Dispatchers.IO) { val times = withContext(context = Dispatchers.IO) {
inject<StopTimeDao>().value get<StopTimeDao>()
.getForStopDated( .getForStopDated(
stopId, stopId,
listOf(date.dayOfWeek).serialise(), listOf(date.dayOfWeek).serialise(),

View file

@ -24,7 +24,7 @@ class GtfsDataFixer(
name = name, name = name,
lat = avgLat, lat = avgLat,
lng = avgLng, lng = avgLng,
parent = "", parent = null,
hasWheelChairBoarding = stops.all { it.hasWheelChairBoarding }, hasWheelChairBoarding = stops.all { it.hasWheelChairBoarding },
level = "", level = "",
platformCode = "", platformCode = "",

View file

@ -1,7 +1,5 @@
package moe.lava.banksia.server package moe.lava.banksia.server
import androidx.room.immediateTransaction
import androidx.room.useWriterConnection
import io.ktor.util.logging.Logger import io.ktor.util.logging.Logger
import moe.lava.banksia.core.model.Route import moe.lava.banksia.core.model.Route
import moe.lava.banksia.core.model.Service import moe.lava.banksia.core.model.Service
@ -11,6 +9,7 @@ import moe.lava.banksia.core.model.Stop
import moe.lava.banksia.core.model.StopTime import moe.lava.banksia.core.model.StopTime
import moe.lava.banksia.core.model.Trip import moe.lava.banksia.core.model.Trip
import moe.lava.banksia.core.room.Database import moe.lava.banksia.core.room.Database
import moe.lava.banksia.core.room.DatabaseManager
import moe.lava.banksia.core.room.entity.asEntity import moe.lava.banksia.core.room.entity.asEntity
import moe.lava.banksia.server.gtfs.GtfsData import moe.lava.banksia.server.gtfs.GtfsData
import moe.lava.banksia.server.gtfs.GtfsParser import moe.lava.banksia.server.gtfs.GtfsParser
@ -18,74 +17,66 @@ import kotlin.time.Clock
class GtfsImporter( class GtfsImporter(
private val parser: GtfsParser, private val parser: GtfsParser,
private val database: Database, private val dbm: DatabaseManager,
private val log: Logger, private val log: Logger,
) { ) {
suspend fun import(url: String, date: Long = Clock.System.now().epochSeconds) { suspend fun import(url: String, date: Long = Clock.System.now().epochSeconds) {
database.useWriterConnection { transactor -> val database = dbm.makeAlt()
transactor.immediateTransaction {
database.routeDao.deleteAll()
database.serviceDao.deleteAll()
database.serviceExceptionDao.deleteAll()
database.shapeDao.deleteAll()
database.stopDao.deleteAll()
database.stopTimeDao.deleteAll()
database.tripDao.deleteAll()
parser.update(url).collect { chunk -> parser.update(url).collect { chunk ->
when (chunk) { when (chunk) {
is GtfsData.RouteChunk -> addRoutes(chunk.routes) is GtfsData.RouteChunk -> database.addRoutes(chunk.routes)
is GtfsData.ServiceChunk -> addServices(chunk.services) is GtfsData.ServiceChunk -> database.addServices(chunk.services)
is GtfsData.ServiceExceptionChunk -> addServiceExceptions(chunk.exceptions) is GtfsData.ServiceExceptionChunk -> database.addServiceExceptions(chunk.exceptions)
is GtfsData.ShapeChunk -> addShapes(chunk.shapes) is GtfsData.ShapeChunk -> database.addShapes(chunk.shapes)
is GtfsData.StopChunk -> addStops(chunk.stops) is GtfsData.StopChunk -> database.addStops(chunk.stops)
is GtfsData.StopTimeChunk -> addStopTimes(chunk.stopTimes) is GtfsData.StopTimeChunk -> database.addStopTimes(chunk.stopTimes)
is GtfsData.TripChunk -> addTrips(chunk.trips) is GtfsData.TripChunk -> database.addTrips(chunk.trips)
} }
} }
updateMetadata(date) database.updateMetadata(date)
} database.close()
} dbm.swap()
} }
private suspend fun updateMetadata(date: Long) { private suspend fun Database.updateMetadata(date: Long) {
val dao = database.versionMetadataDao val dao = versionMetadataDao
log.info("updating metadata...") log.info("updating metadata...")
dao.update(date, listOf("routes", "stops", "shapes", "trips", "stop_times")) dao.update(date, listOf("routes", "stops", "shapes", "trips", "stop_times"))
log.info("done") log.info("done")
} }
private suspend fun addRoutes(routes: List<Route>) { private suspend fun Database.addRoutes(routes: List<Route>) {
val dao = database.routeDao val dao = routeDao
log.info("inserting routes...") log.info("inserting routes...")
dao.insertOrReplaceAll(*routes.map { it.asEntity() }.toTypedArray()) dao.insertOrReplaceAll(*routes.map { it.asEntity() }.toTypedArray())
log.info("done") log.info("done")
} }
private suspend fun addServices(services: List<Service>) { private suspend fun Database.addServices(services: List<Service>) {
val dao = database.serviceDao val dao = serviceDao
log.info("inserting services...") log.info("inserting services...")
dao.insertOrReplaceAll(*services.map { it.asEntity() }.toTypedArray()) dao.insertOrReplaceAll(*services.map { it.asEntity() }.toTypedArray())
log.info("done") log.info("done")
} }
private suspend fun addServiceExceptions(exceptions: List<ServiceException>) { private suspend fun Database.addServiceExceptions(exceptions: List<ServiceException>) {
val dao = database.serviceExceptionDao val dao = serviceExceptionDao
log.info("inserting exceptions...") log.info("inserting exceptions...")
dao.insertOrReplaceAll(*exceptions.map { it.asEntity() }.toTypedArray()) dao.insertOrReplaceAll(*exceptions.map { it.asEntity() }.toTypedArray())
log.info("done") log.info("done")
} }
private suspend fun addShapes(shapes: List<Shape>) { private suspend fun Database.addShapes(shapes: List<Shape>) {
val dao = database.shapeDao val dao = shapeDao
log.info("inserting shapes...") log.info("inserting shapes...")
dao.insertOrReplaceAll(*shapes.map { it.asEntity() }.toTypedArray()) dao.insertOrReplaceAll(*shapes.map { it.asEntity() }.toTypedArray())
log.info("done") log.info("done")
} }
private suspend fun addStops(stops: List<Stop>) { private suspend fun Database.addStops(stops: List<Stop>) {
val dao = database.stopDao val dao = stopDao
log.info("inserting stops...") log.info("inserting stops...")
stops stops
.groupBy { it.id } .groupBy { it.id }
@ -102,15 +93,15 @@ class GtfsImporter(
log.info("done") log.info("done")
} }
private suspend fun addStopTimes(stopTimes: List<StopTime>) { private suspend fun Database.addStopTimes(stopTimes: List<StopTime>) {
val dao = database.stopTimeDao val dao = stopTimeDao
log.info("inserting ${stopTimes.size} stoptimes...") log.info("inserting ${stopTimes.size} stoptimes...")
dao.insertOrReplaceAll(*stopTimes.map { it.asEntity() }.toTypedArray()) dao.insertOrReplaceAll(*stopTimes.map { it.asEntity() }.toTypedArray())
log.info("done") log.info("done")
} }
private suspend fun addTrips(trips: List<Trip>) { private suspend fun Database.addTrips(trips: List<Trip>) {
val dao = database.tripDao val dao = tripDao
log.info("inserting ${trips.size} trips...") log.info("inserting ${trips.size} trips...")
dao.insertOrReplaceAll(*trips.map { it.asEntity() }.toTypedArray()) dao.insertOrReplaceAll(*trips.map { it.asEntity() }.toTypedArray())
log.info("done") log.info("done")

View file

@ -6,6 +6,7 @@ import moe.lava.banksia.server.GtfsDataFixer
import moe.lava.banksia.server.GtfsImporter import moe.lava.banksia.server.GtfsImporter
import moe.lava.banksia.server.gtfs.GtfsParser import moe.lava.banksia.server.gtfs.GtfsParser
import moe.lava.banksia.server.gtfsrt.GtfsrtService import moe.lava.banksia.server.gtfsrt.GtfsrtService
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module import org.koin.dsl.module
@ -16,6 +17,6 @@ val ServerModules = module {
singleOf(::GtfsParser) singleOf(::GtfsParser)
singleOf(::GtfsrtService) singleOf(::GtfsrtService)
singleOf(::GtfsDataFixer) factoryOf(::GtfsDataFixer)
singleOf(::GtfsImporter) factoryOf(::GtfsImporter)
} }