⚡️ Only update configuration once per second
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Fri, 26 Jul 2019 14:45:59 +0000 (16:45 +0200)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Fri, 26 Jul 2019 14:48:51 +0000 (16:48 +0200)
src/main/java/net/pterodactylus/sone/database/memory/MemoryDatabase.kt
src/test/kotlin/net/pterodactylus/sone/database/memory/MemoryDatabaseTest.kt

index 6fce7e0..a9459e8 100644 (file)
@@ -21,7 +21,7 @@ import com.google.common.base.Preconditions.checkNotNull
 import com.google.common.collect.HashMultimap
 import com.google.common.collect.Multimap
 import com.google.common.collect.TreeMultimap
-import com.google.common.util.concurrent.AbstractService
+import com.google.common.util.concurrent.*
 import com.google.inject.Inject
 import com.google.inject.Singleton
 import net.pterodactylus.sone.data.Album
@@ -70,6 +70,7 @@ class MemoryDatabase @Inject constructor(private val configuration: Configuratio
        private val soneImages: Multimap<String, Image> = HashMultimap.create<String, Image>()
        private val memoryBookmarkDatabase = MemoryBookmarkDatabase(this, configurationLoader)
        private val memoryFriendDatabase = MemoryFriendDatabase(configurationLoader)
+       private val saveRateLimiter: RateLimiter = RateLimiter.create(1.0)
 
        override val soneLoader get() = this::getSone
 
@@ -82,8 +83,10 @@ class MemoryDatabase @Inject constructor(private val configuration: Configuratio
        override val bookmarkedPosts get() = memoryBookmarkDatabase.bookmarkedPosts
 
        override fun save() {
-               saveKnownPosts()
-               saveKnownPostReplies()
+               if (saveRateLimiter.tryAcquire()) {
+                       saveKnownPosts()
+                       saveKnownPostReplies()
+               }
        }
 
        override fun doStart() {
index 1536da4..4d7a105 100644 (file)
@@ -38,7 +38,7 @@ import kotlin.test.*
  */
 class MemoryDatabaseTest {
 
-       private val configuration = mock<Configuration>()
+       private val configuration = deepMock<Configuration>()
        private val memoryDatabase = MemoryDatabase(configuration)
        private val sone = mock<Sone>()
 
@@ -409,6 +409,14 @@ class MemoryDatabaseTest {
                assertThat(configuration.getStringValue("KnownReplies/1/ID").value, equalTo<Any>(null))
        }
 
+       @Test
+       @Dirty("the rate limiter should be mocked")
+       fun `saving the database twice in a row only saves it once`() {
+               memoryDatabase.save()
+               memoryDatabase.save()
+               verify(configuration.getStringValue("KnownPosts/0/ID"), times(1)).value = null
+       }
+
 }
 
 private const val SONE_ID = "sone"