Skip to content

Commit

Permalink
Merge pull request #10 from AllanHasegawa/fix/cache_invalidation_offline
Browse files Browse the repository at this point in the history
Fix cache invalidation for same boot routine
  • Loading branch information
AllanHasegawa authored Jul 12, 2020
2 parents b421095 + 940367e commit bf8812a
Show file tree
Hide file tree
Showing 12 changed files with 284 additions and 102 deletions.
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
ext {
def versionMajor = 0
def versionMinor = 2
def versionMinor = 3
def versionPatch = 0
def versionCode = versionPatch + versionMinor * 100 + versionMajor * 10000

Expand All @@ -20,8 +20,8 @@ buildscript {
ext {
depPaths = {
def versions = [
gradlePlugin : '3.3.2',
kotlin : '1.3.21',
gradlePlugin : '4.0.0',
kotlin : '1.3.70',
supportLib : '28.0.0',
rxJava : '2.2.7',
rxAndroid : '2.1.1',
Expand Down
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
53 changes: 33 additions & 20 deletions gradlew
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
#!/usr/bin/env sh

#
# Copyright 2015 the original author or 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
#
# https://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.
#

##############################################################################
##
## Gradle start up script for UN*X
Expand Down Expand Up @@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
Expand Down Expand Up @@ -66,6 +82,7 @@ esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar


# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
Expand Down Expand Up @@ -109,10 +126,11 @@ if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

JAVACMD=`cygpath --unix "$JAVACMD"`

# We build the pattern for arguments to be converted via cygpath
Expand All @@ -138,19 +156,19 @@ if $cygwin ; then
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
i=`expr $i + 1`
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi

Expand All @@ -159,14 +177,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
APP_ARGS=`save "$@"`

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi

exec "$JAVACMD" "$@"
22 changes: 21 additions & 1 deletion gradlew.bat
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem

@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
Expand All @@ -13,8 +29,11 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
Expand Down Expand Up @@ -65,6 +84,7 @@ set CMD_LINE_ARGS=%*

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar


@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

Expand Down
1 change: 1 addition & 0 deletions tempo/src/main/java/io/tempo/DeviceClocks.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package io.tempo

interface DeviceClocks {
fun bootCount(): Int?
fun uptime(): Long
fun estimatedBootTime(): Long
}
2 changes: 1 addition & 1 deletion tempo/src/main/java/io/tempo/Tempo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ object Tempo {
timeSources: List<TimeSource> = listOf(SlackSntpTimeSource()),
config: TempoConfig = TempoConfig(),
storage: Storage = SharedPrefStorage(application),
deviceClocks: DeviceClocks = AndroidDeviceClocks(),
deviceClocks: DeviceClocks = AndroidDeviceClocks(application),
scheduler: Scheduler = NoOpScheduler()) {

synchronized(instanceLock) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,18 @@

package io.tempo.device_clocks

import android.content.Context
import android.os.Build
import android.os.SystemClock
import android.provider.Settings
import io.tempo.DeviceClocks

class AndroidDeviceClocks : DeviceClocks {
class AndroidDeviceClocks(private val context: Context) : DeviceClocks {
override fun bootCount(): Int? =
if (Build.VERSION.SDK_INT >= 24)
Settings.Global.getInt(context.contentResolver, Settings.Global.BOOT_COUNT)
else null

override fun uptime(): Long = SystemClock.elapsedRealtime()
override fun estimatedBootTime(): Long = System.currentTimeMillis() - uptime()
}
19 changes: 13 additions & 6 deletions tempo/src/main/java/io/tempo/internal/TempoInstance.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import io.tempo.TimeSourceCache
import io.tempo.TimeSourceWrapper
import io.tempo.schedulers.NoOpScheduler
import java.util.concurrent.TimeUnit
import kotlin.math.abs

internal class TempoInstance(
val timeSources: List<TimeSource>,
Expand Down Expand Up @@ -130,7 +131,9 @@ internal class TempoInstance(
timeSourceId = timeSource.config().id,
estimatedBootTime = deviceClocks.estimatedBootTime(),
requestDeviceUptime = deviceClocks.uptime(),
requestTime = reqTime)
requestTime = reqTime,
bootCount = deviceClocks.bootCount()
)
TimeSourceWrapper(timeSource, cache)
}

Expand All @@ -140,11 +143,15 @@ internal class TempoInstance(
}

private fun restoreCache() {
fun isCacheValid(cache: TimeSourceCache): Boolean {
val estimatedBootTime = deviceClocks.estimatedBootTime()
val cacheEstimatedBootTime = cache.estimatedBootTime
return Math.abs(cacheEstimatedBootTime - estimatedBootTime) <= 5000L
}
fun isCacheValid(cache: TimeSourceCache): Boolean =
when (val bootCount = deviceClocks.bootCount()) {
null -> {
val estimatedBootTime = deviceClocks.estimatedBootTime()
val cacheEstimatedBootTime = cache.estimatedBootTime
abs(cacheEstimatedBootTime - estimatedBootTime) <= 5000L
}
else -> bootCount == cache.bootCount
}

timeSources
.map { source -> source to storage.getCache(source.config().id) }
Expand Down
77 changes: 47 additions & 30 deletions tempo/src/main/java/io/tempo/storage/SharedPrefStorage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,53 +18,70 @@ package io.tempo.storage

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import io.tempo.Storage
import io.tempo.TimeSourceCache
import kotlin.reflect.KClass

class SharedPrefStorage(private val context: Context) : Storage {
companion object {
private const val FILE = "tempo-storage"
private fun keyCacheEstBootTime(name: String) = "$name-est-boot-time"
private fun keyCacheReqUptime(name: String) = "$name-req-uptime"
private fun keyCacheReqTime(name: String) = "$name-req-time"

private fun keyCacheEstBootTime(name: String) = Config("$name-est-boot-time", Long::class)
private fun keyCacheReqUptime(name: String) = Config("$name-req-uptime", Long::class)
private fun keyCacheReqTime(name: String) = Config("$name-req-time", Long::class)
private fun keyBootCount(name: String) = Config("$name-req-boot-count", Int::class)
}

private val accessLock = Any()

@SuppressLint("CommitPrefEdits", "ApplySharedPref")
override fun putCache(cache: TimeSourceCache) {
synchronized(accessLock) {
getSharedPref().edit().apply {
val timeSourceId = cache.timeSourceId
putLong(keyCacheEstBootTime(timeSourceId), cache.estimatedBootTime)
putLong(keyCacheReqUptime(timeSourceId), cache.requestDeviceUptime)
putLong(keyCacheReqTime(timeSourceId), cache.requestTime)
commit()
}
override fun putCache(cache: TimeSourceCache): Unit = synchronized(accessLock) {
getSharedPref().edit().run {
val timeSourceId = cache.timeSourceId
put(keyCacheEstBootTime(timeSourceId), cache.estimatedBootTime)
put(keyCacheReqUptime(timeSourceId), cache.requestDeviceUptime)
put(keyCacheReqTime(timeSourceId), cache.requestTime)
cache.bootCount?.let { put(keyBootCount(timeSourceId), it) }
commit()
}
}

override fun getCache(timeSourceId: String): TimeSourceCache? {
synchronized(accessLock) {
val estBootTime = getSharedPref().getLong(keyCacheEstBootTime(timeSourceId), -1L)
val reqUptime = getSharedPref().getLong(keyCacheReqUptime(timeSourceId), -1L)
val reqTime = getSharedPref().getLong(keyCacheReqTime(timeSourceId), -1L)
return when (reqUptime > 0L && reqTime > 0L && estBootTime > 0L) {
true -> TimeSourceCache(timeSourceId,
estimatedBootTime = estBootTime,
requestDeviceUptime = reqUptime,
requestTime = reqTime)
else -> null
}
override fun getCache(timeSourceId: String): TimeSourceCache? = synchronized(accessLock) {
with(getSharedPref()) {
TimeSourceCache(
timeSourceId = timeSourceId,
estimatedBootTime = get(keyCacheEstBootTime(timeSourceId)) ?: return null,
requestDeviceUptime = get(keyCacheReqUptime(timeSourceId)) ?: return null,
requestTime = get(keyCacheReqTime(timeSourceId)) ?: return null,
bootCount = get(keyBootCount(timeSourceId))
)
}
}

@SuppressLint("CommitPrefEdits", "ApplySharedPref")
override fun clearCaches() {
synchronized(accessLock) {
getSharedPref().edit().clear().commit()
}
@SuppressLint("ApplySharedPref")
override fun clearCaches(): Unit = synchronized(accessLock) {
getSharedPref().edit().clear().commit()
}

private fun getSharedPref() = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)

private fun SharedPreferences.Editor.put(config: Config<Long>, value: Long) =
putLong(config.key, value)

private fun SharedPreferences.Editor.put(config: Config<Int>, value: Int) =
putInt(config.key, value)

private fun SharedPreferences.get(config: Config<Long>): Long? =
when (val value = getLong(config.key, -1L)) {
-1L -> null
else -> value
}

private fun SharedPreferences.get(config: Config<Int>): Int? =
when (val value = getInt(config.key, -1)) {
-1 -> null
else -> value
}

private data class Config<T : Any>(val key: String, val type: KClass<T>)
}
18 changes: 10 additions & 8 deletions tempo/src/main/java/io/tempo/time_source.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@ interface TimeSource {
}

data class TimeSourceCache(
val timeSourceId: String,
val estimatedBootTime: Long,
val requestDeviceUptime: Long,
val requestTime: Long) : Serializable
val timeSourceId: String,
val estimatedBootTime: Long,
val requestDeviceUptime: Long,
val requestTime: Long,
val bootCount: Int?
) : Serializable

data class TimeSourceWrapper(
val timeSource: TimeSource,
val cache: TimeSourceCache) {

val timeSource: TimeSource,
val cache: TimeSourceCache
) {
fun nowFromCache(deviceUptime: Long): Long =
cache.requestTime + (deviceUptime - cache.requestDeviceUptime)
cache.requestTime + (deviceUptime - cache.requestDeviceUptime)
}
Loading

0 comments on commit bf8812a

Please sign in to comment.