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

Remove initialization state from the SNTP service #51

Merged
merged 1 commit into from
Nov 23, 2020
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 @@ -69,14 +69,14 @@ internal class SntpServiceImpl @JvmOverloads constructor(private val sntpClient:
private val cacheExpirationMs: Long = CACHE_EXPIRATION_MS,
private val maxNtpResponseTimeMs: Long = MAX_NTP_RESPONSE_TIME_MS) : SntpService {

private val state = AtomicReference(State.INIT)
private val state = AtomicReference(State.IDLE)
private val cachedSyncTime = AtomicLong(0)
private val executor = Executors.newSingleThreadExecutor { Thread(it, "kronos-android") }

private val response: SntpClient.Response?
get() {
val response = responseCache.get()
val isCachedFromPreviousBoot = state.compareAndSet(State.INIT, State.IDLE) && response != null && !response.isFromSameBoot
val isCachedFromPreviousBoot = state.get() == State.IDLE && response != null && !response.isFromSameBoot
return if (isCachedFromPreviousBoot) {
responseCache.clear()
null
Expand All @@ -89,7 +89,6 @@ internal class SntpServiceImpl @JvmOverloads constructor(private val sntpClient:
get() = deviceClock.getElapsedTimeMs() - cachedSyncTime.get()

private enum class State {
INIT,
IDLE,
SYNCING,
STOPPED
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,19 @@ class SntpServiceTest {
verify(sntpSyncListener, times(1)).onError(eq("1.fake.pool.ntp.org"), any<NTPSyncException>())
verify(sntpSyncListener, times(1)).onError(eq("2.fake.pool.ntp.org"), any<NTPSyncException>())
}

@Test
fun shouldClearCacheWhenSyncFailsAndGettingCurrentTime() {
whenever(sntpClient.requestTime("1.fake.pool.ntp.org", TIMEOUT_MS)).thenReturn(mockResponse)
whenever(sntpClient.requestTime("2.fake.pool.ntp.org", TIMEOUT_MS)).thenReturn(mockResponse)
whenever(mockResponse.currentTimeMs).thenReturn(-1)
whenever(mockResponse.isFromSameBoot).thenReturn(false)
whenever(responseCache.get()).thenReturn(mockResponse)

assertThat(sntpService.sync()).isFalse

sntpService.currentTime()

verify(responseCache, times(1)).clear()
}
}