Skip to content

Compose benchmark app crud #2818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions engine/benchmarks/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
synthea
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.fhir.engine.benchmarks.app

import kotlin.time.Duration

internal data class BenchmarkDuration(val size: Int, val duration: Duration) {
val averageDuration: Duration
get() = if (size > 0) duration.div(size) else Duration.ZERO

companion object {
val ZERO: BenchmarkDuration = BenchmarkDuration(size = 0, duration = Duration.ZERO)
}
}

internal operator fun BenchmarkDuration.plus(other: BenchmarkDuration): BenchmarkDuration {
return BenchmarkDuration(this.size + other.size, this.duration + other.duration)
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,105 @@ package com.google.android.fhir.engine.benchmarks.app

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.tracing.traceAsync
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.engine.benchmarks.app.data.ResourcesDataProvider
import java.time.LocalDateTime
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType

@Suppress("unused")
class CrudApiViewModel(
internal class CrudApiViewModel(
private val resourcesDataProvider: ResourcesDataProvider,
private val fhirEngine: FhirEngine,
) : ViewModel() {
private val _detailMutableStateFlow = MutableStateFlow("")
val detailStateFlow: StateFlow<String> = _detailMutableStateFlow.asStateFlow()

private val _crudMutableStateFlow = MutableStateFlow(CRUDUiState())
val crudStateFlow = _crudMutableStateFlow.asStateFlow()

init {
viewModelScope.launch(benchmarkingViewModelWorkDispatcher) {
_detailMutableStateFlow.value = "CRUD: ${LocalDateTime.now()}"
viewModelScope.launch(benchmarkingViewModelWorkDispatcher) { traceCRUD() }
}

private suspend fun traceCRUD() {
// Create
fhirEngine.clearDatabase()
val savedResourceTypeIdPairs: MutableList<List<Pair<ResourceType, String>>> = mutableListOf()

resourcesDataProvider.provideResources { resources ->
val (logicalIds, duration) = traceCreateResources(resources)
val result = BenchmarkDuration(logicalIds.size, duration)
_crudMutableStateFlow.update { it.copy(create = it.create + result) }

savedResourceTypeIdPairs += resources.zip(logicalIds) { r, l -> Pair(r.resourceType, l) }
}

// Get
val dbResources =
savedResourceTypeIdPairs.mapIndexed { index, list ->
val (resourceType, logicalId) = list.shuffled().random()
val (resource, duration) = traceGetResource(resourceType, logicalId)

val result = BenchmarkDuration(1, duration)
_crudMutableStateFlow.update { it.copy(read = it.read + result) }
resource
}

// Update
val updateDbResources =
dbResources.shuffled().mapIndexed { index, resource ->
val duration = traceUpdateResources(listOf(resource))

val result = BenchmarkDuration(1, duration)
_crudMutableStateFlow.update { it.copy(update = it.update + result) }
resource
}

// Delete
updateDbResources.shuffled().forEachIndexed { index, resource ->
val logicalId = resource.idElement?.idPart.orEmpty()
val duration = traceDeleteResources(resource.resourceType, logicalId)
val result = BenchmarkDuration(1, duration)
_crudMutableStateFlow.update { it.copy(delete = it.delete + result) }
}
}

/**
* measureTime wraps to get time elapsed for display in UI while trace wraps for use in
* macrobenchmarking of the application as a TraceMetric
*/
private suspend fun traceCreateResources(resources: List<Resource>) = measureTimedValueAsync {
traceAsync(TRACE_CREATE_SECTION_NAME, 0) { fhirEngine.create(*resources.toTypedArray()) }
}

private suspend fun traceUpdateResources(resources: List<Resource>) = measureTimeAsync {
traceAsync(TRACE_UPDATE_SECTION_NAME, 1) { fhirEngine.update(*resources.toTypedArray()) }
}

private suspend fun traceGetResource(resourceType: ResourceType, resourceId: String) =
measureTimedValueAsync {
traceAsync(TRACE_GET_SECTION_NAME, 2) { fhirEngine.get(resourceType, resourceId) }
}

private suspend fun traceDeleteResources(resourceType: ResourceType, resourceId: String) =
measureTimeAsync {
traceAsync(TRACE_DELETE_SECTION_NAME, 3) { fhirEngine.delete(resourceType, resourceId) }
}

companion object {
const val TRACE_CREATE_SECTION_NAME = "Create API"
const val TRACE_UPDATE_SECTION_NAME = "Update API"
const val TRACE_GET_SECTION_NAME = "Get API"
const val TRACE_DELETE_SECTION_NAME = "Delete API"
}
}

internal data class CRUDUiState(
val create: BenchmarkDuration = BenchmarkDuration.ZERO,
val read: BenchmarkDuration = BenchmarkDuration.ZERO,
val update: BenchmarkDuration = BenchmarkDuration.ZERO,
val delete: BenchmarkDuration = BenchmarkDuration.ZERO,
)
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package com.google.android.fhir.engine.benchmarks.app
import android.app.Application
import android.content.Context
import android.util.Log
import androidx.tracing.Trace
import com.google.android.fhir.DatabaseErrorStrategy.RECREATE_AT_OPEN
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.FhirEngineConfiguration
Expand All @@ -31,6 +32,8 @@ class MainApplication : Application() {

override fun onCreate() {
super.onCreate()
Trace.forceEnableAppTracing()

FhirEngineProvider.init(
FhirEngineConfiguration(
enableEncryptionIfSupported = true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ package com.google.android.fhir.engine.benchmarks.app

import androidx.lifecycle.ViewModel

class MainViewModel() : ViewModel()
internal class MainViewModel() : ViewModel()
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

@Suppress("unused")
class SearchApiViewModel(
internal class SearchApiViewModel(
private val resourcesDataProvider: ResourcesDataProvider,
private val fhirEngine: FhirEngine,
) : ViewModel() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

@Suppress("unused")
class SyncApiViewModel(
internal class SyncApiViewModel(
private val resourcesDataProvider: ResourcesDataProvider,
private val fhirEngine: FhirEngine,
) : ViewModel() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,23 @@

package com.google.android.fhir.engine.benchmarks.app

import kotlin.time.Duration
import kotlin.time.TimeSource
import kotlin.time.TimedValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi

@OptIn(ExperimentalCoroutinesApi::class)
internal val benchmarkingViewModelWorkDispatcher = Dispatchers.Default.limitedParallelism(1)

internal suspend fun measureTimeAsync(block: suspend () -> Unit): Duration {
val mark = TimeSource.Monotonic.markNow()
block()
return mark.elapsedNow()
}

internal suspend fun <T> measureTimedValueAsync(block: suspend () -> T): TimedValue<T> {
val mark = TimeSource.Monotonic.markNow()
val result = block()
return TimedValue(result, mark.elapsedNow())
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class ResourcesDataProvider(
private val assetManager: AssetManager,
private val fhirR4JsonParser: IParser,
) {
suspend fun provideResources(onResourcesProvided: (Iterable<Resource>) -> Unit) {
suspend fun provideResources(onResourcesProvided: suspend (List<Resource>) -> Unit) {
try {
readFileResources()
.chunked(READ_CHUNK_SIZE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,63 @@ package com.google.android.fhir.engine.benchmarks.app.ui

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.android.fhir.engine.benchmarks.app.BenchmarkDuration
import com.google.android.fhir.engine.benchmarks.app.CrudApiViewModel
import kotlin.time.Duration.Companion.milliseconds

@Composable
fun CrudDetail(
internal fun CrudDetail(
viewModel: CrudApiViewModel,
navigateToHome: () -> Unit,
) {
val detailState = viewModel.detailStateFlow.collectAsStateWithLifecycle()
val crudUiState = viewModel.crudStateFlow.collectAsStateWithLifecycle()
val crudUiStateValue by remember { crudUiState }

DetailScaffold("CRUD", navigateToHome) {
Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.Center) {
Text(detailState.value, fontSize = 20.sp, textAlign = TextAlign.Center)
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
CrudBenchmarkResultView("FhirEngine#Create", crudUiStateValue.create)
CrudBenchmarkResultView("FhirEngine#Get", crudUiStateValue.read)
CrudBenchmarkResultView("FhirEngine#Update", crudUiStateValue.update)
CrudBenchmarkResultView("FhirEngine#Delete", crudUiStateValue.delete)
}
}
}

@Composable
internal fun CrudBenchmarkResultView(headline: String, benchmarkDuration: BenchmarkDuration) {
Column(Modifier.padding(8.dp)) {
Text(headline, style = MaterialTheme.typography.headlineMedium)
Spacer(Modifier.size(8.dp))
when {
benchmarkDuration == BenchmarkDuration.ZERO -> Text("Waiting for results\u2026")
else -> {
Text("Takes ~${benchmarkDuration.duration} for ${benchmarkDuration.size} resources")
Text("Averages: ~${benchmarkDuration.averageDuration}")
}
}
}
}

@Preview(showBackground = true)
@Composable
internal fun PreviewCrudBenchmarkResultView() {
CrudBenchmarkResultView("FhirEngine#Create", BenchmarkDuration(20, 1008.milliseconds))
}

@Preview(showBackground = true)
@Composable
internal fun PreviewCrudNilBenchmarkResultView() {
CrudBenchmarkResultView("FhirEngine#Create", BenchmarkDuration.ZERO)
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

Expand All @@ -57,7 +59,7 @@ fun DetailScaffold(
},
)
},
modifier = Modifier.fillMaxSize(),
modifier = Modifier.fillMaxSize().semantics { testTagsAsResourceId = true },
) { innerPadding ->
Card(
shape = RoundedCornerShape(10.dp),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
Expand All @@ -57,7 +60,7 @@ fun Home(
) {
Scaffold(
topBar = { TopAppBar(title = { Text(stringResource(R.string.app_name)) }) },
modifier = Modifier.fillMaxSize(),
modifier = Modifier.fillMaxSize().semantics { testTagsAsResourceId = true },
) { innerPadding ->
Box(
Modifier.padding(innerPadding).padding(horizontal = 16.dp),
Expand All @@ -66,18 +69,21 @@ fun Home(
ActionCard(
title = "CRUD",
imageId = R.drawable.ic_outline_database_24,
modifier = Modifier.testTag("crudBenchmarkSection"),
onActionClick = navigateToCrudScreen,
)

ActionCard(
title = "Search API",
imageId = R.drawable.ic_home_search,
modifier = Modifier.testTag("searchBenchmarkSection"),
onActionClick = navigateToSearchScreen,
)

ActionCard(
title = "Sync API",
imageId = R.drawable.ic_home_sync,
modifier = Modifier.testTag("syncBenchmarkSection"),
onActionClick = navigateToSyncScreen,
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.android.fhir.engine.benchmarks.app.SearchApiViewModel

@Composable
fun SearchApiDetail(viewModel: SearchApiViewModel, navigateToHome: () -> Unit) {
internal fun SearchApiDetail(viewModel: SearchApiViewModel, navigateToHome: () -> Unit) {
val detailState = viewModel.detailStateFlow.collectAsStateWithLifecycle()

DetailScaffold("Search API", navigateToHome) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.android.fhir.engine.benchmarks.app.SyncApiViewModel

@Composable
fun SyncApiDetail(viewModel: SyncApiViewModel, navigateToHome: () -> Unit) {
internal fun SyncApiDetail(viewModel: SyncApiViewModel, navigateToHome: () -> Unit) {
val detailState = viewModel.detailStateFlow.collectAsStateWithLifecycle()

DetailScaffold("Sync API", navigateToHome) {
Expand Down
Loading
Loading