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