[M120 Migration][VD] TV customization of Disk Cache 57/317757/2 submit/tizen/20240919.160018
authorLiu Feifei <feifei08.liu@samsung.com>
Sat, 14 Sep 2024 16:48:07 +0000 (00:48 +0800)
committerfeifei liu <feifei08.liu@samsung.com>
Thu, 19 Sep 2024 09:04:14 +0000 (09:04 +0000)
1.Disable the disk cache by default on TV
2.Check the disk life time before Disk Cache created
3.Forbid store video/audio to DiskCache on TV
4.Check the free disk of TV when Disk Cache init
5.Separate web apps disk cache location
6.Set Disk Cache size to 0 when --disk-cache-size=0
7.Calculate app disk cache size when cache init
8.Accept disk-cache-size from command line
9.Set lower bound to disk cache file limit
10.SetNetworkCacheEnable API
11.Modify the disk cache storage path
12.Implement clear disk cache when Network service is enabled
13.Change cache type from

References:https://review.tizen.org/gerrit/#/c/280451/

Change-Id: Ic468c51a660ed144ccadac64e21713d00ddacd0f
Signed-off-by: Liu Feifei <feifei08.liu@samsung.com>
13 files changed:
net/disk_cache/blockfile/backend_impl.cc
net/disk_cache/blockfile/backend_impl.h
net/disk_cache/blockfile/eviction.cc
net/disk_cache/cache_util.h
net/disk_cache/cache_util_posix.cc
net/disk_cache/disk_cache.cc
net/http/http_cache.cc
net/http/http_cache.h
services/network/network_context.cc
services/network/network_context.h
services/network/public/mojom/network_context.mojom
tizen_src/ewk/efl_integration/eweb_context.cc
tizen_src/ewk/efl_integration/eweb_context.h

index 309a8ba9b5485160172a7d6cc9ae0341793000b9..0ca44df184e49a787ba4f8dfb8716b7e1d201bb1 100644 (file)
@@ -58,6 +58,12 @@ const int kBaseTableLen = 64 * 1024;
 // Avoid trimming the cache for the first 5 minutes (10 timer ticks).
 const int kTrimDelay = 10;
 
