diff Framework/Deprecated/Toolbox/BaseWebService.cpp @ 872:733c6db3e5a3 am-dev

limiting the size of the cache
author Alain Mazy <alain@mazy.be>
date Mon, 01 Jul 2019 13:36:51 +0200
parents c0fcb2757b0a
children 200b4e0dddfc
line wrap: on
line diff
--- a/Framework/Deprecated/Toolbox/BaseWebService.cpp	Mon Jun 24 16:29:49 2019 +0200
+++ b/Framework/Deprecated/Toolbox/BaseWebService.cpp	Mon Jul 01 13:36:51 2019 +0200
@@ -27,6 +27,7 @@
 #include <Core/OrthancException.h>
 
 #include <boost/shared_ptr.hpp>
+#include <algorithm>
 
 namespace Deprecated
 {
@@ -101,6 +102,15 @@
     }
     else
     {
+      // put the uri on top of the most recently accessed list
+      std::deque<std::string>::iterator it = std::find(orderedCacheKeys_.begin(), orderedCacheKeys_.end(), uri);
+      if (it != orderedCacheKeys_.end())
+      {
+        std::string uri = *it;
+        orderedCacheKeys_.erase(it);
+        orderedCacheKeys_.push_front(uri);
+      }
+
       // create a command and "post" it to the Oracle so it is executed and commited "later"
       NotifyHttpSuccessLater(cache_[uri], payload, successCallback);
     }
@@ -123,7 +133,23 @@
 
   void BaseWebService::CacheAndNotifyHttpSuccess(const IWebService::HttpRequestSuccessMessage& message)
   {
+    while (cacheCurrentSize_ + message.GetAnswerSize() > cacheMaxSize_ && orderedCacheKeys_.size() > 0)
+    {
+      const std::string& oldestUri = orderedCacheKeys_.back();
+      HttpCache::iterator it = cache_.find(oldestUri);
+      if (it != cache_.end())
+      {
+        cacheCurrentSize_ -= it->second->GetAnswerSize();
+        cache_.erase(it);
+      }
+      orderedCacheKeys_.pop_back();
+
+    }
+
     cache_[message.GetUri()] = boost::shared_ptr<CachedHttpRequestSuccessMessage>(new CachedHttpRequestSuccessMessage(message));
+    orderedCacheKeys_.push_front(message.GetUri());
+    cacheCurrentSize_ += message.GetAnswerSize();
+
     NotifyHttpSuccess(message);
   }