1#include <s3api/clients/client.hpp>
6#include <boost/algorithm/string.hpp>
9#include <userver/http/common_headers.hpp>
10#include <userver/http/url.hpp>
11#include <userver/logging/log.hpp>
12#include <userver/utils/algo.hpp>
13#include <userver/utils/exception.hpp>
15#include <userver/s3api/authenticators/access_key.hpp>
17#include <s3api/s3_connection.hpp>
18#include <s3api/s3api_methods.hpp>
20USERVER_NAMESPACE_BEGIN
25const std::string kMeta =
"x-amz-meta-";
26const std::string kTagging =
"X-Amz-Tagging";
27constexpr const std::size_t kMaxS3Keys = 1000;
29void SaveMeta(clients::
http::Headers& headers,
const ClientImpl::Meta& meta) {
30 for (
const auto& [header, value] : meta) {
31 headers[kMeta + header] = value;
35void ReadMeta(
const clients::
http::Headers& headers,
ClientImpl::Meta& meta) {
36 for (
const auto& [header, value] : headers) {
37 if (boost::istarts_with(header, kMeta)) {
38 meta[header.substr(kMeta.length())] = value;
43void SaveTags(clients::
http::Headers& headers,
const std::vector<ClientImpl::Tag>& tags) {
45 for (
const auto& [key, value] : tags) {
46 size += key.size() + value.size() + 2;
48 std::string tag_values;
49 tag_values.reserve(size);
50 for (
const auto& [key, value] : tags) {
51 tag_values.append(key);
52 tag_values.append(
"=");
53 tag_values.append(value);
54 tag_values.append(
"&");
56 if (!tag_values.empty()) {
58 tag_values.pop_back();
60 headers[kTagging] = std::move(tag_values);
63void AddQueryParamsToPresignedUrl(
64 std::ostringstream& generated_url,
69 if (!req.req.empty()) {
70 generated_url <<
"/" + req.req;
73 auto params = authenticator->Sign(req, expires_at);
75 if (!params.empty()) {
77 generated_url << USERVER_NAMESPACE::http::MakeQuery(params);
81std::string GeneratePresignedUrl(
83 std::string_view host,
84 std::string_view protocol,
85 const std::chrono::system_clock::time_point& expires_at,
88 std::ostringstream generated_url;
91 generated_url << protocol << request.bucket <<
"." << host;
92 const auto expires_at_time_t = std::chrono::system_clock::to_time_t(expires_at);
93 AddQueryParamsToPresignedUrl(generated_url, expires_at_time_t, request, authenticator);
94 return generated_url.str();
97std::vector<ObjectMeta> ParseS3ListResponse(std::string_view s3_response) {
98 std::vector<ObjectMeta> result;
99 pugi::xml_document xml;
100 pugi::xml_parse_result parse_result = xml.load_string(s3_response.data());
101 if (parse_result.status != pugi::status_ok) {
102 throw ListBucketError(fmt::format(
103 "Failed to parse S3 list response as xml, error: {}, response: {}", parse_result.description(), s3_response
107 const auto items = xml.child(
"ListBucketResult").children(
"Contents");
108 for (
const auto& item : items) {
109 const auto key = item.child(
"Key").child_value();
110 const auto size = std::stoull(item.child(
"Size").child_value());
111 const auto last_modified = item.child(
"LastModified").child_value();
112 result.push_back(ObjectMeta{key, size, last_modified});
114 }
catch (
const pugi::xpath_exception& ex) {
115 throw ListBucketError(
116 fmt::format(
"Bad xml structure for S3 list response, error: {}, response: {}", ex.what(), s3_response)
122std::vector<std::string> ParseS3DirectoriesListResponse(std::string_view s3_response) {
123 std::vector<std::string> result;
124 pugi::xml_document xml;
125 pugi::xml_parse_result parse_result = xml.load_string(s3_response.data());
126 if (parse_result.status != pugi::status_ok) {
127 throw ListBucketError(fmt::format(
128 "Failed to parse S3 directories list response as xml, error: {}, "
130 parse_result.description(),
135 const auto items = xml.child(
"ListBucketResult").children(
"CommonPrefixes");
136 for (
const auto& item : items) {
137 result.push_back(item.child(
"Prefix").child_value());
139 }
catch (
const pugi::xpath_exception& ex) {
140 throw ListBucketError(fmt::format(
141 "Bad xml structure for S3 directories list response, error: {}, "
159 : conn_(std::move(s3conn)), authenticator_{std::move(authenticator)}, bucket_(std::move(bucket)) {}
168 std::static_pointer_cast<authenticators::Authenticator>(std::move(authenticator)),
172std::string_view
ClientImpl::GetBucketName()
const {
return bucket_; }
175 std::string_view path,
177 const std::optional<Meta>& meta,
178 std::string_view content_type,
179 const std::optional<std::string>& content_disposition,
180 const std::optional<std::vector<Tag>>& tags
182 auto req = api_methods::PutObject(
190 if (meta.has_value()) {
191 SaveMeta(req.headers, meta.value());
193 if (tags.has_value()) {
194 SaveTags(req.headers, tags.value());
196 return RequestApi(req,
"put_object");
199void ClientImpl::DeleteObject(std::string_view path)
const {
200 auto req = api_methods::DeleteObject(bucket_, path);
201 RequestApi(req,
"delete_object");
204std::optional<std::string>
ClientImpl::GetObject(
205 std::string_view path,
206 std::optional<std::string> version,
211 return std::make_optional(TryGetObject(path, std::move(version), headers_data, headers_request));
213 if (e.code() == 404) {
214 LOG_INFO() <<
"Can't get object with path: " << path <<
", object not found:" << e.what();
216 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
219 }
catch (
const std::exception& e) {
220 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
226 std::string_view path,
227 std::optional<std::string> version,
231 auto req = api_methods::GetObject(bucket_, path, std::move(version));
232 return RequestApi(req,
"get_object", headers_data, headers_request);
235std::optional<std::string>
ClientImpl::GetPartialObject(
236 std::string_view path,
237 std::string_view range,
238 std::optional<std::string> version,
243 return std::make_optional(TryGetPartialObject(path, range, std::move(version), headers_data, headers_request));
245 if (e.code() == 404) {
246 LOG_INFO() <<
"Can't get object with path: " << path <<
", object not found:" << e.what();
248 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
251 }
catch (
const std::exception& e) {
252 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
258 std::string_view path,
259 std::string_view range,
260 std::optional<std::string> version,
264 auto req = api_methods::GetObject(bucket_, path, std::move(version));
265 api_methods::SetRange(req, range);
266 return RequestApi(req,
"get_object", headers_data, headers_request);
272 auto req = api_methods::GetObjectHead(bucket_, path);
274 RequestApi(req,
"get_object_head", &headers_data, headers_request);
275 }
catch (
const std::exception& e) {
276 LOG_INFO() <<
"Can't get object with path: " << path <<
", error:" << e.what();
279 return std::make_optional(std::move(headers_data));
282[[deprecated]] std::string
ClientImpl::GenerateDownloadUrl(std::string_view path, time_t expires_at,
bool use_ssl)
284 auto req = api_methods::GetObject(bucket_, path);
286 std::ostringstream generated_url;
287 auto host = conn_->GetHost();
288 if (host.find(
"://") == std::string::npos) {
289 generated_url << (use_ssl ?
"https" :
"http") <<
"://";
291 generated_url << host;
293 if (!req.bucket.empty()) {
294 generated_url <<
"/" + req.bucket;
296 AddQueryParamsToPresignedUrl(generated_url, expires_at, req, authenticator_);
297 return generated_url.str();
300std::string
ClientImpl::GenerateDownloadUrlVirtualHostAddressing(
301 std::string_view path,
302 const std::chrono::system_clock::time_point& expires_at,
303 std::string_view protocol
305 auto req = api_methods::GetObject(bucket_, path);
306 if (req.bucket.empty()) {
307 throw NoBucketError(
"presigned url for empty bucket string");
309 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
312std::string
ClientImpl::GenerateUploadUrlVirtualHostAddressing(
313 std::string_view data,
314 std::string_view content_type,
315 std::string_view path,
316 const std::chrono::system_clock::time_point& expires_at,
317 std::string_view protocol
319 auto req = api_methods::PutObject(bucket_, path, std::string{data}, content_type);
320 if (req.bucket.empty()) {
321 throw NoBucketError(
"presigned url for empty bucket string");
323 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
327 if (!authenticator_) {
332 auto auth_headers = authenticator_->Auth(request);
335 auto it = std::find_if(
336 auth_headers.cbegin(),
338 [&request](
const decltype(auth_headers)::value_type& header) {
339 return request.headers.count(std::get<0>(header));
343 if (it != auth_headers.cend()) {
344 throw AuthHeaderConflictError{std::string{
"Conflict with auth header: "} + it->first};
348 request.headers.insert(
349 std::make_move_iterator(std::begin(auth_headers)), std::make_move_iterator(std::end(auth_headers))
355 std::string_view method_name,
361 auto response = conn_->RequestApi(request, method_name);
364 if (headers_request.need_meta) {
365 headers_data->meta.emplace();
366 ReadMeta(response->headers(), *headers_data->meta);
369 if (headers_request.headers) {
370 headers_data->headers.emplace();
371 for (
const auto& header : *headers_request.headers) {
372 if (
auto it = response->headers().find(header); it != response->headers().end()) {
373 headers_data->headers->emplace(it->first, it->second);
379 return response->body();
382std::optional<std::string>
383ClientImpl::ListBucketContents(std::string_view path,
int max_keys, std::string marker, std::string delimiter)
const {
384 auto req = api_methods::ListBucketContents(bucket_, path, max_keys, marker, delimiter);
385 std::string reply = RequestApi(req,
"list_bucket_contents");
389 return std::optional<std::string>{std::move(reply)};
392std::vector<ObjectMeta>
ClientImpl::ListBucketContentsParsed(std::string_view path_prefix)
const {
393 std::vector<ObjectMeta> result;
395 std::string marker =
"";
396 bool is_finished =
false;
397 while (!is_finished) {
398 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker, {});
400 LOG_WARNING() <<
"Empty S3 bucket listing response for path prefix " << path_prefix;
403 auto response_result = ParseS3ListResponse(*response);
404 if (response_result.empty()) {
407 if (response_result.size() < kMaxS3Keys) {
412 std::make_move_iterator(response_result.begin()),
413 std::make_move_iterator(response_result.end())
415 marker = result.back().key;
420std::vector<std::string>
ClientImpl::ListBucketDirectories(std::string_view path_prefix)
const {
421 std::vector<std::string> result;
423 std::string marker =
"";
424 bool is_finished =
false;
425 while (!is_finished) {
426 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker,
"/");
428 LOG_WARNING() <<
"Empty S3 directory bucket listing response "
433 auto response_result = ParseS3DirectoriesListResponse(*response);
434 if (response_result.empty()) {
437 if (response_result.size() < kMaxS3Keys) {
442 std::make_move_iterator(response_result.begin()),
443 std::make_move_iterator(response_result.end())
445 marker = result.back();
452 std::string_view key_from,
453 std::string_view bucket_to,
454 std::string_view key_to,
455 const std::optional<Meta>& meta
457 const auto object_head = [&] {
458 HeaderDataRequest header_request;
459 header_request.headers.emplace();
460 header_request.headers->emplace(USERVER_NAMESPACE::http::headers::kContentType);
461 header_request.need_meta =
false;
462 return GetObjectHead(key_from, header_request);
465 USERVER_NAMESPACE::
utils::LogErrorAndThrow(
"S3Api : Failed to get object head");
468 const auto content_type = [&object_head]() -> std::optional<std::string> {
469 if (!object_head->headers) {
473 return USERVER_NAMESPACE::utils::FindOptional(
474 *object_head->headers, USERVER_NAMESPACE::http::headers::kContentType
478 USERVER_NAMESPACE::
utils::LogErrorAndThrow(
"S3Api : Object head is missing `content-type` header");
481 auto req = api_methods::CopyObject(bucket_, key_from, bucket_to, key_to, *content_type);
483 SaveMeta(req.headers, *meta);
485 return RequestApi(req,
"copy_object");
489ClientImpl::CopyObject(std::string_view key_from, std::string_view key_to,
const std::optional<Meta>& meta) {
490 return CopyObject(key_from, bucket_, key_to, meta);
493ClientPtr GetS3Client(
498 return GetS3Client(s3conn, std::static_pointer_cast<authenticators::Authenticator>(authenticator), bucket);
501ClientPtr GetS3Client(
506 return std::static_pointer_cast<Client>(std::make_shared<ClientImpl>(s3conn, authenticator, bucket));