Skip to content

Commit

Permalink
refactor: Extract listResources utility function for handling pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
SanjayVas committed Nov 15, 2024
1 parent 684948d commit 2734faf
Show file tree
Hide file tree
Showing 11 changed files with 275 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ kt_jvm_library(
deps = [
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:context_keys",
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:measurement_principal",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc:akid_principal_server_interceptor",
"//src/main/kotlin/org/wfanet/measurement/common/grpc:context",
"//src/main/kotlin/org/wfanet/measurement/common/identity",
"//src/main/proto/wfa/measurement/api/v2alpha:duchy_kt_jvm_proto",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ load("@wfa_rules_kotlin_jvm//kotlin:defs.bzl", "kt_jvm_library")
package(default_visibility = ["//visibility:public"])

kt_jvm_library(
name = "grpc",
name = "akid_principal_server_interceptor",
srcs = ["AkidPrincipalServerInterceptor.kt"],
deps = [
"//src/main/kotlin/org/wfanet/measurement/common/api:principal",
Expand All @@ -14,3 +14,13 @@ kt_jvm_library(
"@wfa_common_jvm//src/main/kotlin/org/wfanet/measurement/common/grpc",
],
)

kt_jvm_library(
name = "list_resources",
srcs = ["ListResources.kt"],
deps = [
"@wfa_common_jvm//imports/java/com/google/protobuf",
"@wfa_common_jvm//imports/kotlin/kotlinx/coroutines:core",
"@wfa_rules_kotlin_jvm//imports/io/gprc/kotlin:stub",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2024 The Cross-Media Measurement Authors
*
* 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 org.wfanet.measurement.common.api.grpc

import com.google.protobuf.Message
import io.grpc.kotlin.AbstractCoroutineStub
import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flattenConcat
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map

data class ResourceList<T : Message>(val resources: List<T>, val nextPageToken: String) :
List<T> by resources

/**
* Lists resources from this stub, handling pagination.
*
* @param pageToken page token for initial request
* @param list function which calls the appropriate List method on the stub
*/
fun <T : Message, S : AbstractCoroutineStub<S>> S.listResources(
pageToken: String = "",
list: suspend S.(pageToken: String) -> ResourceList<T>,
): Flow<ResourceList<T>> =
listResources(Int.MAX_VALUE, pageToken) { nextPageToken, _ -> list(nextPageToken) }

/**
* Lists resources from this stub, handling pagination.
*
* @param limit maximum number of resources to emit
* @param pageToken page token for initial request
* @param list function which calls the appropriate List method on the stub, returning no more than
* the specified remaining number of resources
*/
fun <T : Message, S : AbstractCoroutineStub<S>> S.listResources(
limit: Int,
pageToken: String = "",
list: suspend S.(pageToken: String, remaining: Int) -> ResourceList<T>,
): Flow<ResourceList<T>> {
require(limit > 0) { "limit must be positive" }
return flow {
var remaining: Int = limit
var nextPageToken = pageToken

while (true) {
coroutineContext.ensureActive()

val resourceList: ResourceList<T> = list(nextPageToken, remaining)
require(resourceList.size <= remaining) {
"List call must ensure that limit is not exceeded. " +
"Returned ${resourceList.size} items when only $remaining were remaining"
}
emit(resourceList)

remaining -= resourceList.size
nextPageToken = resourceList.nextPageToken
if (nextPageToken.isEmpty() || remaining == 0) {
break
}
}
}
}

/** @see [flattenConcat] */
@ExperimentalCoroutinesApi // Overloads experimental `flattenConcat` function.
fun <T : Message> Flow<ResourceList<T>>.flattenConcat(): Flow<T> =
map { it.asFlow() }.flattenConcat()
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ kt_jvm_library(
],
deps = [
":in_process_cmms_components",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc:list_resources",
"//src/main/kotlin/org/wfanet/measurement/kingdom/batch:measurement_system_prober",
"//src/main/kotlin/org/wfanet/measurement/kingdom/deploy/common/service:data_services",
"@wfa_common_jvm//imports/java/com/google/common/truth",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import java.io.File
import java.nio.file.Paths
import java.time.Clock
import java.time.Duration
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
Expand All @@ -30,13 +32,15 @@ import org.junit.Rule
import org.junit.Test
import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt.DataProvidersCoroutineStub
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineStub
import org.wfanet.measurement.api.v2alpha.ListMeasurementsResponse
import org.wfanet.measurement.api.v2alpha.Measurement
import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub
import org.wfanet.measurement.api.v2alpha.MeasurementsGrpcKt.MeasurementsCoroutineStub
import org.wfanet.measurement.api.v2alpha.RequisitionsGrpcKt.RequisitionsCoroutineStub
import org.wfanet.measurement.api.v2alpha.listMeasurementsRequest
import org.wfanet.measurement.api.withAuthenticationKey
import org.wfanet.measurement.common.api.grpc.ResourceList
import org.wfanet.measurement.common.api.grpc.flattenConcat
import org.wfanet.measurement.common.api.grpc.listResources
import org.wfanet.measurement.common.getRuntimePath
import org.wfanet.measurement.common.identity.withPrincipalName
import org.wfanet.measurement.common.testing.ProviderRule
Expand Down Expand Up @@ -129,33 +133,32 @@ abstract class InProcessMeasurementSystemProberIntegrationTest(
assertThat(measurements.size).isEqualTo(1)
}

@OptIn(ExperimentalCoroutinesApi::class) // For `flattenConcat`.
private suspend fun listMeasurements(): List<Measurement> {
var nextPageToken = ""
val measurementConsumerData = inProcessCmmsComponents.getMeasurementConsumerData()

do {
val response: ListMeasurementsResponse =
try {
publicMeasurementsClient
.withAuthenticationKey(measurementConsumerData.apiAuthenticationKey)
.listMeasurements(
val measurementLists =
publicMeasurementsClient
.withAuthenticationKey(measurementConsumerData.apiAuthenticationKey)
.listResources { pageToken ->
val response =
listMeasurements(
listMeasurementsRequest {
parent = measurementConsumerData.name
pageToken = nextPageToken
this.pageToken = pageToken
}
)
} catch (e: StatusException) {
throw Exception(
"Unable to list measurements for measurement consumer ${measurementConsumerData.name}",
e,
)
ResourceList(response.measurementsList, response.nextPageToken)
}
if (response.measurementsList.isNotEmpty()) {
return response.measurementsList
}
nextPageToken = response.nextPageToken
} while (nextPageToken.isNotEmpty())
return emptyList()

return try {
measurementLists.flattenConcat().toList()
} catch (e: StatusException) {
throw Exception(
"Unable to list measurements for measurement consumer ${measurementConsumerData.name}",
e,
)
}
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ kt_jvm_library(
"//src/main/kotlin/org/wfanet/measurement/api:api_key_constants",
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:packed_messages",
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:resource_key",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc:list_resources",
"//src/main/proto/wfa/measurement/api/v2alpha:data_provider_kt_jvm_proto",
"//src/main/proto/wfa/measurement/api/v2alpha:data_providers_service_kt_jvm_grpc_proto",
"//src/main/proto/wfa/measurement/api/v2alpha:event_group_kt_jvm_proto",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import java.security.SecureRandom
import java.time.Clock
import java.time.Duration
import java.util.logging.Logger
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.singleOrNull
import org.wfanet.measurement.api.v2alpha.CanonicalRequisitionKey
import org.wfanet.measurement.api.v2alpha.DataProvider
import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt
Expand Down Expand Up @@ -60,6 +64,9 @@ import org.wfanet.measurement.api.v2alpha.requisitionSpec
import org.wfanet.measurement.api.v2alpha.unpack
import org.wfanet.measurement.api.withAuthenticationKey
import org.wfanet.measurement.common.Instrumentation
import org.wfanet.measurement.common.api.grpc.ResourceList
import org.wfanet.measurement.common.api.grpc.flattenConcat
import org.wfanet.measurement.common.api.grpc.listResources
import org.wfanet.measurement.common.crypto.Hashing
import org.wfanet.measurement.common.crypto.SigningKeyHandle
import org.wfanet.measurement.common.crypto.readCertificate
Expand Down Expand Up @@ -253,55 +260,50 @@ class MeasurementSystemProber(
return clock.instant() >= nextMeasurementEarliestInstant
}

@OptIn(ExperimentalCoroutinesApi::class) // For `flattenConcat`.
private suspend fun getLastUpdatedMeasurement(): Measurement? {
var nextPageToken = ""
do {
val response: ListMeasurementsResponse =
try {
measurementsStub
.withAuthenticationKey(apiAuthenticationKey)
.listMeasurements(
listMeasurementsRequest {
parent = measurementConsumerName
this.pageSize = 1
pageToken = nextPageToken
}
)
} catch (e: StatusException) {
throw Exception(
"Unable to list measurements for measurement consumer $measurementConsumerName",
e,
val measurements: Flow<ResourceList<Measurement>> =
measurementsStub.withAuthenticationKey(apiAuthenticationKey).listResources(1) {
pageToken,
remaining ->
val response: ListMeasurementsResponse =
listMeasurements(
listMeasurementsRequest {
parent = measurementConsumerName
this.pageToken = pageToken
this.pageSize = remaining
}
)
}
if (response.measurementsList.isNotEmpty()) {
return response.measurementsList.single()
ResourceList(response.measurementsList, response.nextPageToken)
}
nextPageToken = response.nextPageToken
} while (nextPageToken.isNotEmpty())
return null

return try {
measurements.flattenConcat().singleOrNull()
} catch (e: StatusException) {
throw Exception(
"Unable to list measurements for measurement consumer $measurementConsumerName",
e,
)
}
}

private suspend fun getRequisitionsForMeasurement(measurementName: String): List<Requisition> {
var nextPageToken = ""
val requisitions = mutableListOf<Requisition>()
do {
val response: ListRequisitionsResponse =
try {
requisitionsStub
.withAuthenticationKey(apiAuthenticationKey)
.listRequisitions(
listRequisitionsRequest {
parent = measurementName
pageToken = nextPageToken
}
)
} catch (e: StatusException) {
@OptIn(ExperimentalCoroutinesApi::class) // For `flattenConcat`.
private fun getRequisitionsForMeasurement(measurementName: String): Flow<Requisition> {
return requisitionsStub
.withAuthenticationKey(apiAuthenticationKey)
.listResources { pageToken ->
val response: ListRequisitionsResponse =
listRequisitions(listRequisitionsRequest { this.pageToken = pageToken })
ResourceList(response.requisitionsList, response.nextPageToken)
}
.catch { e ->
if (e is StatusException) {
throw Exception("Unable to list requisitions for measurement $measurementName", e)
} else {
throw e
}
requisitions.addAll(response.requisitionsList)
nextPageToken = response.nextPageToken
} while (nextPageToken.isNotEmpty())
return requisitions
}
.flattenConcat()
}

private suspend fun getDataProviderEntry(
Expand Down Expand Up @@ -360,10 +362,12 @@ class MeasurementSystemProber(

private suspend fun updateLastTerminalRequisitionGauge(lastUpdatedMeasurement: Measurement) {
val requisitions = getRequisitionsForMeasurement(lastUpdatedMeasurement.name)
for (requisition in requisitions) {
requisitions.collect { requisition ->
if (requisition.state == Requisition.State.FULFILLED) {
val requisitionKey = CanonicalRequisitionKey.fromName(requisition.name)
require(requisitionKey != null) { "CanonicalRequisitionKey cannot be null" }
val requisitionKey =
requireNotNull(CanonicalRequisitionKey.fromName(requisition.name)) {
"Requisition name ${requisition.name} is invalid"
}
val dataProviderName: String = requisitionKey.dataProviderId
val attributes = Attributes.of(DATA_PROVIDER_ATTRIBUTE_KEY, dataProviderName)
lastTerminalRequisitionTimeGauge.set(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ kt_jvm_library(
"context_keys",
":reporting_principal",
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:resource_key",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc:akid_principal_server_interceptor",
"//src/main/kotlin/org/wfanet/measurement/common/identity",
"@wfa_common_jvm//imports/java/com/google/protobuf",
"@wfa_common_jvm//imports/java/io/grpc:api",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ kt_jvm_library(
"context_keys",
":reporting_principal",
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:resource_key",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc:akid_principal_server_interceptor",
"//src/main/kotlin/org/wfanet/measurement/common/identity",
"@wfa_common_jvm//imports/java/com/google/protobuf",
"@wfa_common_jvm//imports/java/io/grpc:api",
Expand Down Expand Up @@ -120,6 +120,7 @@ kt_jvm_library(
"//imports/java/org/projectnessie/cel",
"//src/main/kotlin/org/wfanet/measurement/api:api_key_constants",
"//src/main/kotlin/org/wfanet/measurement/api/v2alpha:packed_messages",
"//src/main/kotlin/org/wfanet/measurement/common/api/grpc:list_resources",
"//src/main/kotlin/org/wfanet/measurement/reporting/service/api:cel_env_provider",
"//src/main/kotlin/org/wfanet/measurement/reporting/service/api:encryption_key_pair_store",
"//src/main/kotlin/org/wfanet/measurement/reporting/service/api/v2alpha:principal_server_interceptor",
Expand Down
Loading

0 comments on commit 2734faf

Please sign in to comment.