Repository navigation
Expand file tree
/
Copy pathResponseBodyStreamWithCaching.cpp
More file actions
236 lines (203 loc) · 7.63 KB
/
Copy pathResponseBodyStreamWithCaching.cpp
File metadata and controls
236 lines (203 loc) · 7.63 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
/*
* Copyright 2017 Sony Corporation
*/
#include "Poco/Exception.h"
#include "Poco/File.h"
#include "Poco/FileStream.h"
#include "Poco/TemporaryFile.h"
#include "Poco/Timestamp.h"
#include "easyhttpcpp/common/CoreLogger.h"
#include "easyhttpcpp/common/CacheManager.h"
#include "easyhttpcpp/common/FileUtil.h"
#include "easyhttpcpp/HttpException.h"
#include "HttpCacheInternal.h"
#include "HttpCacheMetadata.h"
#include "HttpUtil.h"
#include "ResponseBodyStreamWithCaching.h"
using easyhttpcpp::common::Cache;
using easyhttpcpp::common::CacheManager;
using easyhttpcpp::common::CacheMetadata;
using easyhttpcpp::common::FileUtil;
namespace easyhttpcpp {
static const std::string Tag = "ResponseBodyStreamWithCaching";
ResponseBodyStreamWithCaching::ResponseBodyStreamWithCaching(std::istream& content,
ConnectionInternal::Ptr pConnectionInternal, ConnectionPoolInternal::Ptr pConnectionPoolInternal,
Response::Ptr pResponse, HttpCache::Ptr pHttpCache) :
ResponseBodyStreamInternal(content), m_pConnectionInternal(pConnectionInternal),
m_pConnectionPoolInternal(pConnectionPoolInternal), m_pResponse(pResponse), m_pHttpCache(pHttpCache),
m_pTempFileStream(NULL), m_writtenDataSize(0)
{
}
ResponseBodyStreamWithCaching::~ResponseBodyStreamWithCaching()
{
closeOutStream();
}
ssize_t ResponseBodyStreamWithCaching::read(char* pBuffer, size_t readBytes)
{
ssize_t retBytes = ResponseBodyStreamInternal::read(pBuffer, readBytes);
if (retBytes < 0) {
return retBytes;
}
Poco::Mutex::ScopedLock lock(m_instanceMutex);
if (m_closed) {
EASYHTTPCPP_LOG_D(Tag, "read: already closed.");
throw HttpIllegalStateException("stream already closed.");
}
// save temp file for cache
if (!createTempFile()) {
return retBytes;
}
try {
m_pTempFileStream->write(static_cast<const char*> (pBuffer), static_cast<std::streamsize> (retBytes));
m_writtenDataSize += retBytes;
} catch (const std::exception& e) {
std::string message = "can not receive response because IO error occurred.(write)";
EASYHTTPCPP_LOG_D(Tag, "%s %s", message.c_str(), e.what());
}
return retBytes;
}
void ResponseBodyStreamWithCaching::close()
{
Poco::Mutex::ScopedLock lock(m_instanceMutex);
if (m_closed) {
EASYHTTPCPP_LOG_D(Tag, "close: already closed");
return;
}
// skip remaining data, if exist.
if (skipAll(m_pConnectionInternal->getPocoHttpClientSession())) {
EASYHTTPCPP_LOG_D(Tag, "Connection is reusable.");
// release connection.
m_pConnectionPoolInternal->releaseConnection(m_pConnectionInternal);
} else {
EASYHTTPCPP_LOG_D(Tag, "Could not reuse connection since skipping response body failed.");
// remove connection.
m_pConnectionPoolInternal->removeConnection(m_pConnectionInternal);
}
m_pConnectionInternal = NULL;
m_pConnectionPoolInternal = NULL;
bool responseBodyValid = isValidResponseBody();
ResponseBodyStreamInternal::close();
// put cache
closeOutStream();
if (responseBodyValid) {
putCache();
} else {
EASYHTTPCPP_LOG_D(Tag, "remove TempFile, because response body is not valid");
removeTempFile();
}
EASYHTTPCPP_LOG_D(Tag, "close: finished");
}
Connection::Ptr ResponseBodyStreamWithCaching::getConnection()
{
return m_pConnectionInternal.unsafeCast<Connection>();
}
bool ResponseBodyStreamWithCaching::createTempFile()
{
if (m_pTempFileStream) {
return true;
}
HttpCacheInternal* pCacheInternal = static_cast<HttpCacheInternal*> (m_pHttpCache.get());
try {
const std::string& tempDirectory = pCacheInternal->getTempDirectory();
m_tempFilePath = Poco::TemporaryFile::tempName(tempDirectory);
EASYHTTPCPP_LOG_D(Tag, "tempFile=%s", m_tempFilePath.c_str());
} catch (const HttpException& e) {
EASYHTTPCPP_LOG_D(Tag, "can not get temp directory. HttpException=%s", e.getMessage().c_str());
m_pTempFileStream = NULL;
m_tempFilePath.clear();
return false;
}
try {
m_pTempFileStream = new Poco::FileOutputStream(m_tempFilePath,
std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
m_writtenDataSize = 0;
} catch (const HttpException& e) {
EASYHTTPCPP_LOG_D(Tag, "can not create temp file. HttpException=%s", e.getMessage().c_str());
m_pTempFileStream = NULL;
m_tempFilePath.clear();
return false;
} catch (const Poco::Exception& e) {
EASYHTTPCPP_LOG_D(Tag, "can not create temp file. Poco::Exception=%s", e.message().c_str());
m_pTempFileStream = NULL;
m_tempFilePath.clear();
return false;
} catch (const std::exception& e) {
EASYHTTPCPP_LOG_D(Tag, "can not create temp file. std::exception=%s", e.what());
m_pTempFileStream = NULL;
m_tempFilePath.clear();
return false;
}
return true;
}
void ResponseBodyStreamWithCaching::closeOutStream()
{
if (m_pTempFileStream) {
m_pTempFileStream->close();
delete m_pTempFileStream;
m_pTempFileStream = NULL;
}
}
bool ResponseBodyStreamWithCaching::isValidResponseBody()
{
if (!m_pResponse->hasContentLength()) {
if (isEof()) {
return true;
} else {
return false;
}
}
ssize_t contentLength = m_pResponse->getContentLength();
if (contentLength == -1) {
if (isEof()) {
return true;
} else {
return false;
}
}
if (contentLength != m_writtenDataSize) {
return false;
}
return true;
}
void ResponseBodyStreamWithCaching::removeTempFile()
{
if (m_tempFilePath.empty()) {
EASYHTTPCPP_LOG_D(Tag, "removeTempFile: temporary file is not created.");
return;
}
Poco::File file(m_tempFilePath);
if (!FileUtil::removeFileIfPresent(file)) {
std::string message = "can not receive response because IO error occurred.(remove)";
EASYHTTPCPP_LOG_D(Tag, "%s", message.c_str());
throw HttpExecutionException(message);
}
}
void ResponseBodyStreamWithCaching::putCache()
{
CacheMetadata::Ptr pCacheMetadata = new HttpCacheMetadata();
HttpCacheMetadata* pHttpCacheMetadata = static_cast<HttpCacheMetadata*> (pCacheMetadata.get());
Request::Ptr pRequest = m_pResponse->getRequest();
pHttpCacheMetadata->setKey(HttpUtil::makeCacheKey(pRequest));
if (pHttpCacheMetadata->getKey().empty()) {
EASYHTTPCPP_LOG_D(Tag, "putCache: can not make key.");
removeTempFile();
return;
}
pHttpCacheMetadata->setUrl(pRequest->getUrl());
pHttpCacheMetadata->setHttpMethod(pRequest->getMethod());
pHttpCacheMetadata->setStatusCode(m_pResponse->getCode());
pHttpCacheMetadata->setStatusMessage(m_pResponse->getMessage());
pHttpCacheMetadata->setResponseHeaders(m_pResponse->getHeaders());
pHttpCacheMetadata->setResponseBodySize(m_writtenDataSize);
pHttpCacheMetadata->setSentRequestAtEpoch(m_pResponse->getSentRequestSec());
pHttpCacheMetadata->setReceivedResponseAtEpoch(m_pResponse->getReceivedResponseSec());
Poco::Timestamp now;
pHttpCacheMetadata->setCreatedAtEpoch(now.epochTime());
HttpCacheInternal* pCacheInternal = static_cast<HttpCacheInternal*> (m_pHttpCache.get());
CacheManager::Ptr pCacheManager = pCacheInternal->getCacheManager();
if (!pCacheManager->put(pHttpCacheMetadata->getKey(), pCacheMetadata, m_tempFilePath)) {
EASYHTTPCPP_LOG_D(Tag, "putCache: can not put cache[%s].", pHttpCacheMetadata->getKey().c_str());
removeTempFile();
}
}
} /* namespace easyhttpcpp */