Skip to content
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 @@ -7,6 +7,12 @@ import java.time.YearMonth

/** 선택한 월의 일별 운동 요약 조회 */
interface ArchiveRepository {
/** 마지막 조회 월과 일치하는 월간 요약 캐시, 없으면 null */
fun getCachedMonthlySummary(month: YearMonth): List<DailyActivitySummary>?

/** 월간 요약 캐시 삭제 */
fun clearCache()

suspend fun getDailyRecords(date: LocalDate): Result<List<ArchiveRecord>>

suspend fun getMonthlySummary(month: YearMonth): Result<List<DailyActivitySummary>>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,26 @@ internal class ArchiveRepositoryImpl @Inject constructor(
private val service: ArchiveService,
private val apiResponseHandler: ApiResponseHandler,
) : ArchiveRepository {
private val cacheLock = Any()
private var cacheVersion = 0
private var cachedMonth: Pair<YearMonth, List<DailyActivitySummary>>? = null

override fun getCachedMonthlySummary(month: YearMonth): List<DailyActivitySummary>? = synchronized(cacheLock) {
cachedMonth?.takeIf { it.first == month }?.second
}

override fun clearCache() = synchronized(cacheLock) {
cacheVersion++
cachedMonth = null
}

override suspend fun getDailyRecords(date: LocalDate): Result<List<ArchiveRecord>> =
apiResponseHandler.safeApiCall { service.getDailyRecords(date.toString()) }
.map { response -> response.activities.map { ArchiveRecord(it.activityId, it.title, it.thumbnailUrl) } }

override suspend fun getMonthlySummary(month: YearMonth): Result<List<DailyActivitySummary>> =
apiResponseHandler.safeApiCall { service.getMonthlySummary(month.year, month.monthValue) }
override suspend fun getMonthlySummary(month: YearMonth): Result<List<DailyActivitySummary>> {
val version = synchronized(cacheLock) { cacheVersion }
return apiResponseHandler.safeApiCall { service.getMonthlySummary(month.year, month.monthValue) }
.mapCatching { response ->
response.result.map { day ->
DailyActivitySummary(
Expand All @@ -27,5 +41,10 @@ internal class ArchiveRepositoryImpl @Inject constructor(
coverImageUrl = day.coverImageUrl,
)
}
}.onSuccess { summaries ->
synchronized(cacheLock) {
if (version == cacheVersion) cachedMonth = month to summaries
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package com.routee.android.core.data.connectivity.repository

/** 기기 네트워크 연결 상태. API를 부르지 않는 동작 전에 오프라인인지 확인할 때 사용 */
import kotlinx.coroutines.flow.Flow

/** 기기 인터넷 연결 상태 조회 및 변경 감지 */
interface ConnectivityRepository {
/** 인터넷이 되는 네트워크에 연결되어 있는지. 네트워크를 검증하는 중이면 잠시 기다린 뒤 결과를 반환 */
suspend fun isConnected(): Boolean

/** 현재 인터넷 연결 상태와 이후 변경 감지, 화면이 보이는 동안 수집 */
fun observeConnection(): Flow<Boolean>
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ package com.routee.android.core.data.connectivity.repository

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.transformLatest

private const val VALIDATION_CHECK_COUNT = 10
private const val VALIDATION_CHECK_INTERVAL_MILLIS = 200L
Expand All @@ -15,16 +22,45 @@ internal class ConnectivityRepositoryImpl @Inject constructor(
) : ConnectivityRepository {
override suspend fun isConnected(): Boolean = awaitNetworkValidation(::currentNetworkState)

override fun observeConnection() = callbackFlow {
val manager = context.getSystemService(ConnectivityManager::class.java)
if (manager == null) {
trySend(NetworkState.DISCONNECTED)
close()
return@callbackFlow
}
val callback = object : ConnectivityManager.NetworkCallback() {
private var currentNetwork: Network? = null

override fun onAvailable(network: Network) {
currentNetwork = network
trySend(NetworkState.VALIDATING)
}

override fun onLost(network: Network) {
if (network == currentNetwork) {
currentNetwork = null
trySend(NetworkState.DISCONNECTED)
}
}

override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
if (network == currentNetwork) {
trySend(capabilities.networkState())
}
}
}
manager.registerDefaultNetworkCallback(callback)
trySend(currentNetworkState())
awaitClose { manager.unregisterNetworkCallback(callback) }
}.validatedConnection()

private fun currentNetworkState(): NetworkState {
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
?: return NetworkState.DISCONNECTED
val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
?: return NetworkState.DISCONNECTED
return when {
!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) -> NetworkState.DISCONNECTED
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) -> NetworkState.VALIDATED
else -> NetworkState.VALIDATING
}
return capabilities.networkState()
}
}

Expand All @@ -40,3 +76,17 @@ internal suspend fun awaitNetworkValidation(currentState: () -> NetworkState): B
}
return currentState() == NetworkState.VALIDATED
}

private fun NetworkCapabilities.networkState(): NetworkState = when {
!hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) -> NetworkState.DISCONNECTED
hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) -> NetworkState.VALIDATED
else -> NetworkState.VALIDATING
}

