• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "cache_proxy.h"
17 
18 #include <atomic>
19 #include <condition_variable>
20 #include <mutex>
21 #include <thread>
22 
23 #include "base64_utils.h"
24 #include "constant.h"
25 #include "lru_cache_disk_handler.h"
26 #include "netstack_common_utils.h"
27 #include "netstack_log.h"
28 #include "request_context.h"
29 
30 static constexpr const char *CACHE_FILE = "/data/storage/el2/base/cache/cache.json";
31 static constexpr int32_t WRITE_INTERVAL = 60;
32 
33 namespace OHOS::NetStack {
34 std::mutex g_diskCacheMutex;
35 std::mutex g_cacheNeedRunMutex;
36 std::atomic_bool g_cacheNeedRun(false);
37 std::atomic_bool g_cacheIsRunning(false);
38 std::condition_variable g_cacheThreadCondition;
39 std::condition_variable g_cacheNeedRunCondition;
40 static LRUCacheDiskHandler DISK_LRU_CACHE(CACHE_FILE, 0); // NOLINT(cert-err58-cpp)
41 
CacheProxy(HttpRequestOptions & requestOptions)42 CacheProxy::CacheProxy(HttpRequestOptions &requestOptions) : strategy_(requestOptions)
43 {
44     std::string str = requestOptions.GetUrl() + HttpConstant::HTTP_LINE_SEPARATOR +
45                       CommonUtils::ToLower(requestOptions.GetMethod()) + HttpConstant::HTTP_LINE_SEPARATOR;
46     for (const auto &p : requestOptions.GetHeader()) {
47         str += p.first + HttpConstant::HTTP_HEADER_SEPARATOR + p.second + HttpConstant::HTTP_LINE_SEPARATOR;
48     }
49     str += std::to_string(requestOptions.GetHttpVersion());
50     key_ = Base64::Encode(str);
51 }
52 
ReadResponseFromCache(RequestContext * context)53 bool CacheProxy::ReadResponseFromCache(RequestContext *context)
54 {
55     if (!g_cacheIsRunning.load()) {
56         return false;
57     }
58 
59     if (!strategy_.CouldUseCache()) {
60         NETSTACK_LOGI("only GET/HEAD method or header has [Range] can use cache");
61         return false;
62     }
63 
64     auto responseFromCache = DISK_LRU_CACHE.Get(key_);
65     if (responseFromCache.empty()) {
66         NETSTACK_LOGI("no cache with this request");
67         return false;
68     }
69     HttpResponse cachedResponse;
70     cachedResponse.SetRawHeader(Base64::Decode(responseFromCache[HttpConstant::RESPONSE_KEY_HEADER]));
71     cachedResponse.SetResult(Base64::Decode(responseFromCache[HttpConstant::RESPONSE_KEY_RESULT]));
72     cachedResponse.SetCookies(Base64::Decode(responseFromCache[HttpConstant::RESPONSE_KEY_COOKIES]));
73     cachedResponse.SetResponseTime(Base64::Decode(responseFromCache[HttpConstant::RESPONSE_TIME]));
74     cachedResponse.SetRequestTime(Base64::Decode(responseFromCache[HttpConstant::REQUEST_TIME]));
75     cachedResponse.SetResponseCode(static_cast<uint32_t>(ResponseCode::OK));
76     cachedResponse.ParseHeaders();
77 
78     CacheStatus status = strategy_.RunStrategy(cachedResponse);
79     if (status == CacheStatus::FRESH) {
80         context->response = cachedResponse;
81         NETSTACK_LOGI("cache is FRESH");
82         return true;
83     }
84     if (status == CacheStatus::STALE) {
85         NETSTACK_LOGI("cache is STATE, we try to talk to the server");
86         context->SetCacheResponse(cachedResponse);
87         return false;
88     }
89     NETSTACK_LOGD("cache should not be used");
90     return false;
91 }
92 
WriteResponseToCache(const HttpResponse & response)93 void CacheProxy::WriteResponseToCache(const HttpResponse &response)
94 {
95     if (!g_cacheIsRunning.load()) {
96         return;
97     }
98 
99     if (!strategy_.IsCacheable(response)) {
100         NETSTACK_LOGE("do not cache this response");
101         return;
102     }
103     std::unordered_map<std::string, std::string> cacheResponse;
104     cacheResponse[HttpConstant::RESPONSE_KEY_HEADER] = Base64::Encode(response.GetRawHeader());
105     cacheResponse[HttpConstant::RESPONSE_KEY_RESULT] = Base64::Encode(response.GetResult());
106     cacheResponse[HttpConstant::RESPONSE_KEY_COOKIES] = Base64::Encode(response.GetCookies());
107     cacheResponse[HttpConstant::RESPONSE_TIME] = Base64::Encode(response.GetResponseTime());
108     cacheResponse[HttpConstant::REQUEST_TIME] = Base64::Encode(response.GetRequestTime());
109 
110     DISK_LRU_CACHE.Put(key_, cacheResponse);
111 }
112 
RunCache()113 void CacheProxy::RunCache()
114 {
115     RunCacheWithSize(MAX_DISK_CACHE_SIZE);
116 }
117 
RunCacheWithSize(size_t capacity)118 void CacheProxy::RunCacheWithSize(size_t capacity)
119 {
120     if (g_cacheIsRunning.load()) {
121         return;
122     }
123     DISK_LRU_CACHE.SetCapacity(capacity);
124 
125     g_cacheNeedRun.store(true);
126 
127     DISK_LRU_CACHE.ReadCacheFromJsonFile();
128 
129     std::thread([]() {
130         g_cacheIsRunning.store(true);
131         while (g_cacheNeedRun.load()) {
132             std::unique_lock<std::mutex> lock(g_cacheNeedRunMutex);
133             g_cacheNeedRunCondition.wait_for(lock, std::chrono::seconds(WRITE_INTERVAL),
134                                              [] { return !g_cacheNeedRun.load(); });
135 
136             DISK_LRU_CACHE.WriteCacheToJsonFile();
137         }
138 
139         g_cacheIsRunning.store(false);
140         g_cacheThreadCondition.notify_all();
141     }).detach();
142 }
143 
FlushCache()144 void CacheProxy::FlushCache()
145 {
146     if (!g_cacheIsRunning.load()) {
147         return;
148     }
149     DISK_LRU_CACHE.WriteCacheToJsonFile();
150 }
151 
StopCacheAndDelete()152 void CacheProxy::StopCacheAndDelete()
153 {
154     if (!g_cacheIsRunning.load()) {
155         return;
156     }
157     g_cacheNeedRun.store(false);
158     g_cacheNeedRunCondition.notify_all();
159 
160     std::unique_lock<std::mutex> lock(g_diskCacheMutex);
161     g_cacheThreadCondition.wait(lock, [] { return !g_cacheIsRunning.load(); });
162     DISK_LRU_CACHE.Delete();
163 }
164 } // namespace OHOS::NetStack
165