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 #ifndef HTTP_CACHE_STRATEGY_H
17 #define HTTP_CACHE_STRATEGY_H
18 
19 #include <cstring>
20 #include <iostream>
21 #include <tuple>
22 
23 #include "http_cache_request.h"
24 #include "http_cache_response.h"
25 #include "http_request_options.h"
26 #include "http_response.h"
27 
28 namespace OHOS::NetStack::Http {
29 enum CacheStatus {
30     FRESH,
31     STALE,
32     DENY
33 };
34 
35 class HttpCacheStrategy {
36 public:
37     HttpCacheStrategy() = delete;
38 
39     explicit HttpCacheStrategy(HttpRequestOptions &requestOptions);
40 
41     CacheStatus RunStrategy(HttpResponse &response);
42 
43     bool IsCacheable(const HttpResponse &response);
44 
45     bool CouldUseCache();
46 
47 private:
48     CacheStatus RunStrategyInternal(HttpResponse &response);
49 
50     bool IsCacheable(const HttpCacheResponse &cacheResponse);
51 
52     int64_t CacheResponseAgeMillis();
53 
54     std::tuple<int64_t, int64_t, int64_t, int64_t> GetFreshness();
55 
56     int64_t ComputeFreshnessLifetimeMillis();
57 
58     int64_t ComputeFreshnessLifetimeSecondsInternal();
59 
60     void UpdateRequestHeader(const std::string &etag, const std::string &lastModified, const std::string &date);
61 
62     HttpRequestOptions &requestOptions_;
63 
64     HttpCacheResponse cacheResponse_;
65 
66     HttpCacheRequest cacheRequest_;
67 };
68 } // namespace OHOS::NetStack::Http
69 #endif /* HTTP_CACHE_STRATEGY_H */
70