+#if BUILDFLAG(IS_TIZEN_TV)
+// tv needs minimum space to install and update apps, 90M
+const int kTVReservedSpace = 90 * 1024 * 1024;
+const int kMaxFileSizeLowerBound = 5 * 1024 * 1024;
+#endif
+
 int DesiredIndexTableLen(int32_t storage_size) {
   if (storage_size <= k64kEntriesStore)
     return kBaseTableLen;
@@ -219,6 +225,14 @@ int BackendImpl::SyncInit() {
   if (init_)
     return net::ERR_FAILED;
 
+#if BUILDFLAG(IS_TIZEN_TV)
+  int life_time = disk_cache::GetMemoryLifeTime();
+  if (life_time <= 0 || life_time > 5) {
+    LOG(ERROR) << "MemoryLifeTime was dangerous for using cache";
+    return net::ERR_FAILED;
+  }
+#endif
+
   bool create_files = false;
   if (!InitBackingStore(&create_files)) {
     ReportError(ERR_STORAGE_ERROR);
@@ -678,8 +692,12 @@ scoped_refptr<EntryImpl> BackendImpl::OpenNextEntryImpl(
 }
 
 bool BackendImpl::SetMaxSize(int64_t max_bytes) {
-  if (max_bytes < 0 || max_bytes > std::numeric_limits<int>::max())
+  if (max_bytes < 0 || max_bytes > std::numeric_limits<int>::max()) {
+#if BUILDFLAG(IS_TIZEN_TV)
+    max_size_ = max_bytes;
+#endif
     return false;
+  }
 
   // Zero size means use the default.
   if (!max_bytes)
@@ -875,6 +893,13 @@ void BackendImpl::OnEntryDestroyBegin(Addr address) {
 
 void BackendImpl::OnEntryDestroyEnd() {
   DecreaseNumRefs();
+#if BUILDFLAG(IS_TIZEN_TV)
+  if (up_ticks_ > kTrimDelay && !already_update_) {
+    already_update_ = true;
+    UpdateMaxCacheSize();
+    LOG(INFO) << "Current real max cache size : " << max_size_;
+  }
+#endif
   consider_evicting_at_op_end_ = true;
 }
 
@@ -903,7 +928,14 @@ int32_t BackendImpl::GetCurrentEntryId() const {
 }
 
 int64_t BackendImpl::MaxFileSize() const {
+#if BUILDFLAG(IS_TIZEN_TV)
+  if (GetCacheType() == net::PNACL_CACHE)
+    return max_size_;
+
+  return std::max(max_size_ / 8, kMaxFileSizeLowerBound);
+#else
   return GetCacheType() == net::PNACL_CACHE ? max_size_ : max_size_ / 8;
+#endif
 }
 
 void BackendImpl::ModifyStorageSize(int32_t old_size, int32_t new_size) {
@@ -1339,6 +1371,12 @@ bool BackendImpl::InitBackingStore(bool* file_created) {
   if (!base::CreateDirectory(path_))
     return false;
 
+#if BUILDFLAG(IS_TIZEN_TV)
+  if (max_size_ && base::SysInfo::AmountOfFreeDiskSpace(path_) <
+                       (max_size_ + kTVReservedSpace))
+    return false;
+#endif
+
   base::FilePath index_name = path_.AppendASCII(kIndexName);
 
   int flags = base::File::FLAG_READ | base::File::FLAG_WRITE |
@@ -1379,8 +1417,14 @@ bool BackendImpl::InitBackingStore(bool* file_created) {
 // The maximum cache size will be either set explicitly by the caller, or
 // calculated by this code.
 void BackendImpl::AdjustMaxCacheSize(int table_len) {
+#if BUILDFLAG(IS_TIZEN_TV)
+  // if set cache size to zero not use the default.
+  if (max_size_ >= 0)
+    return;
+#else
   if (max_size_)
     return;
+#endif
 
   // If table_len is provided, the index file exists.
   DCHECK(!table_len || data_->header.magic);
@@ -1392,6 +1436,12 @@ void BackendImpl::AdjustMaxCacheSize(int table_len) {
     return;
   }
 
+#if BUILDFLAG(IS_TIZEN_TV)
+  if (available <= kTVReservedSpace)
+    return;
+  available -= kTVReservedSpace;
+#endif
+
   if (table_len)
     available += data_->header.num_bytes;
 
@@ -2014,4 +2064,28 @@ void BackendImpl::FlushAsynchronouslyForTesting(base::OnceClosure callback) {
                                           std::move(callback));
 }
 
+#if BUILDFLAG(IS_TIZEN_TV)
+void BackendImpl::UpdateMaxCacheSize() {
+  int used_size = CalculateWebAppCacheSize(path_, GetCacheType());
+
+  if (used_size == -1)
+    return;
+
+  if (used_size < max_size_) {
+    max_size_ = max_size_ - used_size + data_->header.num_bytes;
+    return;
+  }
+
+  if (data_->header.num_bytes * 2 >= max_size_) {
+    max_size_ =
+        (data_->header.num_bytes > max_size_ ? max_size_
+                                             : data_->header.num_bytes) /
+        2;
+    return;
+  }
+
+  max_size_ = data_->header.num_bytes;
+}
+#endif
+
 }  // namespace disk_cache
index 1be2722e96e6fa43ffdb172d462540171e3b03ee..0ddd154fe5bb0e69bf4e534be098ca9aed5099ff 100644 (file)
@@ -316,6 +316,10 @@ class NET_EXPORT_PRIVATE BackendImpl : public Backend {
   bool InitStats();
   void StoreStats();
 
+#if BUILDFLAG(IS_TIZEN_TV)
+  void UpdateMaxCacheSize();
+#endif
+
   // Deletes the cache and starts again.
   void RestartCache(bool failure);
   void PrepareForRestart();
@@ -425,6 +429,9 @@ class NET_EXPORT_PRIVATE BackendImpl : public Backend {
   bool first_timer_ = true;    // True if the timer has not been called.
   bool user_load_ =
       false;  // True if we see a high load coming from the caller.
+#if BUILDFLAG(IS_TIZEN_TV)
+  bool already_update_ = false;
+#endif
 
   // True if we should consider doing eviction at end of current operation.
   bool consider_evicting_at_op_end_ = false;
index d7b5aada7252c5127f5b8826012c49118081decb..a56f0dd35d5604eb2b7261516462d70f3ff3aea5 100644 (file)
@@ -113,6 +113,10 @@ void Eviction::TrimCache(bool empty) {
   if (backend_->disabled_ || trimming_)
     return;
 
+#if BUILDFLAG(IS_TIZEN_TV)
+  max_size_ = LowWaterAdjust(backend_->max_size_);
+#endif
+
   if (!empty && !ShouldTrim())
     return PostDelayedTrim();
 
index db71eabcfa94a6913a6808a6e0ef3718bbbbaa20..69bf2f52808f061ee2bb27f1534c6a92193cf3ba 100644 (file)
@@ -56,6 +56,18 @@ NET_EXPORT_PRIVATE int PreferredCacheSize(
     int64_t available,
     net::CacheType type = net::DISK_CACHE);
 
+#if BUILDFLAG(IS_TIZEN_TV)
+// Get the life time of device
+int GetMemoryLifeTime();
+
+// Calculate the total web apps disk cache size.
+int CalculateWebAppCacheSize(const base::FilePath& path, net::CacheType type);
+
+// Web apps disk cache path prefix.
+const char kTizenAppCache[] = "WebAppsCache";
+const char kIndexName[] = "index";
+#endif
+
 // The default cache size should not ideally be exposed, but the blockfile
 // backend uses it for reasons that include testing.
 NET_EXPORT_PRIVATE extern const int kDefaultCacheSize;
index 8b3eefa31b50289051cb1bd12ef4c6d66dc0eca5..024c7a1fe42021f5994228ff760fd1f471a27fdd 100644 (file)
 #include "base/strings/string_util.h"
 #include "build/chromeos_buildflags.h"
 
+#if BUILDFLAG(IS_TIZEN_TV)
+#include "net/disk_cache/blockfile/disk_format.h"
+#endif
+
 namespace disk_cache {
 
 bool MoveCache(const base::FilePath& from_path, const base::FilePath& to_path) {
@@ -40,4 +44,75 @@ bool MoveCache(const base::FilePath& from_path, const base::FilePath& to_path) {
 #endif
 }
 
+#if BUILDFLAG(IS_TIZEN_TV)
+/*
+  Device life time table : return value of BSP API, life_time
+  0x00 : Not defined
+  0x01 :  0% -  10% device life time used
+  0x02 : 10% -  20% device life time used
+  0x03 : 20% -  30% device life time used
+  0x04 : 30% -  40% device life time used
+  0x05 : 40% -  50% device life time used
+  0x06 : 50% -  60% device life time used
+  0x07 : 60% -  70% device life time used
+  0x08 : 70% -  80% device life time used
+  0x09 : 80% -  90% device life time used
+  0x0A : 90% - 100% device life time used
+  0x0B : Exceeded its maximum estimated device life time
+  *IMPORTANT* The disk cache should be used having the device
+  life time value from 0x01 to 0x05.
+*/
+int GetMemoryLifeTime() {
+  base::FilePath file_path(FILE_PATH_LITERAL("/sys/block/mmcblk0/life_time"));
+
+  base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
+  if (!file.IsValid())
+    return -1;
+
+  std::string buffer;
+  if (!base::ReadFileToString(file_path, &buffer))
+    return -1;
+
+  int life_time = static_cast<int>(strtol(buffer.c_str(), 0, 16));
+  return life_time;
+}
+
+// Reads the |header_size| bytes from the beginning of file |name|.
+bool ReadHeader(const base::FilePath& name, char* header, int header_size) {
+  base::File file(name, base::File::FLAG_OPEN | base::File::FLAG_READ);
+  if (!file.IsValid())
+    return false;
+
+  int read = file.Read(0, header, header_size);
+  if (read != header_size)
+    return false;
+
+  return true;
+}
+
+int CalculateWebAppCacheSize(const base::FilePath& path, net::CacheType type) {
+  if (type != net::DISK_CACHE)
+    return -1;
+
+  // Only need to calculate the web app cache size, so skip the non web app.
+  if (path.value().find(kTizenAppCache) == std::string::npos)
+    return -1;
+
+  int total = 0;
+  base::FileEnumerator iter(path.DirName(), false,
+                            base::FileEnumerator::DIRECTORIES);
+  for (base::FilePath app_name = iter.Next(); !app_name.value().empty();
+       app_name = iter.Next()) {
+    base::FilePath index_path = app_name.Append(kIndexName);
+    disk_cache::IndexHeader header;
+    if (!ReadHeader(index_path, reinterpret_cast<char*>(&header),
+                    sizeof(header)))
+      continue;
+    total += header.num_bytes;
+  }
+
+  return total;
+}
+#endif
+
 }  // namespace disk_cache
index eb0f34b4e05dfdc37f5ff91a474ec490617baa21..95cadfdf6668de81cd51ca37bca2dd8c2be8bb46 100644 (file)
 
 namespace {
 
+#if BUILDFLAG(IS_TIZEN_TV)
+const double kCacheSizeMagic = 0.7;
+#endif
+
 using FileEnumerator = disk_cache::BackendFileOperations::FileEnumerator;
 using ApplicationStatusListenerGetter =
     disk_cache::ApplicationStatusListenerGetter;
@@ -162,7 +166,13 @@ net::Error CacheCreator::Run() {
       /*cache_thread = */ nullptr, type_, net_log_);
   disk_cache::BackendImpl* new_cache = cache.get();
   created_cache_ = std::move(cache);
+#if BUILDFLAG(IS_TIZEN_TV)
+  // In disk cache case, the cached resource size is about equal to  0.7 *
+  // file.size  which file store cached resource in disk.
+  new_cache->SetMaxSize((double)max_bytes_ * kCacheSizeMagic);
+#else
   new_cache->SetMaxSize(max_bytes_);
+#endif
   new_cache->Init(
       base::BindOnce(&CacheCreator::OnIOComplete, base::Unretained(this)));
   return net::ERR_IO_PENDING;
index e787e799b4e71cce6fcb5d5197e15fc95d170b33..01e3abb796d6c4f678b7ee1d3c50833e44b49b60 100644 (file)
@@ -229,7 +229,11 @@ HttpCache::HttpCache(std::unique_ptr<HttpTransactionFactory> network_layer,
                      std::unique_ptr<BackendFactory> backend_factory)
     : net_log_(nullptr),
       backend_factory_(std::move(backend_factory)),
-
+#if BUILDFLAG(IS_TIZEN_TV)
+      mode_(DISABLE),
+#else
+      mode_(NORMAL),
+#endif
       network_layer_(std::move(network_layer)),
       clock_(base::DefaultClock::GetInstance()) {
   g_init_cache = true;
index bea9762d5b05e65d69f7f37c8433e11c3027bbed..9634166b416a6b4241abe3e5c17efbc9ce2d5431 100644 (file)
@@ -74,6 +74,10 @@ class NET_EXPORT HttpCache : public HttpTransactionFactory {
         NetLog* net_log,
         base::OnceCallback<void(disk_cache::BackendResult)> callback) = 0;
 
+#if BUILDFLAG(IS_TIZEN_TV)
+    virtual void UpdateWebAppDiskCachePath(const base::FilePath& cache_path) {}
+#endif
+
 #if BUILDFLAG(IS_ANDROID)
     virtual void SetAppStatusListenerGetter(
         disk_cache::ApplicationStatusListenerGetter
@@ -105,6 +109,12 @@ class NET_EXPORT HttpCache : public HttpTransactionFactory {
         NetLog* net_log,
         base::OnceCallback<void(disk_cache::BackendResult)> callback) override;
 
+#if BUILDFLAG(IS_TIZEN_TV)
+    void UpdateWebAppDiskCachePath(const base::FilePath& cache_path) override {
+      path_ = cache_path;
+    }
+#endif
+
 #if BUILDFLAG(IS_ANDROID)
     void SetAppStatusListenerGetter(disk_cache::ApplicationStatusListenerGetter
                                         app_status_listener_getter) override;
@@ -115,7 +125,13 @@ class NET_EXPORT HttpCache : public HttpTransactionFactory {
     BackendType backend_type_;
     const scoped_refptr<disk_cache::BackendFileOperationsFactory>
         file_operations_factory_;
+#if BUILDFLAG(IS_TIZEN_TV)
+    // Web apps will have separated disk cache under this directory once web app
+    // id has set.
+    base::FilePath path_;
+#else
     const base::FilePath path_;
+#endif
     int max_bytes_;
     bool hard_reset_;
 #if BUILDFLAG(IS_ANDROID)
@@ -192,6 +208,13 @@ class NET_EXPORT HttpCache : public HttpTransactionFactory {
   void set_mode(Mode value) { mode_ = value; }
   Mode mode() { return mode_; }
 
+#if BUILDFLAG(IS_TIZEN_TV)
+  void UpdateWebAppDiskCachePath(const base::FilePath& cache_path) {
+    if (backend_factory_.get())
+      backend_factory_->UpdateWebAppDiskCachePath(cache_path);
+  }
+#endif
+
   // Get/Set the cache's clock. These are public only for testing.
   void SetClockForTesting(base::Clock* clock) { clock_ = clock; }
   base::Clock* clock() const { return clock_; }
index 2f9fb890939f99b7a8d7e436547c536bce95ca94..5b27eccaf97617cf0afde62abb11a8d538d034ee 100644 (file)
@@ -3137,6 +3137,15 @@ void NetworkContext::SetCacheMode(bool enable) {
   cache->set_mode(enable ? net::HttpCache::NORMAL : net::HttpCache::DISABLE);
 }
 
+void NetworkContext::UpdateWebAppDiskCachePath(
+    const base::FilePath& cache_path) {
+#if BUILDFLAG(IS_TIZEN_TV)
+  url_request_context_->http_transaction_factory()
+      ->GetCache()
+      ->UpdateWebAppDiskCachePath(cache_path);
+#endif
+}
+
 void NetworkContext::CreateCookieManager(
     mojom::NetworkContextParamsPtr params) {
   base::FilePath cookie_path;
index d189f41847083978356d912141b4f3972ad5c493..dec1953e38ffba8e7338854c6935313ae52710ba 100644 (file)
@@ -675,6 +675,7 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext
 
   void CreateCookieManager(mojom::NetworkContextParamsPtr params) override;
   void SetCacheMode(bool enable) override;
+  void UpdateWebAppDiskCachePath(const base::FilePath& cache_path) override;
 
  private:
   class NetworkContextHttpAuthPreferences : public net::HttpAuthPreferences {
index d073132b2bb689cf83bed531923be6b76cc1ec47..df655cd868d66b09deca78dff41b0d29602e9788 100644 (file)
@@ -1686,4 +1686,5 @@ interface NetworkContext {
 
   // Disable/Enable diskcache
   SetCacheMode(bool enable);
+  UpdateWebAppDiskCachePath(mojo_base.mojom.FilePath cache_path);
 };
index 70fe6c97428b1310acde70b60df712294af1d981..79f22fe885536a9cbf33f811a83830bfe06599d9 100644 (file)
@@ -11,6 +11,7 @@
 #include <dlfcn.h>
 #endif
 
+#include "base/path_service.h"
 #include "browser/favicon/favicon_database.h"
 #include "browser/password_manager/password_helper_efl.h"
 #include "browser/tizen_extensible_host.h"
@@ -103,6 +104,28 @@ void SetNetworkCacheEnableOnIOThread(
 
   network_context->SetCacheMode(enable);
 }
+
+#if BUILDFLAG(IS_TIZEN_TV)
+void UpdateWebAppDiskCachePathOnIOThread(
+    const std::string& app_id,
+    content::StoragePartition* storage_partition) {
+  base::FilePath cache_base_path;
+  if (!storage_partition)
+    return;
+
+  if (!base::PathService::Get(base::DIR_CACHE, &cache_base_path)) {
+    LOG(ERROR) << "Could not retrieve path to the cache directory";
+    return;
+  }
+
+  auto network_context = storage_partition->GetNetworkContext();
+  if (!network_context)
+    return;
+
+  network_context->UpdateWebAppDiskCachePath(
+      cache_base_path.AppendASCII(disk_cache::kTizenAppCache).Append(app_id));
+}
+#endif
 /**
  * @brief Helper class for obtaining WebStorage origins
  */
@@ -282,6 +305,13 @@ void EWebContext::SetTizenAppId(        // LCOV_EXCL_LINE
   command_line.AppendSwitchASCII(switches::kTizenAppId, tizen_app_id_);
 #endif  // IS_TIZEN_TV
 #endif  // IS_TIZEN
+
+#if BUILDFLAG(IS_TIZEN_TV)
+  // Since Web Browser also called ewk_context_tizen_app_id_set,
+  // so need to check the application type here.
+  if (application_type_ == EWK_APPLICATION_TYPE_TIZENWRT)
+    UpdateWebAppDiskCachePath(tizen_app_id_);
+#endif
 }       // LCOV_EXCL_LINE
 /* LCOV_EXCL_START */
 bool EWebContext::SetAppVersion(const std::string& tizen_app_version) {
@@ -1007,6 +1037,8 @@ void EWebContext::SetApplicationType(
       break;
     case EWK_APPLICATION_TYPE_TIZENWRT:
       content::SetApplicationType(content::ApplicationType::TIZENWRT);
+      if (!tizen_app_id_.empty())
+        UpdateWebAppDiskCachePath(tizen_app_id_);
       // Now some wrt apps use RGBA mode show transparent background
       // have black issue, only when set support RGBA true can use this
       // RGBA mode
@@ -1028,6 +1060,13 @@ bool EWebContext::GetInspectorServerState() {
   return content::DevToolsUtilManager::GetPort();
 }
 
+void EWebContext::UpdateWebAppDiskCachePath(const std::string& app_id) {
+  content::GetIOThreadTaskRunner({})->PostTask(
+      FROM_HERE,
+      base::BindOnce(&UpdateWebAppDiskCachePathOnIOThread, app_id,
+                     browser_context()->GetDefaultStoragePartition()));
+}
+
 bool EWebContext::ShowInspectorPortInfoState() {
   if (!is_showing_mapping_info_)
     return false;
index 8e312ae1f2039157052a60f3214db5c73e45684d..3049d4dc23b4bddbd1e98c9e80c0901afabc68b3 100644 (file)
@@ -229,6 +229,7 @@ class EWebContext {
       Ewk_Context* ewk_context,
       Ewk_Context_Intercept_Request_Callback callback,
       void* user_data);
+  void UpdateWebAppDiskCachePath(const std::string& app_id);
 #endif
 
   void EnableAppControl(bool enabled);