userver: /data/code/userver/libraries/s3api/src/s3api/clients/client.cpp Source File
Loading...
Searching...
No Matches
client.cpp
1#include <s3api/clients/client.hpp>
2
3#include <sstream>
4#include <stdexcept>
5
6#include <fmt/format.h>
7#include <boost/algorithm/string.hpp>
8#include <pugixml.hpp>
9
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>
15
16#include <userver/s3api/authenticators/access_key.hpp>
17
18#include <s3api/s3_connection.hpp>
19#include <s3api/s3api_methods.hpp>
20
21USERVER_NAMESPACE_BEGIN
22
23namespace s3api {
24namespace {
25
26const std::string kMeta = "x-amz-meta-";
27const std::string kTagging = "X-Amz-Tagging";
28constexpr const std::size_t kMaxS3Keys = 1000;
29
30constexpr http::headers::PredefinedHeader kEtagHeader{"ETag"};
31
32void SaveMeta(clients::http::Headers& headers, const ClientImpl::Meta& meta) {
33 for (const auto& [header, value] : meta) {
34 headers[kMeta + header] = value;
35 }
36}
37
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;
42 }
43 }
44}
45
46void SaveTags(clients::http::Headers& headers, const std::vector<ClientImpl::Tag>& tags) {
47 size_t size = 0;
48 for (const auto& [key, value] : tags) {
49 size += key.size() + value.size() + 2;
50 }
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("&");
58 }
59 if (!tag_values.empty()) {
60 // pop last &
61 tag_values.pop_back();
62 }
63 headers[kTagging] = std::move(tag_values);
64}
65
66void AddQueryParamsToPresignedUrl(
67 std::ostringstream& generated_url,
68 time_t expires_at,
69 const Request& req,
70 std::shared_ptr<authenticators::Authenticator> authenticator
71) {
72 if (!req.req.empty()) {
73 generated_url << "/" + req.req;
74 }
75
76 auto params = authenticator->Sign(req, expires_at);
77
78 if (!params.empty()) {
79 generated_url << "?";
80 generated_url << USERVER_NAMESPACE::http::MakeQuery(params);
81 }
82}
83
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);
88 }
89
90 const auto path_pos = endpoint.find('/');
91 if (path_pos == std::string_view::npos) {
92 return {};
93 }
94
95 auto path = endpoint.substr(path_pos);
96 if (path.ends_with('/')) {
97 path.remove_suffix(1);
98 }
99 return path;
100}
101
102std::string GeneratePresignedUrl(
103 Request& request,
104 std::string_view host,
105 std::string_view protocol,
106 const std::chrono::system_clock::time_point& expires_at,
107 std::shared_ptr<authenticators::Authenticator> authenticator
108) {
109 std::ostringstream generated_url;
110 // both internal (s3.mds(t)) and private (s3-private)
111 // balancers support virtual host addressing and https
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);
115
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();
119}
120
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";
124}
125
126std::vector<ObjectMeta> ParseS3ListResponse(utils::zstring_view s3_response, bool& is_truncated) {
127 std::vector<ObjectMeta> result;
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) {
131 throw ListBucketError(fmt::format(
132 "Failed to parse S3 list response as xml, error: {}, response: {}",
133 parse_result.description(),
134 s3_response
135 ));
136 }
137 try {
138 const auto list_bucket_result = xml.child("ListBucketResult");
139 is_truncated = IsS3ResponseTruncated(list_bucket_result);
140
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});
147 }
148 } catch (const pugi::xpath_exception& ex) {
149 throw ListBucketError(
150 fmt::format("Bad xml structure for S3 list response, error: {}, response: {}", ex.what(), s3_response)
151 );
152 }
153 return result;
154}
155
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) {
161 throw ListBucketError(fmt::format(
162 "Failed to parse S3 directories list response as xml, error: {}, "
163 "response: {}",
164 parse_result.description(),
165 s3_response
166 ));
167 }
168 try {
169 const auto list_bucket_result = xml.child("ListBucketResult");
170 is_truncated = IsS3ResponseTruncated(list_bucket_result);
171
172 const auto items = list_bucket_result.children("CommonPrefixes");
173 for (const auto& item : items) {
174 result.push_back(item.child("Prefix").child_value());
175 }
176 } catch (const pugi::xpath_exception& ex) {
177 throw ListBucketError(fmt::format(
178 "Bad xml structure for S3 directories list response, error: {}, "
179 "response: {}",
180 ex.what(),
181 s3_response
182 ));
183 }
184 return result;
185}
186
187} // namespace
188
189void ClientImpl::UpdateConfig(ConnectionCfg&& config) { conn_->UpdateConfig(std::move(config)); }
190
191ClientImpl::ClientImpl(
192 std::shared_ptr<S3Connection> s3conn,
193 std::shared_ptr<authenticators::Authenticator> authenticator,
194 std::string bucket
195)
196 : conn_(std::move(s3conn)),
197 authenticator_{std::move(authenticator)},
198 bucket_(std::move(bucket))
199{}
200
201ClientImpl::ClientImpl(
202 std::shared_ptr<S3Connection> s3conn,
203 std::shared_ptr<authenticators::AccessKey> authenticator,
204 std::string bucket
205)
206 : ClientImpl(
207 std::move(s3conn),
208 std::static_pointer_cast<authenticators::Authenticator>(std::move(authenticator)),
209 std::move(bucket)
210 )
211{}
212
213std::string_view ClientImpl::GetBucketName() const { return bucket_; }
214
215std::string ClientImpl::PutObject(
216 std::string_view path, //
217 std::string data, //
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
222) const {
223 auto req = api_methods::PutObject( //
224 bucket_, //
225 path, //
226 std::move(data), //
227 content_type, //
228 content_disposition //
229 );
230
231 if (meta.has_value()) {
232 SaveMeta(req.headers, meta.value());
233 }
234 if (tags.has_value()) {
235 SaveTags(req.headers, tags.value());
236 }
237 return RequestApi(req, "put_object");
238}
239
240void ClientImpl::DeleteObject(std::string_view path) const {
241 auto req = api_methods::DeleteObject(bucket_, path);
242 RequestApi(req, "delete_object");
243}
244
245void Client::PutObjectConditional(std::string_view, std::string, const std::optional<std::string>&) const {
246 throw std::logic_error("This S3 client does not implement conditional writes");
247}
248
250 std::string_view path,
251 std::string data,
252 const std::optional<std::string>& expected_etag,
253 const std::optional<Meta>& meta
254) const {
255 if (meta && !meta->empty()) {
256 throw std::logic_error("This S3 client does not implement conditional writes with metadata");
257 }
258 PutObjectConditional(path, std::move(data), expected_etag);
259}
260
262 std::string_view path,
263 std::string data,
264 const std::optional<std::string>& expected_etag
265) const {
266 PutObjectConditional(path, std::move(data), expected_etag, std::nullopt);
267}
268
270 std::string_view path,
271 std::string data,
272 const std::optional<std::string>& expected_etag,
273 const std::optional<Meta>& meta
274) const {
275 auto request = api_methods::PutObject(bucket_, path, std::move(data), "application/json", std::nullopt);
276 if (expected_etag) {
277 if (expected_etag.value().empty()) {
278 throw std::invalid_argument("An S3 conditional-write ETag must not be empty");
279 }
280 request.headers[http::headers::kIfMatch] = expected_etag.value();
281 } else {
282 request.headers[http::headers::kIfNoneMatch] = "*";
283 }
284 if (meta) {
285 SaveMeta(request.headers, *meta);
286 }
287 RequestApi(request, "put_object_conditional");
288}
289
290std::optional<std::string> ClientImpl::GetObject(
291 std::string_view path,
292 std::optional<std::string> version,
293 HeadersDataResponse* headers_data,
294 const HeaderDataRequest& headers_request
295) const {
296 try {
297 return std::make_optional(TryGetObject(path, std::move(version), headers_data, headers_request));
298 } catch (const clients::http::HttpException& e) {
299 if (e.code() == 404) {
300 LOG_INFO() << "Can't get object with path: " << path << ", object not found:" << e.what();
301 } else {
302 LOG_ERROR() << "Can't get object with path: " << path << ", unknown error:" << e.what();
303 }
304 return std::nullopt;
305 } catch (const std::exception& e) {
306 LOG_ERROR() << "Can't get object with path: " << path << ", unknown error:" << e.what();
307 return std::nullopt;
308 }
309}
310
311std::string ClientImpl::TryGetObject(
312 std::string_view path,
313 std::optional<std::string> version,
314 HeadersDataResponse* headers_data,
315 const HeaderDataRequest& headers_request
316) const {
317 auto req = api_methods::GetObject(bucket_, path, std::move(version));
318 return RequestApi(req, "get_object", headers_data, headers_request);
319}
320
321std::optional<std::string> ClientImpl::GetPartialObject(
322 std::string_view path,
323 std::string_view range,
324 std::optional<std::string> version,
325 HeadersDataResponse* headers_data,
326 const HeaderDataRequest& headers_request
327) const {
328 try {
329 return std::make_optional(TryGetPartialObject(path, range, std::move(version), headers_data, headers_request));
330 } catch (const clients::http::HttpException& e) {
331 if (e.code() == 404) {
332 LOG_INFO() << "Can't get object with path: " << path << ", object not found:" << e.what();
333 } else {
334 LOG_ERROR() << "Can't get object with path: " << path << ", unknown error:" << e.what();
335 }
336 return std::nullopt;
337 } catch (const std::exception& e) {
338 LOG_ERROR() << "Can't get object with path: " << path << ", unknown error:" << e.what();
339 return std::nullopt;
340 }
341}
342
343std::string ClientImpl::TryGetPartialObject(
344 std::string_view path,
345 std::string_view range,
346 std::optional<std::string> version,
347 HeadersDataResponse* headers_data,
348 const HeaderDataRequest& headers_request
349) const {
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);
353}
354
355std::optional<ClientImpl::HeadersDataResponse> ClientImpl::GetObjectHead(
356 std::string_view path,
357 const HeaderDataRequest& headers_request
358) const {
359 HeadersDataResponse headers_data;
360 auto req = api_methods::GetObjectHead(bucket_, path);
361 try {
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();
365 return std::nullopt;
366 }
367 return std::make_optional(std::move(headers_data));
368}
369
370[[deprecated]] std::string ClientImpl::GenerateDownloadUrl(std::string_view path, time_t expires_at, bool use_ssl)
371 const {
372 auto req = api_methods::GetObject(bucket_, path);
373
374 std::ostringstream generated_url;
375 auto host = conn_->GetHost();
376
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;
380 } else {
381 generated_url << host;
382 req.headers[USERVER_NAMESPACE::http::headers::kHost] = host.substr(scheme_pos + 3);
383 }
384
385 if (!req.bucket.empty()) {
386 generated_url << '/' << req.bucket;
387 }
388
389 AddQueryParamsToPresignedUrl(generated_url, expires_at, req, authenticator_);
390 return generated_url.str();
391}
392
393std::string ClientImpl::GenerateDownloadUrlVirtualHostAddressing(
394 std::string_view path,
395 const std::chrono::system_clock::time_point& expires_at,
396 std::string_view protocol
397) const {
398 auto req = api_methods::GetObject(bucket_, path);
399 if (req.bucket.empty()) {
400 throw NoBucketError("presigned url for empty bucket string");
401 }
402 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
403}
404
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
411) const {
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");
415 }
416 return GeneratePresignedUrl(req, conn_->GetHost(), protocol, expires_at, authenticator_);
417}
418
419void ClientImpl::Auth(Request& request) const {
420 if (!authenticator_) {
421 // anonymous request
422 return;
423 }
424
425 auto auth_headers = authenticator_->Auth(request);
426
427 {
428 auto it = std::ranges::find_if(auth_headers, [&request](const auto& header) {
429 return request.headers.contains(header.first);
430 });
431
432 if (it != auth_headers.cend()) {
433 throw AuthHeaderConflictError{std::string{"Conflict with auth header: "} + it->first};
434 }
435 }
436
437 request.headers
438 .insert(std::make_move_iterator(std::begin(auth_headers)), std::make_move_iterator(std::end(auth_headers)));
439}
440
441std::string ClientImpl::RequestApi(
442 Request& request,
443 std::string_view method_name,
444 HeadersDataResponse* headers_data,
445 const HeaderDataRequest& headers_request
446) const {
447 request.headers[USERVER_NAMESPACE::http::headers::kHost] = conn_->GetHostHeader(request);
448 Auth(request);
449
450 auto response = conn_->RequestApi(request, method_name);
451
452 if (headers_data) {
453 if (headers_request.need_meta) {
454 headers_data->meta.emplace();
455 ReadMeta(response->headers(), *headers_data->meta);
456 }
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);
462 }
463 }
464 }
465 }
466
467 return response->body();
468}
469
470std::optional<std::string> ClientImpl::ListBucketContents(
471 std::string_view path,
472 int max_keys,
473 std::string marker,
474 std::string delimiter
475) const {
476 auto req = api_methods::ListBucketContents(bucket_, path, max_keys, marker, delimiter);
477 std::string reply = RequestApi(req, "list_bucket_contents");
478 if (reply.empty()) {
479 return std::nullopt;
480 }
481 return std::optional<std::string>{std::move(reply)};
482}
483
484std::vector<ObjectMeta> ClientImpl::ListBucketContentsParsed(std::string_view path_prefix) const {
485 std::vector<ObjectMeta> result;
486 // S3 doc: specifies the key to start with when listing objects in a bucket
487 std::string marker{};
488 bool is_finished = false;
489 while (!is_finished) {
490 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker, {});
491 if (!response) {
492 LOG_WARNING() << "Empty S3 bucket listing response for path prefix " << path_prefix;
493 break;
494 }
495
496 bool is_truncated = false;
497 auto response_result = ParseS3ListResponse(*response, is_truncated);
498 if (response_result.empty()) {
499 break;
500 }
501 if (!is_truncated) {
502 is_finished = true;
503 }
504 result.insert(
505 result.end(),
506 std::make_move_iterator(response_result.begin()),
507 std::make_move_iterator(response_result.end())
508 );
509 marker = result.back().key;
510 }
511 return result;
512}
513
514std::vector<std::string> ClientImpl::ListBucketDirectories(std::string_view path_prefix) const {
515 std::vector<std::string> result;
516 // S3 doc: specifies the key to start with when listing objects in a bucket
517 std::string marker{};
518 bool is_finished = false;
519 while (!is_finished) {
520 auto response = ListBucketContents(path_prefix, kMaxS3Keys, marker, "/");
521 if (!response) {
522 LOG_WARNING() << "Empty S3 directory bucket listing response for path prefix " << path_prefix;
523 break;
524 }
525
526 bool is_truncated = false;
527 auto response_result = ParseS3DirectoriesListResponse(*response, is_truncated);
528 if (response_result.empty()) {
529 break;
530 }
531 if (!is_truncated) {
532 is_finished = true;
533 }
534 result.insert(
535 result.end(),
536 std::make_move_iterator(response_result.begin()),
537 std::make_move_iterator(response_result.end())
538 );
539 marker = result.back();
540 }
541
542 return result;
543}
544
545std::string ClientImpl::CopyObject(
546 std::string_view key_from,
547 std::string_view bucket_to,
548 std::string_view key_to,
549 const std::optional<Meta>& meta
550) {
551 const auto object_head = [&] {
552 HeaderDataRequest header_request;
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);
557 }();
558 if (!object_head) {
559 USERVER_NAMESPACE::utils::LogErrorAndThrow("S3Api : Failed to get object head");
560 }
561
562 const auto content_type = [&object_head]() -> std::optional<std::string> {
563 if (!object_head->headers) {
564 return std::nullopt;
565 }
566
567 return USERVER_NAMESPACE::utils::FindOptional(
568 *object_head->headers,
569 USERVER_NAMESPACE::http::headers::kContentType
570 );
571 }();
572 if (!content_type) {
573 USERVER_NAMESPACE::utils::LogErrorAndThrow("S3Api : Object head is missing `content-type` header");
574 }
575
576 auto req = api_methods::CopyObject(bucket_, key_from, bucket_to, key_to, *content_type);
577 if (meta) {
578 SaveMeta(req.headers, *meta);
579 }
580 return RequestApi(req, "copy_object");
581}
582
583std::string ClientImpl::CopyObject(
584 std::string_view key_from,
585 std::string_view key_to,
586 const std::optional<Meta>& meta
587) {
588 return CopyObject(key_from, bucket_, key_to, meta);
589}
590
592 const multipart_upload::CreateMultipartUploadRequest& request
593) const try
594{
595 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
596 const auto api_response_body = RequestApi(api_request, "create_multipart_upload");
597 return multipart_upload::InitiateMultipartUploadResult::Parse(api_response_body);
598} catch (const ResponseParsingError& exc) {
600 fmt::format("failed to parse CreateMultipartUpload action response - {}; key: {}", exc.what(), request.key)
601 );
602}
603
604multipart_upload::UploadPartResult ClientImpl::UploadPart(const multipart_upload::UploadPartRequest& request) const try
605{
606 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
607
608 const HeaderDataRequest expected_headers({{std::string(kEtagHeader)}}, false);
609 HeadersDataResponse response_headers_data;
610
611 RequestApi(api_request, "upload_part", &response_headers_data, expected_headers);
612 if (!response_headers_data.headers) {
613 throw ResponseParsingError("missing ETag header in response");
614 }
615 const auto iter = response_headers_data.headers->find(kEtagHeader);
616 if (iter == response_headers_data.headers->end()) {
617 throw ResponseParsingError("missing ETag header in response");
618 }
619 if (iter->second.empty()) {
620 throw ResponseParsingError("got empty ETag header value in response");
621 }
622 return {std::move(iter->second)};
623
624} catch (const ResponseParsingError& exc) {
625 throw MultipartUploadError(fmt::format(
626 "failed to parse UploadPart action response - {}; upload_id '{}'; key '{}'",
627 exc.what(),
628 request.upload_id,
629 request.key
630 ));
631}
632
634 const multipart_upload::CompleteMultipartUploadRequest& request
635) const try
636{
637 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
638 const auto api_response_body = RequestApi(api_request, "complete_multipart_upload");
639 return multipart_upload::CompleteMultipartUploadResult::Parse(api_response_body);
640} catch (const ResponseParsingError& exc) {
641 throw MultipartUploadError(fmt::format(
642 "failed to parse CompleteMultipartUpload action response - {}; upload_id '{}'; key '{}'",
643 exc.what(),
644 request.upload_id,
645 request.key
646 ));
647}
648
649void ClientImpl::AbortMultipartUpload(const multipart_upload::AbortMultipartUploadRequest& request) const {
650 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
651 RequestApi(api_request, "abort_multipart_upload");
652}
653
654multipart_upload::ListPartsResult ClientImpl::ListParts(const multipart_upload::ListPartsRequest& request) const try
655{
656 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
657 const auto api_response_body = RequestApi(api_request, "list_parts");
658 return multipart_upload::ListPartsResult::Parse(api_response_body);
659} catch (const ResponseParsingError& exc) {
660 throw MultipartUploadError(fmt::format(
661 "failed to parse ListParts action response - {}; upload_id '{}'; key '{}'",
662 exc.what(),
663 request.upload_id,
664 request.key
665 ));
666}
667
669 const multipart_upload::ListMultipartUploadsRequest& request
670) const try
671{
672 auto api_request = api_methods::CreateInternalApiRequest(bucket_, request);
673 const auto api_response_body = RequestApi(api_request, "list_multipart_uploads");
674 return multipart_upload::ListMultipartUploadsResult::Parse(api_response_body);
675} catch (const ResponseParsingError& exc) {
676 throw MultipartUploadError(fmt::format("failed to parse ListMultipartUploads action response - {}", exc.what()));
677}
678
679ClientPtr GetS3Client(
680 std::shared_ptr<S3Connection> s3conn,
681 std::shared_ptr<authenticators::AccessKey> authenticator,
682 std::string bucket
683) {
684 return GetS3Client(
685 std::move(s3conn),
686 std::static_pointer_cast<authenticators::Authenticator>(authenticator),
687 std::move(bucket)
688 );
689}
690
691ClientPtr GetS3Client(
692 std::shared_ptr<S3Connection> s3conn,
693 std::shared_ptr<authenticators::Authenticator> authenticator,
694 std::string bucket
695) {
696 return std::static_pointer_cast<Client>(std::make_shared<ClientImpl>(s3conn, authenticator, bucket));
697}
698
699} // namespace s3api
700
701USERVER_NAMESPACE_END