@OptIn(ExperimentalCoroutinesApi::class)
internal fun Flow<NetworkState>.validatedConnection(): Flow<Boolean> = distinctUntilChanged().transformLatest { state ->
if (state == NetworkState.VALIDATING) {
delay(VALIDATION_CHECK_COUNT * VALIDATION_CHECK_INTERVAL_MILLIS)
}
emit(state == NetworkState.VALIDATED)
}.distinctUntilChanged()
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,11 @@ package com.routee.android.core.data.member.repository
import com.routee.android.core.data.member.model.MemberSummary

interface MemberRepository {
/** 마지막으로 조회한 회원 요약, 로그아웃 전까지만 사용 */
val cachedSummary: MemberSummary?

/** 회원 요약 캐시 삭제 */
fun clearCache()

suspend fun getMemberSummary(): Result<MemberSummary>
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,28 @@ internal class MemberRepositoryImpl @Inject constructor(
private val apiResponseHandler: ApiResponseHandler,
) : MemberRepository {

override suspend fun getMemberSummary(): Result<MemberSummary> =
apiResponseHandler.safeApiCall { memberService.getMemberSummary() }
private val cacheLock = Any()
private var cacheVersion = 0

@Volatile
override var cachedSummary: MemberSummary? = null
private set

override fun clearCache() = synchronized(cacheLock) {
cacheVersion++
cachedSummary = null
}

override suspend fun getMemberSummary(): Result<MemberSummary> {
val version = synchronized(cacheLock) { cacheVersion }
return apiResponseHandler.safeApiCall { memberService.getMemberSummary() }
.mapCatching { it.toMemberSummary() }
.onSuccess { summary ->
synchronized(cacheLock) {
if (version == cacheVersion) cachedSummary = summary
}
}
}

private fun MemberSummaryResponse.toMemberSummary() = MemberSummary(
nickname = nickname,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@ import java.io.IOException
import java.time.LocalDate
import java.time.YearMonth
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test

@OptIn(ExperimentalCoroutinesApi::class)
class ArchiveRepositoryImplTest {
@Test
fun dailyRecordsUseIsoDateAndKeepServerOrderAndMissingThumbnail() = runTest {
Expand Down Expand Up @@ -56,6 +61,30 @@ class ArchiveRepositoryImplTest {
.getMonthlySummary(YearMonth.of(2026, 3))
}

@Test
fun cacheOnlyRestoresMatchingMonthAndClearRemovesIt() = runTest {
val month = YearMonth.of(2026, 3)
val repository = ArchiveRepositoryImpl(FakeService(), ApiResponseHandler(Json))
val summary = repository.getMonthlySummary(month).getOrThrow()
assertEquals(summary, repository.getCachedMonthlySummary(month))
assertEquals(null, repository.getCachedMonthlySummary(month.minusMonths(1)))
repository.clearCache()
assertEquals(null, repository.getCachedMonthlySummary(month))
}

@Test
fun clearingWhileRequestIsRunningDoesNotRestoreOldCache() = runTest {
val service = FakeService().apply { pending = CompletableDeferred() }
val month = YearMonth.of(2026, 3)
val repository = ArchiveRepositoryImpl(service, ApiResponseHandler(Json))
val request = async { repository.getMonthlySummary(month) }
runCurrent()
repository.clearCache()
service.pending!!.complete(Unit)
assertTrue(request.await().isSuccess)
assertEquals(null, repository.getCachedMonthlySummary(month))
}

private class FakeService(private val error: Exception? = null) : ArchiveService {
override suspend fun deleteActivity(activityId: Long) = error("Unused")

Expand All @@ -74,9 +103,11 @@ class ArchiveRepositoryImplTest {
override suspend fun getRoutes(activityId: Long) = error("Unused")

var requestedMonth: YearMonth? = null
var pending: CompletableDeferred<Unit>? = null

override suspend fun getMonthlySummary(year: Int, month: Int): BaseResponse<MonthlyActivitySummaryResponse> {
error?.let { throw it }
pending?.await()
requestedMonth = YearMonth.of(year, month)
val response = Json.decodeFromString<MonthlyActivitySummaryResponse>(
"""{"result":[{"activityDate":"2026-03-12","totalDurationMinutes":61,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.routee.android.core.data.connectivity.repository

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test

@OptIn(ExperimentalCoroutinesApi::class)
class ObserveConnectionValidationTest {
@Test
fun validatingThenValidatedDoesNotEmitOffline() = runTest {
val states = MutableSharedFlow<NetworkState>()
val connections = mutableListOf<Boolean>()
backgroundScope.launch { states.validatedConnection().collect { connections.add(it) } }
runCurrent()

states.emit(NetworkState.VALIDATING)
advanceTimeBy(1_000)
assertEquals(emptyList<Boolean>(), connections)
states.emit(NetworkState.VALIDATED)
runCurrent()
advanceTimeBy(2_000)
runCurrent()

assertEquals(listOf(true), connections)
}

@Test
fun validationTimeoutEmitsOfflineAndCanRecover() = runTest {
val states = MutableSharedFlow<NetworkState>()
val connections = mutableListOf<Boolean>()
backgroundScope.launch { states.validatedConnection().collect { connections.add(it) } }
runCurrent()

states.emit(NetworkState.VALIDATED)
runCurrent()
states.emit(NetworkState.VALIDATING)
advanceTimeBy(1_999)
assertEquals(listOf(true), connections)
advanceTimeBy(1)
runCurrent()
assertEquals(listOf(true, false), connections)
states.emit(NetworkState.VALIDATED)
runCurrent()

assertEquals(listOf(true, false, true), connections)
}

@Test
fun disconnectionCancelsValidationWaitImmediately() = runTest {
val states = MutableSharedFlow<NetworkState>()
val connections = mutableListOf<Boolean>()
backgroundScope.launch { states.validatedConnection().collect { connections.add(it) } }
runCurrent()

states.emit(NetworkState.VALIDATING)
advanceTimeBy(100)
states.emit(NetworkState.DISCONNECTED)
runCurrent()

assertEquals(listOf(false), connections)
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package com.routee.android.core.domain.auth

import com.routee.android.core.data.archive.repository.ArchiveRepository
import com.routee.android.core.data.image.repository.ImageCacheRepository
import com.routee.android.core.data.member.repository.MemberRepository
import com.routee.android.core.domain.workout.DiscardWorkoutUseCase
import javax.inject.Inject

/** 기기에 남은 사용자 데이터 전체 삭제, 로그아웃, 탈퇴, 로그인 만료 때 부름. 기록 중이면 위치 기록 서비스도 멈춤 */
class ClearDeviceDataUseCase @Inject constructor(
private val discardWorkout: DiscardWorkoutUseCase,
private val imageCacheRepository: ImageCacheRepository,
private val memberRepository: MemberRepository,
private val archiveRepository: ArchiveRepository,
) {
/** 하나가 실패해도 나머지는 지우고, 첫 실패를 돌려줌 */
suspend operator fun invoke(): Result<Unit> {
memberRepository.clearCache()
archiveRepository.clearCache()
val results = listOf(discardWorkout(), imageCacheRepository.clear())
return results.firstOrNull { it.isFailure } ?: Result.success(Unit)
}
Expand Down
Loading
Loading