HttpLocalCache.h (2956B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 4 #pragma once 5 6 #include "HttpClientWrapper.h" 7 8 namespace AppInstaller::Utility::HttpStream 9 { 10 // Represents an entry in the cache. 11 struct CachedPage 12 { 13 int lastAccessCounter = 0; 14 winrt::Windows::Storage::Streams::IBuffer buffer; 15 }; 16 17 // A cache used internally by the custom HttpRandomAccessStream to reduce round-trips 18 class HttpLocalCache 19 { 20 public: 21 static constexpr UINT32 PAGE_SIZE = 2 << 16; // each entry in the cache is 64 KB 22 static constexpr UINT32 MAX_PAGES = 200; // cache size capped at 12.5 MB (200 * 64KB) 23 24 // Returns a buffer matching the requested range by reading the parts of the range that are cached 25 // and downloading the rest using the provided httpClientWrapper object 26 std::future<winrt::Windows::Storage::Streams::IBuffer> ReadFromCacheAndDownloadIfNecessaryAsync( 27 const ULONG64 requestedPosition, 28 const UINT32 requestedSize, 29 HttpClientWrapper* httpClientWrapper, 30 winrt::Windows::Storage::Streams::InputStreamOptions httpInputStreamOptions); 31 32 private: 33 std::map<ULONG64, CachedPage> m_localCache; 34 UINT32 m_accessCounter = 0U; 35 36 // Returns a vector of all pages corresponding to a range, and another (subset) 37 // vector of the pages missing from the cache. 38 void FindCachePages( 39 const ULONG64 requestedPosition, 40 const UINT32 requestedSize, 41 std::vector<ULONG64>& allPages, 42 std::vector<ULONG64>& unsatisfiablePages); 43 44 void SaveBufferToCache(const winrt::Windows::Storage::Streams::IBuffer& buffer, const ULONG64 firstPageOffset); 45 46 winrt::Windows::Storage::Streams::IBuffer ReadPageFromCache(const ULONG64 pageOffset); 47 48 void VacateStaleEntriesFromCache(); 49 50 std::future<void> DownloadAndSaveToCacheAsync( 51 const std::vector<ULONG64> unsatisfiablePages, 52 HttpClientWrapper* httpClientWrapper, 53 const winrt::Windows::Storage::Streams::InputStreamOptions httpInputStreamOptions); 54 55 winrt::Windows::Storage::Streams::IBuffer TrimBufferToSatisfyRequest( 56 const winrt::Windows::Storage::Streams::IBuffer& constructedBuffer, 57 const ULONG64 requestedPosition, 58 const UINT32 requestedSize, 59 const std::vector<ULONG64> allPages); 60 61 winrt::Windows::Storage::Streams::IBuffer CreateTrimmedBuffer( 62 const winrt::Windows::Storage::Streams::IBuffer& originalBuffer, 63 UINT32 trimStartIndex, 64 UINT32 size); 65 66 winrt::Windows::Storage::Streams::IBuffer ConcatenateBuffers( 67 const winrt::Windows::Storage::Streams::IBuffer& buffer1, 68 const winrt::Windows::Storage::Streams::IBuffer& buffer2); 69 }; 70 }