1#include <s3api/clients/client.hpp>
7#include <boost/algorithm/string.hpp>
10#include <userver/http/common_headers.hpp>
11#include <userver/http/url.hpp>
12#include <userver/logging/log.hpp>
13#include <userver/utils/algo.hpp>
14#include <userver/utils/exception.hpp>
16#include <userver/s3api/authenticators/access_key.hpp>
18#include <s3api/s3_connection.hpp>
19#include <s3api/s3api_methods.hpp>
21USERVER_NAMESPACE_BEGIN
26const std::string kMeta =
"x-amz-meta-";
27const std::string kTagging =
"X-Amz-Tagging";
28constexpr const std::size_t kMaxS3Keys = 1000;
30constexpr http::
headers::PredefinedHeader kEtagHeader{
"ETag"};
32void SaveMeta(clients::http::Headers& headers,
const ClientImpl::Meta& meta) {
33 for (
const auto& [header, value] : meta) {
34 headers
[kMeta + header
] = value;
38void ReadMeta(
const clients::http::Headers& headers,
ClientImpl::Meta& meta) {
39 for (
const auto& [header, value] : headers) {
40 if (boost::istarts_with(header, kMeta)) {
41 meta
[header.substr(kMeta.length())
] = value;
46void SaveTags(clients::http::Headers& headers,
const std::vector<
ClientImpl::
Tag>& tags) {
48 for (
const auto& [key, value] : tags) {
49 size += key.size() + value.size() + 2;
51 std::string tag_values;
52 tag_values.reserve(size);
53 for (
const auto& [key, value] : tags) {
54 tag_values.append(key);
55 tag_values.append(
"=");
56 tag_values.append(value);
57 tag_values.append(
"&");
59 if (!tag_values.empty()) {
61 tag_values.pop_back();
63 headers
[kTagging
] = std::move(tag_values);
66void AddQueryParamsToPresignedUrl(
67 std::ostringstream& generated_url,
72 if (!req.req.empty()) {
73 generated_url <<
"/" + req.req;
76 auto params = authenticator->Sign(req, expires_at);
78 if (!params.empty()) {
80 generated_url << USERVER_NAMESPACE::http::MakeQuery(params);
84std::string_view GetEndpointPath(std::string_view endpoint) {
85 const auto scheme_pos = endpoint.find(
"://");
86 if (scheme_pos != std::string_view::npos) {
87 endpoint.remove_prefix(scheme_pos + 3);
90 const auto path_pos = endpoint.find(
'/');
91 if (path_pos == std::string_view::npos) {
95 auto path = endpoint.substr(path_pos);
96 if (path.ends_with(
'/')) {
97 path.remove_suffix(1);
102std::string GeneratePresignedUrl(
104 std::string_view host,
105 std::string_view protocol,
106 const std::chrono::system_clock::time_point& expires_at,
109 std::ostringstream generated_url;
112 auto& host_header = request.headers
[USERVER_NAMESPACE::http::
headers::kHost
];
113 host_header =
S3Connection::MakeHostHeader(host, request.bucket);
114 generated_url << protocol << host_header << GetEndpointPath(host);
116 const auto expires_at_time_t = std::chrono::system_clock::to_time_t(expires_at);
117 AddQueryParamsToPresignedUrl(generated_url, expires_at_time_t, request, std::move(authenticator));
118 return generated_url.str();
121bool IsS3ResponseTruncated(
const pugi::xml_node& list_bucket_result) {
122 const auto is_truncated = list_bucket_result.child(
"IsTruncated").child_value();
123 return std::string_view{is_truncated} ==
"true";
126std::vector<
ObjectMeta> ParseS3ListResponse(
utils::zstring_view s3_response,
bool& is_truncated) {
128 pugi::xml_document xml;
129 const pugi::xml_parse_result parse_result = xml.load_string(s3_response.c_str());
130 if (parse_result.status != pugi::status_ok) {
132 "Failed to parse S3 list response as xml, error: {}, response: {}",
133 parse_result.description(),
138 const auto list_bucket_result = xml.child(
"ListBucketResult");
139 is_truncated = IsS3ResponseTruncated(list_bucket_result);
141 const auto items = list_bucket_result.children(
"Contents");
142 for (
const auto& item : items) {
143 const auto key = item.child(
"Key").child_value();
144 const auto size = std::stoull(item.child(
"Size").child_value());
145 const auto last_modified = item.child(
"LastModified").child_value();
146 result.push_back(
ObjectMeta{key, size, last_modified});
148 }
catch (
const pugi::xpath_exception& ex) {
150 fmt::format(
"Bad xml structure for S3 list response, error: {}, response: {}", ex.what(), s3_response)
156std::vector<std::string> ParseS3DirectoriesListResponse(
utils::zstring_view s3_response,
bool& is_truncated) {
157 std::vector<std::string> result;
158 pugi::xml_document xml;
159 const pugi::xml_parse_result parse_result = xml.load_string(s3_response.c_str());
160 if (parse_result.status != pugi::status_ok) {
162 "Failed to parse S3 directories list response as xml, error: {}, "
164 parse_result.description(),
169 const auto list_bucket_result = xml.child(
"ListBucketResult");
170 is_truncated = IsS3ResponseTruncated(list_bucket_result);
172 const auto items = list_bucket_result.children(
"CommonPrefixes");
173 for (
const auto& item : items) {
174 result.push_back(item.child(
"Prefix").child_value());
176 }
catch (
const pugi::xpath_exception& ex) {
178 "Bad xml structure for S3 directories list response, error: {}, "
196 : conn_(std::move(s3conn)),
197 authenticator_{std::move(authenticator)},
198 bucket_(std::move(bucket))
213std::string_view
ClientImpl::GetBucketName()
const {
return bucket_; }
216 std::string_view path,
218 const std::optional<Meta>& meta,
219 std::string_view content_type,
220 const std::optional<std::string>& content_disposition,
221 const std::optional<std::vector<
Tag>>& tags
223 auto req = api_methods::PutObject(
231 if (meta.has_value()) {
232 SaveMeta(req.headers, meta.value());
234 if (tags.has_value()) {
235 SaveTags(req.headers, tags.value());
237 return RequestApi(req,
"put_object");
240void ClientImpl::DeleteObject(std::string_view path)
const {
241 auto req = api_methods::DeleteObject(bucket_, path);
242 RequestApi(req,
"delete_object");
246 throw std::logic_error(
"This S3 client does not implement conditional writes");
250 std::string_view path,
252 const std::optional<std::string>& expected_etag,
253 const std::optional<Meta>& meta
256 throw std::logic_error(
"This S3 client does not implement conditional writes with metadata");
262 std::string_view path,
264 const std::optional<std::string>& expected_etag
270 std::string_view path,
272 const std::optional<std::string>& expected_etag,
273 const std::optional<Meta>& meta
275 auto request = api_methods::PutObject(bucket_, path, std::move(data),
"application/json", std::nullopt);
277 if (expected_etag.value().empty()) {
278 throw std::invalid_argument(
"An S3 conditional-write ETag must not be empty");
280 request.headers
[http::
headers::kIfMatch
] = expected_etag.value();
282 request.headers
[http::
headers::kIfNoneMatch
] =
"*";
285 SaveMeta(request.headers, *meta);
287 RequestApi(request,
"put_object_conditional");
290std::optional<std::string>
ClientImpl::GetObject(
291 std::string_view path,
292 std::optional<std::string> version,
297 return std::make_optional(TryGetObject(path, std::move(version), headers_data, headers_request));
299 if (e.code() == 404) {
300 LOG_INFO() <<
"Can't get object with path: " << path <<
", object not found:" << e.what();
302 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
305 }
catch (
const std::exception& e) {
306 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
312 std::string_view path,
313 std::optional<std::string> version,
317 auto req = api_methods::GetObject(bucket_, path, std::move(version));
318 return RequestApi(req,
"get_object", headers_data, headers_request);
321std::optional<std::string>
ClientImpl::GetPartialObject(
322 std::string_view path,
323 std::string_view range,
324 std::optional<std::string> version,
329 return std::make_optional(TryGetPartialObject(path, range, std::move(version), headers_data, headers_request));
331 if (e.code() == 404) {
332 LOG_INFO() <<
"Can't get object with path: " << path <<
", object not found:" << e.what();
334 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
337 }
catch (
const std::exception& e) {
338 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
344 std::string_view path,
345 std::string_view range,
346 std::optional<std::string> version,
350 auto req = api_methods::GetObject(bucket_, path, std::move(version));
351 api_methods::SetRange(req, range);
352 return RequestApi(req,
"get_object", headers_data, headers_request);
356 std::string_view path,
360 auto req = api_methods::GetObjectHead(bucket_, path);
362 RequestApi(req,
"get_object_head", &headers_data, headers_request);
363 }
catch (
const std::exception& e) {
364 LOG_INFO() <<
"Can't get object with path: " << path <<
", error:" << e.what();
367 return std::make_optional(std::move(headers_data));
370[[deprecated]] std::string
ClientImpl::GenerateDownloadUrl(std::string_view path, time_t expires_at,
bool use_ssl)
372 auto req = api_methods::GetObject(bucket_, path);
374 std::ostringstream generated_url;
375 auto host = conn_->GetHost();
377 if (
const auto scheme_pos = host.find(
"://"); scheme_pos == std::string::npos) {
378 generated_url << (use_ssl ?
"https" :
"http") <<
"://" << host;
379 req.headers
[USERVER_NAMESPACE::http::
headers::kHost
] = host;
381 generated_url << host;
382 req.headers
[USERVER_NAMESPACE::http::
headers::kHost
] = host.substr(scheme_pos + 3);
385 if (!req.bucket.empty()) {
386 generated_url <<
'/' << req.bucket;
389 AddQueryParamsToPresignedUrl(generated_url, expires_at, req, authenticator_);
390 return generated_url.str();
393std::string
ClientImpl::GenerateDownloadUrlVirtualHostAddressing(
394 std::string_view path,
395 const std::chrono::system_clock::time_point& expires_at,
396 std::string_view protocol
398 auto req = api_methods::GetObject(bucket_, path);
399 if (req.bucket.empty()) {
400 throw NoBucketError(
"presigned url for empty bucket string");
402 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
405std::string
ClientImpl::GenerateUploadUrlVirtualHostAddressing(
406 std::string_view data,
407 std::string_view content_type,
408 std::string_view path,
409 const std::chrono::system_clock::time_point& expires_at,
410 std::string_view protocol
412 auto req = api_methods::PutObject(bucket_, path, std::string{data}, content_type);
413 if (req.bucket.empty()) {
414 throw NoBucketError(
"presigned url for empty bucket string");
416 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
420 if (!authenticator_) {
425 auto auth_headers = authenticator_->Auth(request);
428 auto it = std::ranges::find_if(auth_headers, [&request](
const auto& header) {
429 return request.headers.contains(header.first);
432 if (it != auth_headers.cend()) {
438 .insert(std::make_move_iterator(std::begin(auth_headers))
, std::make_move_iterator(std::end(auth_headers))
);
443 std::string_view method_name,
447 request.headers
[USERVER_NAMESPACE::http::
headers::kHost
] = conn_->GetHostHeader(request);
450 auto response = conn_->RequestApi(request, method_name);
453 if (headers_request.need_meta) {
454 headers_data->meta.emplace();
455 ReadMeta(response->headers(), *headers_data->meta);
457 if (headers_request.headers) {
458 headers_data->headers.emplace();
459 for (
const auto& header : *headers_request.headers) {
460 if (
auto it = response->headers()
.find(header
); it != response->headers()
.end()) {
461 headers_data->headers->
emplace(it->first
, it->second
);
467 return response->body();
470std::optional<std::string>
ClientImpl::ListBucketContents(
471 std::string_view path,
474 std::string delimiter
476 auto req = api_methods::ListBucketContents(bucket_, path, max_keys, marker, delimiter);
477 std::string reply = RequestApi(req,
"list_bucket_contents");
481 return std::optional<std::string>{std::move(reply)};
484std::vector<
ObjectMeta>
ClientImpl::ListBucketContentsParsed(std::string_view path_prefix)
const {
487 std::string marker{};
488 bool is_finished =
false;
489 while (!is_finished) {
490 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker, {});
492 LOG_WARNING() <<
"Empty S3 bucket listing response for path prefix " << path_prefix;
496 bool is_truncated =
false;
497 auto response_result = ParseS3ListResponse(*response, is_truncated);
498 if (response_result.empty()) {
506 std::make_move_iterator(response_result.begin()),
507 std::make_move_iterator(response_result.end())
509 marker = result.back().key;
514std::vector<std::string>
ClientImpl::ListBucketDirectories(std::string_view path_prefix)
const {
515 std::vector<std::string> result;
517 std::string marker{};
518 bool is_finished =
false;
519 while (!is_finished) {
520 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker,
"/");
522 LOG_WARNING() <<
"Empty S3 directory bucket listing response for path prefix " << path_prefix;
526 bool is_truncated =
false;
527 auto response_result = ParseS3DirectoriesListResponse(*response, is_truncated);
528 if (response_result.empty()) {
536 std::make_move_iterator(response_result.begin()),
537 std::make_move_iterator(response_result.end())
539 marker = result.back();
546 std::string_view key_from,
547 std::string_view bucket_to,
548 std::string_view key_to,
549 const std::optional<Meta>& meta
551 const auto object_head = [&] {
553 header_request.headers.emplace();
554 header_request.headers->emplace(USERVER_NAMESPACE::http::
headers::kContentType);
555 header_request.need_meta =
false;
556 return GetObjectHead(key_from, header_request);
562 const auto content_type = [&object_head]() -> std::optional<std::string> {
563 if (!object_head->headers) {
568 *object_head->headers
,
569 USERVER_NAMESPACE::http::
headers::kContentType
576 auto req = api_methods::CopyObject(bucket_, key_from, bucket_to, key_to, *content_type);
578 SaveMeta(req.headers, *meta);
580 return RequestApi(req,
"copy_object");
584 std::string_view key_from,
585 std::string_view key_to,
586 const std::optional<Meta>& meta
588 return CopyObject(key_from, bucket_, key_to, meta);
595 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
596 const auto api_response_body = RequestApi(api_request,
"create_multipart_upload");
600 fmt::format(
"failed to parse CreateMultipartUpload action response - {}; key: {}", exc.what(), request.key)
606 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
611 RequestApi(api_request,
"upload_part", &response_headers_data, expected_headers);
612 if (!response_headers_data.headers) {
615 const auto iter = response_headers_data.headers->
find(kEtagHeader
);
616 if (iter == response_headers_data.headers->
end()) {
619 if (iter->second.empty()) {
622 return {std::move(iter->second)};
626 "failed to parse UploadPart action response - {}; upload_id '{}'; key '{}'",
637 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
638 const auto api_response_body = RequestApi(api_request,
"complete_multipart_upload");
642 "failed to parse CompleteMultipartUpload action response - {}; upload_id '{}'; key '{}'",
650 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
651 RequestApi(api_request,
"abort_multipart_upload");
656 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
657 const auto api_response_body = RequestApi(api_request,
"list_parts");
661 "failed to parse ListParts action response - {}; upload_id '{}'; key '{}'",
672 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
673 const auto api_response_body = RequestApi(api_request,
"list_multipart_uploads");
676 throw MultipartUploadError(
fmt::format(
"failed to parse ListMultipartUploads action response - {}", exc.what()));
679ClientPtr GetS3Client(
691ClientPtr GetS3Client(
696 return std::static_pointer_cast<
Client>(std::make_shared<
ClientImpl>(s3conn, authenticator, bucket));