Skip to content
This repository has been archived by the owner on Nov 1, 2022. It is now read-only.

Commit

Permalink
Merge branch 'main' into updateCompose
Browse files Browse the repository at this point in the history
  • Loading branch information
rvandermeulen authored Feb 22, 2022
2 parents 1f2d167 + aabeffb commit a19bf89
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 11 deletions.
2 changes: 1 addition & 1 deletion buildSrc/src/main/java/Dependencies.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ object Versions {
const val disklrucache = "2.0.2"
const val leakcanary = "2.8.1"

const val mozilla_appservices = "91.0.1"
const val mozilla_appservices = "91.1.0"

const val mozilla_glean = "44.0.0"

Expand Down
2 changes: 1 addition & 1 deletion buildSrc/src/main/java/Gecko.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ object Gecko {
/**
* GeckoView Version.
*/
const val version = "99.0.20220217094417"
const val version = "99.0.20220222113841"

/**
* GeckoView channel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,7 @@
<string name="mozac_browser_errorpages_safe_phishing_uri_title">Ruk\'ayewal q\'olonel ruxaq</string>
<!-- The %1$s will be replaced by the malicious website URL-->
<string name="mozac_browser_errorpages_safe_phishing_uri_message"><![CDATA[<p>Re ruxaq k\'amaya\'l pa %1$s xya\' rutzijol chi niq\'eleb\'en, ruma ri\' toq xq\'at ruma ach\'ojin chajinïk.</p>]]></string>
</resources>

<!-- The title of the error page for websites that do not support HTTPS when HTTPS-Only is turned on -->
<string name="mozac_browser_errorpages_httpsonly_title">Majun jikïl ruxaq</string>
</resources>
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
<string name="mozac_browser_errorpages_page_refresh">Попробовать снова</string>

<!-- The document title and heading of an error page shown when a website cannot be loaded for an unknown reason. -->
<string name="mozac_browser_errorpages_generic_title">Не удалось завершить запрос</string>
<string name="mozac_browser_errorpages_generic_title">Не удалось выполнить запрос</string>
<!-- The error message shown when a website cannot be loaded for an unknown reason. -->
<string name="mozac_browser_errorpages_generic_message"><![CDATA[
<p>Дополнительная информация об этой ошибке в данное время недоступна.</p>
<p>Дополнительная информация об этой проблеме или ошибке сейчас недоступна.</p>
]]></string>

<!-- The document title and heading of the error page shown when a website sends back unusual and incorrect credentials for an SSL certificate. -->
Expand All @@ -24,8 +24,8 @@
<!-- The error message shown when a website sends has an invalid or expired SSL certificate. -->
<string name="mozac_browser_errorpages_security_bad_cert_message"><![CDATA[
<ul>
<li>Это может быть вызвано неправильной настройкой сервера или же кто-то пытается подменить нужный вам сервер другим.</li>
<li>Если в прошлом вы успешно соединялись с этим сервером, то, возможно, эта ошибка является временной. Попробуйте зайти позже.</li>
<li>Это может быть вызвано неправильной настройкой сервера, или, возможно, кто-то пытается подменить нужный вам сервер другим.</li>
<li>Если раньше вы успешно соединялись с этим сервером, то ошибка может быть временной. В таком случае попробуйте ещё раз позже.</li>
</ul>
]]></string>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal const val MINUTE_IN_MS = 60 * 1000
/**
* Provides access to the Contile services API.
*
* @property context A reference to the application context.
* @param context A reference to the application context.
* @property client [Client] used for interacting with the Contile HTTP API.
* @property endPointURL The url of the endpoint to fetch from. Defaults to [CONTILE_ENDPOINT_URL].
* @property maxCacheAgeInMinutes Maximum time (in minutes) the cache should remain valid
Expand All @@ -46,6 +46,11 @@ class ContileTopSitesProvider(
private val logger = Logger("ContileTopSitesProvider")
private val diskCacheLock = Any()

// The last modified time of the disk cache.
@VisibleForTesting
@Volatile
internal var diskCacheLastModified: Long? = null

/**
* Fetches from the top sites [endPointURL] to provide a list of provided top sites.
* Returns a cached response if [allowCache] is true and the cache is not expired
Expand Down Expand Up @@ -76,6 +81,16 @@ class ContileTopSitesProvider(
}
}

/**
* Refreshes the cache with the latest top sites response from [endPointURL]
* if the cache is active (@see [maxCacheAgeInMinutes]) and expired.
*/
suspend fun refreshTopSitesIfCacheExpired() {
if (maxCacheAgeInMinutes < 0 || !isCacheExpired()) return

getTopSites(allowCache = false)
}

private fun fetchTopSites(): List<TopSite.Provided> {
client.fetch(
Request(url = endPointURL)
Expand Down Expand Up @@ -113,7 +128,10 @@ class ContileTopSitesProvider(
@VisibleForTesting
internal fun writeToDiskCache(responseBody: String) {
synchronized(diskCacheLock) {
getCacheFile().writeString { responseBody }
getCacheFile().let {
it.writeString { responseBody }
diskCacheLastModified = System.currentTimeMillis()
}
}
}

Expand All @@ -123,8 +141,17 @@ class ContileTopSitesProvider(

@VisibleForTesting
internal fun getCacheLastModified(): Long {
diskCacheLastModified?.let { return it }

val file = getBaseCacheFile()
return if (file.exists()) file.lastModified() else -1

return if (file.exists()) {
file.lastModified().also {
diskCacheLastModified = it
}
} else {
-1
}
}

private fun getCacheFile(): AtomicFile = AtomicFile(getBaseCacheFile())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import mozilla.components.support.test.robolectric.testContext
import mozilla.components.support.test.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
Expand Down Expand Up @@ -93,11 +95,16 @@ class ContileTopSitesProviderTest {
)
)

assertNull(provider.diskCacheLastModified)
assertNull(cachingProvider.diskCacheLastModified)

provider.getTopSites()
verify(provider, never()).writeToDiskCache(jsonResponse)
assertNull(provider.diskCacheLastModified)

cachingProvider.getTopSites()
verify(cachingProvider).writeToDiskCache(jsonResponse)
assertNotNull(cachingProvider.diskCacheLastModified)
}

@Test
Expand Down Expand Up @@ -146,6 +153,63 @@ class ContileTopSitesProviderTest {
assertFalse(provider.isCacheExpired())
}

@Test
fun `WHEN the cache last modified time is fetched THEN the returned value is cached`() {
val provider = spy(ContileTopSitesProvider(testContext, prepareClient()))
val file = File(testContext.filesDir, CACHE_FILE_NAME)

assertNull(provider.diskCacheLastModified)

file.createNewFile()

assertTrue(file.exists())

var cacheLastModified = provider.getCacheLastModified()

assertEquals(cacheLastModified, provider.diskCacheLastModified)
assertTrue(file.delete())

cacheLastModified = provider.getCacheLastModified()

assertEquals(cacheLastModified, provider.diskCacheLastModified)
}

@Test
fun `GIVEN cache is not expired WHEN top sites are refreshed THEN do nothing`() = runBlocking {
val provider = spy(
ContileTopSitesProvider(
testContext,
client = prepareClient(),
maxCacheAgeInMinutes = 10
)
)

whenever(provider.isCacheExpired()).thenReturn(false)
provider.refreshTopSitesIfCacheExpired()
verify(provider, never()).getTopSites(allowCache = false)

Unit
}

@Test
fun `GIVEN cache is expired WHEN top sites are refreshed THEN fetch and write new response to cache`() = runBlocking {
val jsonResponse = loadResourceAsString("/contile/contile.json")
val provider = spy(
ContileTopSitesProvider(
testContext,
client = prepareClient(jsonResponse),
maxCacheAgeInMinutes = 10
)
)

whenever(provider.isCacheExpired()).thenReturn(true)

provider.refreshTopSitesIfCacheExpired()

verify(provider).getTopSites(allowCache = false)
verify(provider).writeToDiskCache(jsonResponse)
}

private fun prepareClient(
jsonResponse: String = loadResourceAsString("/contile/contile.json"),
status: Int = 200
Expand Down
2 changes: 1 addition & 1 deletion taskcluster/ac_taskgraph/release_promotion.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,4 @@ def release_promotion_action(parameters, graph_config, input, task_group_id, tas

def read_version_file():
with open(os.path.join(os.path.dirname(__file__), '..', '..', 'version.txt')) as f:
return f.read().strip().decode('utf-8')
return f.read().strip()

0 comments on commit a19bf89

Please sign in to comment.