-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathHttpLocalCache.cpp
More file actions
246 lines (206 loc) · 10.1 KB
/
HttpLocalCache.cpp
File metadata and controls
246 lines (206 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "HttpLocalCache.h"
using namespace Windows::Storage::Streams;
using namespace winrt::Windows::Storage::Streams;
using namespace winrt::Windows::Security::Cryptography;
// Note: this class is used by the HttpRandomAccessStream which is passed to the AppxPackaging COM API
// All exceptions thrown across dll boundaries should be WinRT exception not custom exceptions.
// The HRESULTs will be mapped to UI error code by the appropriate component
namespace AppInstaller::Utility::HttpStream
{
winrt::Windows::Foundation::IAsyncOperation<IBuffer> HttpLocalCache::ReadFromCacheAndDownloadIfNecessaryAsync(
const ULONG64 requestedPosition,
const UINT32 requestedSize,
HttpClientWrapper* httpClientWrapper,
InputStreamOptions httpInputStreamOptions)
{
// Increment cache access counter user for implementing LRU replacement
m_accessCounter++;
// Find all the pages for the given request, and the pages that are missing
std::vector<ULONG64> allPages;
std::vector<ULONG64> unsatisfiablePages;
FindCachePages(requestedPosition, requestedSize, allPages, unsatisfiablePages);
// download the missing pages
co_await DownloadAndSaveToCacheAsync(
unsatisfiablePages,
httpClientWrapper,
httpInputStreamOptions);
// At this point, everything should be in the cache
IBuffer constructedBuffer = {};
for (UINT32 i = 0; i < allPages.size(); i++)
{
UINT64 pageOffset = allPages[i];
IBuffer cachedPageBuffer = ReadPageFromCache(pageOffset);
constructedBuffer = ConcatenateBuffers(constructedBuffer, cachedPageBuffer);
}
// trim buffer to match requested range
IBuffer requestedBuffer = TrimBufferToSatisfyRequest(
constructedBuffer,
requestedPosition,
requestedSize,
allPages);
VacateStaleEntriesFromCache();
co_return requestedBuffer;
}
void HttpLocalCache::FindCachePages(
ULONG64 requestedPosition,
UINT32 requestedSize,
std::vector<ULONG64>& allPages,
std::vector<ULONG64>& unsatisfiablePages)
{
ULONG64 requestedEndPosition;
ULONG64 currentPageOffset;
winrt::check_hresult(ULong64Add(requestedPosition, requestedSize, &requestedEndPosition));
winrt::check_hresult(ULong64Mult((requestedPosition / PAGE_SIZE), PAGE_SIZE, ¤tPageOffset));
// There's always at least one page for the range
do
{
allPages.push_back(currentPageOffset);
if (m_localCache.find(currentPageOffset) == m_localCache.end())
{
unsatisfiablePages.push_back(currentPageOffset);
}
winrt::check_hresult(ULong64Add(currentPageOffset, PAGE_SIZE, ¤tPageOffset));
} while (currentPageOffset < requestedEndPosition);
}
// Breaks the provided buffer into smaller buffers and saves them to the cache at the corresponding
// page offset position, starting at firstPageOffset. The smaller buffers are all PAGE_SIZE bytes,
// except for the one corresponding to the last page in the file
void HttpLocalCache::SaveBufferToCache(const IBuffer& buffer, const ULONG64 firstPageOffset)
{
UINT32 remainingBufferSize = buffer.Length();
UINT32 currentBufferIndex = 0;
ULONG64 currentPageOffset = firstPageOffset;
while (remainingBufferSize > 0)
{
// Extract the sub-buffer
UINT32 currentPageSize = std::min(remainingBufferSize, PAGE_SIZE);
IBuffer currentPageBuffer = CreateTrimmedBuffer(buffer, currentBufferIndex, currentPageSize);
// Add it to the cache
CachedPage currentPage;
currentPage.lastAccessCounter = m_accessCounter;
currentPage.buffer = currentPageBuffer;
m_localCache[currentPageOffset] = currentPage;
// update loop vars
winrt::check_hresult(UInt32Sub(remainingBufferSize, currentPageSize, &remainingBufferSize));
winrt::check_hresult(UInt32Add(currentBufferIndex, currentPageSize, ¤tBufferIndex));
winrt::check_hresult(ULong64Add(currentPageOffset, PAGE_SIZE, ¤tPageOffset));
}
}
IBuffer HttpLocalCache::ReadPageFromCache(const ULONG64 pageOffset)
{
if (!(m_localCache.find(pageOffset) != m_localCache.end()))
{
THROW_HR(E_INVALIDARG);
}
CachedPage& page = m_localCache[pageOffset];
page.lastAccessCounter = m_accessCounter;
return page.buffer;
}
// Trims a buffer that was constructed (by fetching pages from cache and downloading missing pages)
// in order to satisfy a request and return the exact buffer the consumer asked for.
IBuffer HttpLocalCache::TrimBufferToSatisfyRequest(
const IBuffer& constructedBuffer,
const ULONG64 requestedPosition,
const UINT32 requestedSize,
const std::vector<ULONG64> allPages)
{
ULONG64 fullBufferStartOffset = allPages[0];
ULONG64 trimmedBufferStartRelativeIndex;
winrt::check_hresult(ULong64Sub(requestedPosition, fullBufferStartOffset, &trimmedBufferStartRelativeIndex));
IBuffer requestedBuffer = CreateTrimmedBuffer(
constructedBuffer,
(UINT32)trimmedBufferStartRelativeIndex, // Conversion is safe as buffer size is a UINT32.
requestedSize);
return requestedBuffer;
}
// Downloads a chunk of the file, saves it to the cache, and returns the corresponding buffer
// If the requested size is 0, this method returns an empty buffer without making HTTP calls
winrt::Windows::Foundation::IAsyncAction HttpLocalCache::DownloadAndSaveToCacheAsync(
const std::vector<ULONG64> unsatisfiablePages,
HttpClientWrapper* httpClientWrapper,
InputStreamOptions httpInputStreamOptions)
{
// Determine the download job
// To make things easy, we will download the contiguous range that includes all the unsatisfiable ranges.
// Note that in theory, this may include cached pages. However, this situation is rarely expected to happen,
// if at all. The package reader usually reads things in chunks of 64 KB or less, so, we should expect to
// always have up to two satisfiable and unsatisfiable pages in total.
UINT64 fileSize = httpClientWrapper->GetFullFileSize();
ULONG64 downloadJobStartPosition = 0U;
ULONG64 downloadJobEndPosition = 0U;
ULONG64 downloadJobSize = 0U;
if (unsatisfiablePages.size() > 0U)
{
downloadJobStartPosition = unsatisfiablePages[0];
ULONG64 lastUnsatisfiableJob = unsatisfiablePages[unsatisfiablePages.size() - 1];
winrt::check_hresult(ULong64Add(lastUnsatisfiableJob, PAGE_SIZE, &downloadJobEndPosition));
// make sure to not overflow file size
downloadJobEndPosition = std::min(downloadJobEndPosition, fileSize);
winrt::check_hresult(ULong64Sub(downloadJobEndPosition, downloadJobStartPosition, &downloadJobSize));
}
if (downloadJobSize != 0U)
{
// start download job
IBuffer downloadedBuffer = co_await httpClientWrapper->DownloadRangeAsync(
downloadJobStartPosition,
(UINT32)downloadJobSize,
httpInputStreamOptions);
SaveBufferToCache(downloadedBuffer, downloadJobStartPosition);
}
}
void HttpLocalCache::VacateStaleEntriesFromCache()
{
// Copy page offsets into vector and sort by the access counter
std::vector<std::pair<UINT64, int>> orderedPageOffsets;
for (auto pageIter = m_localCache.begin(); pageIter != m_localCache.end(); pageIter++)
{
orderedPageOffsets.push_back(std::pair<UINT64, int>(pageIter->first, pageIter->second.lastAccessCounter));
}
// Compare function to sort by access counter
auto cmp = [](std::pair<UINT64, int> const & a, std::pair<UINT64, int> const & b)
{
return a.second != b.second ? a.second < b.second : a.first < b.first;
};
std::sort(orderedPageOffsets.begin(), orderedPageOffsets.end(), cmp);
for (auto pageIter = orderedPageOffsets.begin(); pageIter != orderedPageOffsets.end(); pageIter++)
{
if (m_localCache.size() > MAX_PAGES)
{
m_localCache.erase(pageIter->first);
}
else
{
break;
}
}
}
IBuffer HttpLocalCache::CreateTrimmedBuffer(
const IBuffer& originalBuffer,
UINT32 trimStartIndex,
UINT32 size)
{
uint32_t bufferLength = originalBuffer.Length();
THROW_HR_IF(E_INVALIDARG, trimStartIndex > bufferLength);
originalBuffer.as<::IInspectable>();
// Get the byte array from the IBuffer object
Microsoft::WRL::ComPtr<IBufferByteAccess> bufferByteAccess;
::IInspectable* bufferAbi = (::IInspectable*)winrt::get_abi(originalBuffer);
bufferAbi->QueryInterface(IID_PPV_ARGS(&bufferByteAccess));
byte* byteBuffer = nullptr;
bufferByteAccess->Buffer(&byteBuffer);
// Create the array of bytes holding the trimmed bytes
IBuffer trimmedBuffer = CryptographicBuffer::CreateFromByteArray(
{ byteBuffer + trimStartIndex, std::min(size, bufferLength - trimStartIndex) });
return trimmedBuffer;
}
IBuffer HttpLocalCache::ConcatenateBuffers(const IBuffer& buffer1, const IBuffer& buffer2)
{
DataWriter writer;
writer.WriteBuffer(buffer1);
writer.WriteBuffer(buffer2);
return writer.DetachBuffer();
}
}