1#include <s3api/clients/client.hpp>
8#include <boost/algorithm/string.hpp>
19#include <s3api/s3_connection.hpp>
20#include <s3api/s3api_methods.hpp>
22USERVER_NAMESPACE_BEGIN
27const std::string kMeta =
"x-amz-meta-";
28const std::string kTagging =
"X-Amz-Tagging";
29constexpr const std::size_t kMaxS3Keys = 1000;
31constexpr http::headers::PredefinedHeader kEtagHeader{
"ETag"};
34 for (
const auto& [header, value] : meta) {
35 headers[kMeta + header] = value;
40 for (
const auto& [header, value] : headers) {
41 if (boost::istarts_with(header, kMeta)) {
42 meta[header.substr(kMeta.length())] = value;
49 for (
const auto& [key, value] : tags) {
50 size += key.size() + value.size() + 2;
52 std::string tag_values;
53 tag_values.reserve(size);
54 for (
const auto& [key, value] : tags) {
55 tag_values.append(key);
56 tag_values.append(
"=");
57 tag_values.append(value);
58 tag_values.append(
"&");
60 if (!tag_values.empty()) {
62 tag_values.pop_back();
64 headers[kTagging] = std::move(tag_values);
67void AddQueryParamsToPresignedUrl(
68 std::ostringstream& generated_url,
71 std::shared_ptr<authenticators::Authenticator> authenticator
73 if (!req.req.empty()) {
74 generated_url <<
"/" + req.req;
77 auto params = authenticator->Sign(req, expires_at);
79 if (!params.empty()) {
81 generated_url << USERVER_NAMESPACE::http::MakeQuery(params);
85std::string_view GetEndpointPath(std::string_view endpoint) {
86 const auto scheme_pos = endpoint.find(
"://");
87 if (scheme_pos != std::string_view::npos) {
88 endpoint.remove_prefix(scheme_pos + 3);
91 const auto path_pos = endpoint.find(
'/');
92 if (path_pos == std::string_view::npos) {
96 auto path = endpoint.substr(path_pos);
97 if (path.ends_with(
'/')) {
98 path.remove_suffix(1);
103std::string GeneratePresignedUrl(
105 std::string_view host,
106 std::string_view protocol,
107 const std::chrono::system_clock::time_point& expires_at,
108 std::shared_ptr<authenticators::Authenticator> authenticator
110 std::ostringstream generated_url;
113 auto& host_header = request.headers[USERVER_NAMESPACE::http::headers::kHost];
114 host_header = S3Connection::MakeHostHeader(host, request.bucket);
115 generated_url << protocol << host_header << GetEndpointPath(host);
117 const auto expires_at_time_t = std::chrono::system_clock::to_time_t(expires_at);
118 AddQueryParamsToPresignedUrl(generated_url, expires_at_time_t, request, std::move(authenticator));
119 return generated_url.str();
122bool IsS3ResponseTruncated(
const pugi::xml_node& list_bucket_result) {
123 const auto is_truncated = list_bucket_result.child(
"IsTruncated").child_value();
124 return std::string_view{is_truncated} ==
"true";
127std::vector<ObjectMeta> ParseS3ListResponse(utils::zstring_view s3_response,
bool& is_truncated) {
128 std::vector<ObjectMeta> result;
129 pugi::xml_document xml;
130 const pugi::xml_parse_result parse_result = xml.load_string(s3_response.c_str());
131 if (parse_result.status != pugi::status_ok) {
133 "Failed to parse S3 list response as xml, error: {}, response: {}",
134 parse_result.description(),
139 const auto list_bucket_result = xml.child(
"ListBucketResult");
140 is_truncated = IsS3ResponseTruncated(list_bucket_result);
142 const auto items = list_bucket_result.children(
"Contents");
143 for (
const auto& item : items) {
144 const auto key = item.child(
"Key").child_value();
145 const auto size = std::stoull(item.child(
"Size").child_value());
146 const auto last_modified = item.child(
"LastModified").child_value();
147 result.push_back(
ObjectMeta{key, size, last_modified});
149 }
catch (
const pugi::xpath_exception& ex) {
151 fmt::format(
"Bad xml structure for S3 list response, error: {}, response: {}", ex.what(), s3_response)
157std::vector<std::string> ParseS3DirectoriesListResponse(utils::zstring_view s3_response,
bool& is_truncated) {
158 std::vector<std::string> result;
159 pugi::xml_document xml;
160 const pugi::xml_parse_result parse_result = xml.load_string(s3_response.c_str());
161 if (parse_result.status != pugi::status_ok) {
163 "Failed to parse S3 directories list response as xml, error: {}, "
165 parse_result.description(),
170 const auto list_bucket_result = xml.child(
"ListBucketResult");
171 is_truncated = IsS3ResponseTruncated(list_bucket_result);
173 const auto items = list_bucket_result.children(
"CommonPrefixes");
174 for (
const auto& item : items) {
175 result.push_back(item.child(
"Prefix").child_value());
177 }
catch (
const pugi::xpath_exception& ex) {
179 "Bad xml structure for S3 directories list response, error: {}, "
190void ClientImpl::UpdateConfig(
ConnectionCfg&& config) { conn_->UpdateConfig(std::move(config)); }
192ClientImpl::ClientImpl(
193 std::shared_ptr<S3Connection> s3conn,
194 std::shared_ptr<authenticators::Authenticator> authenticator,
197 : conn_(std::move(s3conn)),
198 authenticator_{std::move(authenticator)},
199 bucket_(std::move(bucket))
202ClientImpl::ClientImpl(
203 std::shared_ptr<S3Connection> s3conn,
204 std::shared_ptr<authenticators::AccessKey> authenticator,
209 std::static_pointer_cast<authenticators::Authenticator>(
std::move(authenticator)),
214std::string_view ClientImpl::GetBucketName()
const {
return bucket_; }
216std::string ClientImpl::PutObject(
217 std::string_view path,
219 const std::optional<Meta>&
meta,
220 std::string_view content_type,
221 const std::optional<std::string>& content_disposition,
222 const std::optional<std::vector<Tag>>& tags
224 auto req = api_methods::PutObject(
232 if (
meta.has_value()) {
233 SaveMeta(req.headers,
meta.value());
235 if (tags.has_value()) {
236 SaveTags(req.headers, tags.value());
238 return RequestApi(req,
"put_object");
241void ClientImpl::DeleteObject(std::string_view path)
const {
242 auto req = api_methods::DeleteObject(bucket_, path);
243 RequestApi(req,
"delete_object");
247 throw std::logic_error(
"This S3 client does not implement conditional writes");
251 std::string_view path,
253 const std::optional<std::string>& expected_etag,
254 const std::optional<Meta>&
meta
257 throw std::logic_error(
"This S3 client does not implement conditional writes with metadata");
263 std::string_view path,
265 const std::optional<std::string>& expected_etag
271 std::string_view path,
273 const std::optional<std::string>& expected_etag,
274 const std::optional<Meta>&
meta
276 auto request = api_methods::PutObject(bucket_, path, std::move(data),
"application/json", std::nullopt);
278 if (expected_etag.value().empty()) {
279 throw std::invalid_argument(
"An S3 conditional-write ETag must not be empty");
281 request.headers[http::headers::kIfMatch] = expected_etag.value();
283 request.headers[http::headers::kIfNoneMatch] =
"*";
286 SaveMeta(request.headers, *
meta);
288 RequestApi(request,
"put_object_conditional");
291std::optional<std::string> ClientImpl::GetObject(
292 std::string_view path,
293 std::optional<std::string> version,
294 HeadersDataResponse* headers_data,
295 const HeaderDataRequest& headers_request
298 return std::make_optional(TryGetObject(path, std::move(version), headers_data, headers_request));
300 if (e.code() == 404) {
301 LOG_INFO() <<
"Can't get object with path: " << path <<
", object not found:" << e.what();
303 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
306 }
catch (
const std::exception& e) {
307 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
312std::string ClientImpl::TryGetObject(
313 std::string_view path,
314 std::optional<std::string> version,
315 HeadersDataResponse* headers_data,
316 const HeaderDataRequest& headers_request
318 auto req = api_methods::GetObject(bucket_, path, std::move(version));
319 return RequestApi(req,
"get_object", headers_data, headers_request);
322std::optional<std::string> ClientImpl::GetPartialObject(
323 std::string_view path,
324 std::string_view range,
325 std::optional<std::string> version,
326 HeadersDataResponse* headers_data,
327 const HeaderDataRequest& headers_request
330 return std::make_optional(TryGetPartialObject(path, range, std::move(version), headers_data, headers_request));
332 if (e.code() == 404) {
333 LOG_INFO() <<
"Can't get object with path: " << path <<
", object not found:" << e.what();
335 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
338 }
catch (
const std::exception& e) {
339 LOG_ERROR() <<
"Can't get object with path: " << path <<
", unknown error:" << e.what();
344std::string ClientImpl::TryGetPartialObject(
345 std::string_view path,
346 std::string_view range,
347 std::optional<std::string> version,
348 HeadersDataResponse* headers_data,
349 const HeaderDataRequest& headers_request
351 auto req = api_methods::GetObject(bucket_, path, std::move(version));
352 api_methods::SetRange(req, range);
353 return RequestApi(req,
"get_object", headers_data, headers_request);
356std::optional<ClientImpl::HeadersDataResponse> ClientImpl::GetObjectHead(
357 std::string_view path,
358 const HeaderDataRequest& headers_request
360 HeadersDataResponse headers_data;
361 auto req = api_methods::GetObjectHead(bucket_, path);
363 RequestApi(req,
"get_object_head", &headers_data, headers_request);
364 }
catch (
const std::exception& e) {
365 LOG_INFO() <<
"Can't get object with path: " << path <<
", error:" << e.what();
368 return std::make_optional(std::move(headers_data));
371[[deprecated]] std::string ClientImpl::GenerateDownloadUrl(std::string_view path, time_t expires_at,
bool use_ssl)
373 auto req = api_methods::GetObject(bucket_, path);
375 std::ostringstream generated_url;
376 auto host = conn_->GetHost();
378 if (
const auto scheme_pos = host.find(
"://"); scheme_pos == std::string::npos) {
379 generated_url << (use_ssl ?
"https" :
"http") <<
"://" << host;
380 req.headers[USERVER_NAMESPACE::http::headers::kHost] = host;
382 generated_url << host;
383 req.headers[USERVER_NAMESPACE::http::headers::kHost] = host.substr(scheme_pos + 3);
386 if (!req.bucket.empty()) {
387 generated_url <<
'/' << req.bucket;
390 AddQueryParamsToPresignedUrl(generated_url, expires_at, req, authenticator_);
391 return generated_url.str();
394std::string ClientImpl::GenerateDownloadUrlVirtualHostAddressing(
395 std::string_view path,
396 const std::chrono::system_clock::time_point& expires_at,
397 std::string_view protocol
399 auto req = api_methods::GetObject(bucket_, path);
400 if (req.bucket.empty()) {
401 throw NoBucketError(
"presigned url for empty bucket string");
403 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
406std::string ClientImpl::GenerateUploadUrlVirtualHostAddressing(
407 std::string_view data,
408 std::string_view content_type,
409 std::string_view path,
410 const std::chrono::system_clock::time_point& expires_at,
411 std::string_view protocol
413 auto req = api_methods::PutObject(bucket_, path, std::string{data}, content_type);
414 if (req.bucket.empty()) {
415 throw NoBucketError(
"presigned url for empty bucket string");
417 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
420void ClientImpl::Auth(Request& request)
const {
421 if (!authenticator_) {
426 auto auth_headers = authenticator_->Auth(request);
429 auto it = std::ranges::find_if(auth_headers, [&request](
const auto& header) {
430 return request.headers.contains(header.first);
433 if (it != auth_headers.cend()) {
434 throw AuthHeaderConflictError{std::string{
"Conflict with auth header: "} + it->first};
439 .insert(std::make_move_iterator(std::begin(auth_headers)), std::make_move_iterator(std::end(auth_headers)));
442std::string ClientImpl::RequestApi(
444 std::string_view method_name,
445 HeadersDataResponse* headers_data,
446 const HeaderDataRequest& headers_request
448 request.headers[USERVER_NAMESPACE::http::headers::kHost] = conn_->GetHostHeader(request);
451 auto response = conn_->RequestApi(std::move(request), method_name);
454 if (headers_request.need_meta) {
455 headers_data->meta.emplace();
456 ReadMeta(response->headers(), *headers_data->meta);
458 if (headers_request.headers) {
459 headers_data->headers.emplace();
460 for (
const auto& header : *headers_request.headers) {
461 if (
auto it = response->headers().find(header); it != response->headers().end()) {
462 headers_data->headers->emplace(it->first, it->second);
468 if (response.use_count() == 1) {
469 return std::move(*response).body();
471 return response->body();
474std::optional<std::string> ClientImpl::ListBucketContents(
475 std::string_view path,
478 std::string delimiter
480 auto req = api_methods::ListBucketContents(bucket_, path, max_keys, marker, delimiter);
481 std::string reply = RequestApi(req,
"list_bucket_contents");
485 return std::optional<std::string>{std::move(reply)};
488std::vector<ObjectMeta> ClientImpl::ListBucketContentsParsed(std::string_view path_prefix)
const {
489 std::vector<ObjectMeta> result;
491 std::string marker{};
492 bool is_finished =
false;
493 while (!is_finished) {
494 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker, {});
496 LOG_WARNING() <<
"Empty S3 bucket listing response for path prefix " << path_prefix;
500 bool is_truncated =
false;
501 auto response_result = ParseS3ListResponse(*response, is_truncated);
502 if (response_result.empty()) {
510 std::make_move_iterator(response_result.begin()),
511 std::make_move_iterator(response_result.end())
513 marker = result.back().key;
518std::vector<std::string> ClientImpl::ListBucketDirectories(std::string_view path_prefix)
const {
519 std::vector<std::string> result;
521 std::string marker{};
522 bool is_finished =
false;
523 while (!is_finished) {
524 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker,
"/");
526 LOG_WARNING() <<
"Empty S3 directory bucket listing response for path prefix " << path_prefix;
530 bool is_truncated =
false;
531 auto response_result = ParseS3DirectoriesListResponse(*response, is_truncated);
532 if (response_result.empty()) {
540 std::make_move_iterator(response_result.begin()),
541 std::make_move_iterator(response_result.end())
543 marker = result.back();
549std::string ClientImpl::CopyObject(
550 std::string_view key_from,
551 std::string_view bucket_to,
552 std::string_view key_to,
553 const std::optional<Meta>&
meta
555 const auto object_head = [&] {
556 HeaderDataRequest header_request;
557 header_request.headers.emplace();
558 header_request.headers->emplace(USERVER_NAMESPACE::http::headers::kContentType);
559 header_request.need_meta =
false;
560 return GetObjectHead(key_from, header_request);
563 USERVER_NAMESPACE::utils::LogErrorAndThrow(
"S3Api : Failed to get object head");
566 const auto content_type = [&object_head]() -> std::optional<std::string> {
567 if (!object_head->headers) {
571 return USERVER_NAMESPACE::utils::FindOptional(
572 *object_head->headers,
573 USERVER_NAMESPACE::http::headers::kContentType
577 USERVER_NAMESPACE::utils::LogErrorAndThrow(
"S3Api : Object head is missing `content-type` header");
580 auto req = api_methods::CopyObject(bucket_, key_from, bucket_to, key_to, *content_type);
582 SaveMeta(req.headers, *
meta);
584 return RequestApi(req,
"copy_object");
587std::string ClientImpl::CopyObject(
588 std::string_view key_from,
589 std::string_view key_to,
590 const std::optional<Meta>&
meta
592 return CopyObject(key_from, bucket_, key_to,
meta);
599 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
600 const auto api_response_body = RequestApi(api_request,
"create_multipart_upload");
601 return multipart_upload::InitiateMultipartUploadResult::Parse(api_response_body);
604 fmt::format(
"failed to parse CreateMultipartUpload action response - {}; key: {}", exc.what(), request.key)
610 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
615 RequestApi(api_request,
"upload_part", &response_headers_data, expected_headers);
616 if (!response_headers_data.headers) {
619 const auto iter = response_headers_data.headers->find(kEtagHeader);
620 if (iter == response_headers_data.headers->end()) {
623 if (iter->second.empty()) {
626 return {std::move(iter->second)};
630 "failed to parse UploadPart action response - {}; upload_id '{}'; key '{}'",
641 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
642 const auto api_response_body = RequestApi(api_request,
"complete_multipart_upload");
643 return multipart_upload::CompleteMultipartUploadResult::Parse(api_response_body);
646 "failed to parse CompleteMultipartUpload action response - {}; upload_id '{}'; key '{}'",
654 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
655 RequestApi(api_request,
"abort_multipart_upload");
660 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
661 const auto api_response_body = RequestApi(api_request,
"list_parts");
662 return multipart_upload::ListPartsResult::Parse(api_response_body);
665 "failed to parse ListParts action response - {}; upload_id '{}'; key '{}'",
676 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
677 const auto api_response_body = RequestApi(api_request,
"list_multipart_uploads");
678 return multipart_upload::ListMultipartUploadsResult::Parse(api_response_body);
680 throw MultipartUploadError(fmt::format(
"failed to parse ListMultipartUploads action response - {}", exc.what()));
683ClientPtr GetS3Client(
684 std::shared_ptr<S3Connection> s3conn,
685 std::shared_ptr<authenticators::AccessKey> authenticator,
690 std::static_pointer_cast<authenticators::Authenticator>(authenticator),
695ClientPtr GetS3Client(
696 std::shared_ptr<S3Connection> s3conn,
697 std::shared_ptr<authenticators::Authenticator> authenticator,
700 return std::static_pointer_cast<Client>(std::make_shared<ClientImpl>(s3conn, authenticator, bucket));