Skip to content
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

Introducing QueryCacheBuilder #61

Merged
merged 1 commit into from
Aug 11, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,56 @@

package soil.query

import soil.query.core.epoch

/**
* State for managing the execution result of [Mutation].
*/
data class MutationState<out T>(
data class MutationState<out T> internal constructor(
override val data: T? = null,
override val dataUpdatedAt: Long = 0,
override val error: Throwable? = null,
override val errorUpdatedAt: Long = 0,
override val status: MutationStatus = MutationStatus.Idle,
override val mutatedCount: Int = 0
) : MutationModel<T>
) : MutationModel<T> {
companion object {

/**
* Creates a new [MutationState] with the [MutationStatus.Success] status.
*
* @param data The data to be stored in the state.
* @param dataUpdatedAt The timestamp when the data was updated. Default is the current epoch.
* @param mutatedCount The number of times the data was mutated.
*/
fun <T> success(
data: T,
dataUpdatedAt: Long = epoch(),
mutatedCount: Int = 1
): MutationState<T> {
return MutationState(
data = data,
dataUpdatedAt = dataUpdatedAt,
status = MutationStatus.Success,
mutatedCount = mutatedCount
)
}

/**
* Creates a new [MutationState] with the [MutationStatus.Failure] status.
*
* @param error The error that occurred.
* @param errorUpdatedAt The timestamp when the error occurred. Default is the current epoch.
*/
fun <T> failure(
error: Throwable,
errorUpdatedAt: Long = epoch()
): MutationState<T> {
return MutationState(
error = error,
errorUpdatedAt = errorUpdatedAt,
status = MutationStatus.Failure
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright 2024 Soil Contributors
// SPDX-License-Identifier: Apache-2.0

package soil.query

import soil.query.core.TimeBasedCache
import soil.query.core.UniqueId
import soil.query.core.epoch
import kotlin.time.Duration

typealias QueryCache = TimeBasedCache<UniqueId, QueryState<*>>

/**
* Creates a new query cache.
*/
fun QueryCache(capacity: Int = 50): QueryCache {
return QueryCache(capacity)
}

/**
* Builder for creating a query cache.
*/
interface QueryCacheBuilder {

/**
* Puts the query data into the cache.
*
* @param id Unique identifier for the query.
* @param data Data to store.
* @param dataUpdatedAt Timestamp when the data was updated. Default is the current epoch time.
* @param dataStaleAt The timestamp after which data is considered stale. Default is the same as [dataUpdatedAt]
*/
fun <T> put(
id: QueryId<T>,
data: T,
dataUpdatedAt: Long = epoch(),
dataStaleAt: Long = dataUpdatedAt,
ttl: Duration = Duration.INFINITE
)

/**
* Puts the infinite-query data into the cache.
*
* @param id Unique identifier for the infinite query.
* @param data Data to store.
* @param dataUpdatedAt Timestamp when the data was updated. Default is the current epoch time.
* @param dataStaleAt The timestamp after which data is considered stale. Default is the same as [dataUpdatedAt]
*/
fun <T, S> put(
id: InfiniteQueryId<T, S>,
data: QueryChunks<T, S>,
dataUpdatedAt: Long = epoch(),
dataStaleAt: Long = dataUpdatedAt,
ttl: Duration = Duration.INFINITE
)
}

/**
* Creates a new query cache with the specified [capacity] and applies the [block] to the builder.
*
* ```kotlin
* val cache = QueryCacheBuilder {
* put(GetUserKey.Id(userId), user)
* ..
* }
* ```
*/
@Suppress("FunctionName")
fun QueryCacheBuilder(capacity: Int = 50, block: QueryCacheBuilder.() -> Unit): QueryCache {
return DefaultQueryCacheBuilder(capacity).apply(block).build()
}

internal class DefaultQueryCacheBuilder(capacity: Int) : QueryCacheBuilder {
private val cache = QueryCache(capacity)

override fun <T> put(
id: QueryId<T>,
data: T,
dataUpdatedAt: Long,
dataStaleAt: Long,
ttl: Duration
) = cache.set(id, QueryState.success(data, dataUpdatedAt, dataStaleAt), ttl)

override fun <T, S> put(
id: InfiniteQueryId<T, S>,
data: QueryChunks<T, S>,
dataUpdatedAt: Long,
dataStaleAt: Long,
ttl: Duration
) = cache.set(id, QueryState.success(data, dataUpdatedAt, dataStaleAt), ttl)

fun build(): QueryCache {
return cache
}
}
46 changes: 44 additions & 2 deletions soil-query-core/src/commonMain/kotlin/soil/query/QueryState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

package soil.query

import soil.query.core.epoch

/**
* State for managing the execution result of [Query].
*/
data class QueryState<out T>(
data class QueryState<out T> internal constructor(
override val data: T? = null,
override val dataUpdatedAt: Long = 0,
override val dataStaleAt: Long = 0,
Expand All @@ -16,4 +18,44 @@ data class QueryState<out T>(
override val fetchStatus: QueryFetchStatus = QueryFetchStatus.Idle,
override val isInvalidated: Boolean = false,
override val isPlaceholderData: Boolean = false
) : QueryModel<T>
) : QueryModel<T> {
companion object {

/**
* Creates a new [QueryState] with the [QueryStatus.Success] status.
*
* @param data The data to be stored in the state.
* @param dataUpdatedAt The timestamp when the data was updated. Default is the current epoch.
* @param dataStaleAt The timestamp after which data is considered stale. Default is the same as [dataUpdatedAt].
*/
fun <T> success(
data: T,
dataUpdatedAt: Long = epoch(),
dataStaleAt: Long = dataUpdatedAt
): QueryState<T> {
return QueryState(
data = data,
dataUpdatedAt = dataUpdatedAt,
dataStaleAt = dataStaleAt,
status = QueryStatus.Success
)
}

/**
* Creates a new [QueryState] with the [QueryStatus.Failure] status.
*
* @param error The error that occurred.
* @param errorUpdatedAt The timestamp when the error occurred. Default is the current epoch.
*/
fun <T> failure(
error: Throwable,
errorUpdatedAt: Long = epoch()
): QueryState<T> {
return QueryState(
error = error,
errorUpdatedAt = errorUpdatedAt,
status = QueryStatus.Failure
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class SwrCache(private val policy: SwrCachePolicy) : SwrClient, QueryMutableClie
private val mutationStore: MutableMap<UniqueId, ManagedMutation<*>> = mutableMapOf()
private val queryReceiver = policy.queryReceiver
private val queryStore: MutableMap<UniqueId, ManagedQuery<*>> = mutableMapOf()
private val queryCache: TimeBasedCache<UniqueId, QueryState<*>> = policy.queryCache
private val queryCache: QueryCache = policy.queryCache

private val coroutineScope: CoroutineScope = CoroutineScope(
context = newCoroutineContext(policy.coroutineScope)
Expand Down Expand Up @@ -733,7 +733,7 @@ data class SwrCachePolicy(
/**
* Management of cached data for inactive [Query] instances.
*/
val queryCache: TimeBasedCache<UniqueId, QueryState<*>> = TimeBasedCache(DEFAULT_CAPACITY),
val queryCache: QueryCache = QueryCache(),

/**
* Specify the mechanism of [ErrorRelay] when using [SwrClient.errorRelay].
Expand Down Expand Up @@ -794,7 +794,6 @@ data class SwrCachePolicy(
val gcInterval: Duration = DEFAULT_GC_INTERVAL
) {
companion object {
const val DEFAULT_CAPACITY = 50
const val DEFAULT_GC_CHUNK_SIZE = 10
val DEFAULT_GC_INTERVAL: Duration = 500.milliseconds
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import kotlin.time.Duration
* @property time A function that returns the current time in seconds since the epoch.
* @constructor Creates a new time-based cache with the specified capacity and time function.
*/
class TimeBasedCache<K : Any, V : Any>(
class TimeBasedCache<K : Any, V : Any> internal constructor(
private val capacity: Int,
private val time: () -> Long = { epoch() }
) {
Expand Down