From 90089ad326eae0a38adc0e57419ffaa588cada67 Mon Sep 17 00:00:00 2001 From: Larry Osterman Date: Wed, 17 Jul 2024 12:38:30 -0700 Subject: [PATCH] Cleaned up Azure::Core::Context API surface (#5676) * Deprecated Azure::Core::ApplicationContext because its use is confusing and inconsistent with the original design. --------- Co-authored-by: Rick Winter Co-authored-by: Anton Kolesnyk <41349689+antkmsft@users.noreply.github.com> Co-authored-by: Ahson Khan --- CONTRIBUTING.md | 2 +- README.md | 64 +++++++ doc/PerformanceTesting.md | 2 +- .../service/inc/azure/service/client.hpp | 2 +- .../azure/attestation/attestation_client.hpp | 2 +- .../test/ut/connection_tests.cpp | 3 +- .../azure-core-amqp/test/ut/link_tests.cpp | 4 +- .../test/ut/management_tests.cpp | 2 +- .../test/ut/message_sender_receiver.cpp | 8 +- .../test/ut/transport_tests.cpp | 10 +- sdk/core/azure-core-amqp/vcpkg/vcpkg.json | 2 +- .../test/ut/CMakeLists.txt | 6 - sdk/core/azure-core/CHANGELOG.md | 6 + .../azure-core/inc/azure/core/context.hpp | 159 ++++++++++++++++-- .../azure-core/inc/azure/core/operation.hpp | 2 +- sdk/core/azure-core/src/context.cpp | 22 ++- .../test/perf/src/azure_core_perf_test.cpp | 2 +- .../test/ut/azure_libcurl_core_main_test.cpp | 4 +- .../azure-core/test/ut/bodystream_test.cpp | 12 +- .../test/ut/client_options_test.cpp | 44 ++--- sdk/core/azure-core/test/ut/context_test.cpp | 10 +- .../test/ut/curl_connection_pool_test.cpp | 13 +- .../azure-core/test/ut/curl_options_test.cpp | 31 ++-- .../test/ut/curl_session_test_test.cpp | 22 ++- .../test/ut/global_context_test.cpp | 20 ++- sdk/core/azure-core/test/ut/http_test.cpp | 4 +- sdk/core/azure-core/test/ut/policy_test.cpp | 11 +- .../test/ut/request_activity_policy_test.cpp | 4 +- .../test/ut/service_tracing_test.cpp | 8 +- .../test/ut/transport_adapter_base_test.cpp | 107 +++++------- .../test/ut/transport_policy_options.cpp | 25 ++- sdk/core/perf/README.md | 2 +- sdk/core/perf/test/src/random_stream_test.cpp | 8 +- .../perf/src/azure_eventhubs_perf_test.cpp | 2 +- .../test/ut/consumer_client_test.cpp | 9 +- .../test/ut/processor_test.cpp | 13 +- .../samples/azure_cli_credential.cpp | 2 +- .../samples/chained_token_credential.cpp | 2 +- .../samples/client_certificate_credential.cpp | 2 +- .../samples/client_secret_credential.cpp | 2 +- .../samples/default_azure_credential.cpp | 2 +- .../samples/environment_credential.cpp | 2 +- .../samples/managed_identity_credential.cpp | 2 +- .../samples/workload_identity_credential.cpp | 2 +- .../perf/src/azure_identity_perf_test.cpp | 2 +- .../test/ut/azure_cli_credential_test.cpp | 3 +- .../test/ut/token_credential_test.cpp | 6 +- sdk/identity/azure-identity/vcpkg/vcpkg.json | 2 +- ...curity_keyvault_certificates_perf_test.cpp | 2 +- ...azure_security_keyvault_keys_perf_test.cpp | 2 +- .../test/ut/key_client_delete_test_live.cpp | 8 +- .../vcpkg/vcpkg.json | 2 +- ...re_security_keyvault_secrets_perf_test.cpp | 2 +- .../samples/CMakeLists.txt | 4 + .../blob_list_operation_with_timeout.cpp | 82 +++++++++ .../test/perf/CMakeLists.txt | 5 - .../storage/blobs/test/upload_blob_test.hpp | 3 +- .../src/azure_storage_blobs_perf_test.cpp | 2 +- .../azure-storage-common/vcpkg/vcpkg.json | 2 +- 59 files changed, 521 insertions(+), 269 deletions(-) create mode 100644 sdk/storage/azure-storage-blobs/samples/blob_list_operation_with_timeout.cpp diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 543aa23f5..a5f3742ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -256,7 +256,7 @@ Running the above commands will create the test executable and run it. While it If the coverage data has been previously generated (for example, if you manually run the unit tests), you can define `CODE_COVERAGE_COLLECT_ONLY` environment variable (set it to any value) and then the report will be generated without running the tests again. This is how the coverage reports are generated on CI, where the tests runs prior to code coverage step. -### Visual Studio 2019 +### Visual Studio 2019 or newer You can also build the project by simply opening the repo directory in Visual Studio. Visual Studio will detect the `CMake` file and will configure itself to generate, build and run tests. diff --git a/README.md b/README.md index ed05cb488..a2b223fb2 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,69 @@ You can intermittently poll whether the operation has finished by using the `Pol } ``` +#### `Azure::Core::Context` + +Most Azure SDK Service Client methods accept an optional `Azure::Core::Context` parameter, which is used to enable cancellation of the operation or to +establish an absolute deadline for the operation. + +This is useful when you want to assign a time limit on an operation to ensure that it completes in a "reasonable" timeframe. For instance, the +snippet below will cancel a blob client upload after 5 seconds. + + +```cpp + Azure::Core::Context cancelledIn5s{ + std::chrono::system_clock::now() + std::chrono::seconds(5)}; + + auto containerClient = BlobContainerClient::CreateFromConnectionString( + GetConnectionString(), containerName + std::to_string(i)); + containerClient.CreateIfNotExists({}, cancelledIn5s); + for (int j = 0; j < 3; ++j) + { + BlockBlobClient blobClient + = containerClient.GetBlockBlobClient(blobName + std::to_string(j)); + blobClient.UploadFrom( + reinterpret_cast(blobContent.data()), + blobContent.size(), + {}, + cancelledIn5s); + } +``` + +`Context` objects can also be directly cancelled using the `Cancel()` method. + +`Context` objects form a directed tree, where a child context can be created from a parent context. +The context tree is unidirectional and acyclic. + +These are the basic operations that can be performed on a `Context` object: + +* Create a child context from a parent context with a Key/Value pair. This is useful for associating metadata with a context. +* Create a child context from a parent context with a deadline. This is useful for setting a timeout. +* Cancel a context. This will cancel the context and all its children. Note that there is no way of un-cancelling a context. +* Check if a context is cancelled. + +When a context is copied from another context, the copied context will share state with the original context. +This means that if the original context is cancelled, the copied context will also be cancelled. + +Cancellation of a `Context` is a permanent operation. Once a context is cancelled, it cannot be un-cancelled. + +When a client operation fails with an `Azure::Core::OperationCancelledException`, it is typically due to a `Context` getting cancelled. This exception can be caught and handled by the application. + +#### Public, Private, and Internal Types + +For the most part, the APIs defined in the Azure SDK for C++ fall into three categories: + +- **Public**: These are the types that are intended to be used by the consumers of the SDK. +They are part of the public API and are stable. Breaking changes to these types will be avoided as much +as possible. All public types and functions are located are in the `Azure` root namespace. +- **Internal**: These are the types that are used internally by the packages within the SDK. +They are intended for use by the packages which make up the Azure SDK. They are NOT intended to be used by the consumers of the SDK. +Breaking changes to these types are allowed, within certain constraints. These types are located in an `Azure` namespace within the `_internal` terminal namespace (for instance, `Azure::Core::Http::Policies::_internal::RequestActivityPolicy`). +- **Private**: These are the types that are used internally to individual Azure SDK Packages. +They are not intended to be used by the consumers of the SDK, nor by other SDK packages. Breaking changes +to these types are allowed. These types are located in an `Azure` namespace within the `_detail` terminal namespace. + +Within the source tree, Internal types are typically declared in directories named "internal", and Private types are typically declared in directories named "private". + #### Interacting with Azure SDK for C++ Static SDK members should not be accessed and SDK functions should not be called before the static initialization phase is finished. @@ -338,3 +401,4 @@ Azure SDK for C++ is licensed under the [MIT](https://github.com/Azure/azure-sdk This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies. ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-cpp%2FREADME.png) + diff --git a/doc/PerformanceTesting.md b/doc/PerformanceTesting.md index 927fb1967..a7832e8e0 100644 --- a/doc/PerformanceTesting.md +++ b/doc/PerformanceTesting.md @@ -61,7 +61,7 @@ Contains one cpp file that contains the main method defintion Service::Namespace::Test::TestName::GetTestMetadata(), }; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/samples/helpers/service/inc/azure/service/client.hpp b/samples/helpers/service/inc/azure/service/client.hpp index 6609e7ace..44a9fa6e1 100644 --- a/samples/helpers/service/inc/azure/service/client.hpp +++ b/samples/helpers/service/inc/azure/service/client.hpp @@ -34,7 +34,7 @@ namespace Azure { namespace Service { // token, which is not critical for the intended demonstration purposes. And if user runs this, // and authentication is unsuccessful, it may draw an unnecessary attention to an irrelevant (to // the demo) point. - void DoSomething(const Core::Context& context) const; + void DoSomething(const Core::Context& context = {}) const; }; }} // namespace Azure::Service diff --git a/sdk/attestation/azure-security-attestation/inc/azure/attestation/attestation_client.hpp b/sdk/attestation/azure-security-attestation/inc/azure/attestation/attestation_client.hpp index 6cf526efe..37ae12421 100644 --- a/sdk/attestation/azure-security-attestation/inc/azure/attestation/attestation_client.hpp +++ b/sdk/attestation/azure-security-attestation/inc/azure/attestation/attestation_client.hpp @@ -184,7 +184,7 @@ namespace Azure { namespace Security { namespace Attestation { * specified service instance. */ Response GetOpenIdMetadata( - Azure::Core::Context const& context = Azure::Core::Context::ApplicationContext) const; + Azure::Core::Context const& context = {}) const; /** * @brief Retrieve the attestation signing certificates for this attestation instance. diff --git a/sdk/core/azure-core-amqp/test/ut/connection_tests.cpp b/sdk/core/azure-core-amqp/test/ut/connection_tests.cpp index e981e6594..4d1c30b70 100644 --- a/sdk/core/azure-core-amqp/test/ut/connection_tests.cpp +++ b/sdk/core/azure-core-amqp/test/ut/connection_tests.cpp @@ -168,8 +168,7 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests { // Ensure that we got an OnComplete callback within 5 seconds. auto transport = listenerEvents.WaitForResult( listener, - Azure::Core::Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::seconds(5))); + Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(5)}); // Now we can close the connection. connection.Close("xxx", "yyy", {}); diff --git a/sdk/core/azure-core-amqp/test/ut/link_tests.cpp b/sdk/core/azure-core-amqp/test/ut/link_tests.cpp index e222c3327..7ba3d1a69 100644 --- a/sdk/core/azure-core-amqp/test/ut/link_tests.cpp +++ b/sdk/core/azure-core-amqp/test/ut/link_tests.cpp @@ -359,8 +359,8 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests { Azure::Core::Amqp::Common::_internal::AsyncOperationQueue m_linkStateQueue; }; - Azure::Core::Context timeoutContext = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::seconds(60)); + Azure::Core::Context timeoutContext + = Azure::Core::Context{Azure::DateTime::clock::now() + std::chrono::seconds(60)}; Link keepAliveLink{ session, "KeepConnectionAlive", SessionRole::Receiver, "MyTarget", "TestReceiver"}; keepAliveLink.Attach(); diff --git a/sdk/core/azure-core-amqp/test/ut/management_tests.cpp b/sdk/core/azure-core-amqp/test/ut/management_tests.cpp index dea0a14a7..6ba82cbdd 100644 --- a/sdk/core/azure-core-amqp/test/ut/management_tests.cpp +++ b/sdk/core/azure-core-amqp/test/ut/management_tests.cpp @@ -579,7 +579,7 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests { "Type", "Locales", messageToSend, - Azure::Core::Context::ApplicationContext.WithDeadline( + Azure::Core::Context{}.WithDeadline( std::chrono::system_clock::now() + std::chrono::seconds(10))); EXPECT_EQ(response.Status, ManagementOperationStatus::Error); EXPECT_EQ(response.StatusCode, 500); diff --git a/sdk/core/azure-core-amqp/test/ut/message_sender_receiver.cpp b/sdk/core/azure-core-amqp/test/ut/message_sender_receiver.cpp index 6f205afe5..5463b1549 100644 --- a/sdk/core/azure-core-amqp/test/ut/message_sender_receiver.cpp +++ b/sdk/core/azure-core-amqp/test/ut/message_sender_receiver.cpp @@ -314,8 +314,8 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests { Session session{connection.CreateSession()}; // Set up a 30 second deadline on the receiver. - Azure::Core::Context receiveContext = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::seconds(15)); + Azure::Core::Context receiveContext + = Azure::Core::Context{Azure::DateTime::clock::now() + std::chrono::seconds(15)}; // Ensure that the thread is started before we start using the message sender. mockServer.StartListening(); @@ -793,8 +793,8 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests { // Receive a message with a 15 second timeout. It shouldn't throw. { - Azure::Core::Context receiveContext{Azure::Core::Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::seconds(15))}; + Azure::Core::Context receiveContext{ + std::chrono::system_clock::now() + std::chrono::seconds(15)}; // Tell the server it should send a message in the polling loop. serviceEndpoint->ShouldSendMessage(true); diff --git a/sdk/core/azure-core-amqp/test/ut/transport_tests.cpp b/sdk/core/azure-core-amqp/test/ut/transport_tests.cpp index d54d8b555..1c1f7a8ea 100644 --- a/sdk/core/azure-core-amqp/test/ut/transport_tests.cpp +++ b/sdk/core/azure-core-amqp/test/ut/transport_tests.cpp @@ -148,8 +148,8 @@ Accept: */* TEST_F(TestSocketTransport, SimpleOpen) { // Wait until we receive data from the www.microsoft.com server, with a 10 second timeout. - Azure::Core::Context completionContext = Azure::Core::Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::seconds(10)); + Azure::Core::Context completionContext + = Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(10)}; { Transport transport{SocketTransportFactory::Create("www.microsoft.com", 80)}; @@ -206,8 +206,7 @@ Accept: */* // Wait until we receive data from the www.microsoft.com server, with a 10 second timeout. Azure::Core::Context completionContext - = Azure::Core::Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::seconds(10)); + = Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(10)}; ASSERT_EQ(TransportOpenStatus::Ok, transport.Open(completionContext)); unsigned char val[] = R"(GET / HTTP/1.1 @@ -400,8 +399,7 @@ Host: www.microsoft.com)"; GTEST_LOG_(INFO) << "Wait for received event."; events.WaitForReceive( *listenerTransport, - Azure::Core::Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::seconds(10))); + Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(10)}); GTEST_LOG_(INFO) << "Listener received the bytes we just sent, now wait until the sender " "received those bytes back."; diff --git a/sdk/core/azure-core-amqp/vcpkg/vcpkg.json b/sdk/core/azure-core-amqp/vcpkg/vcpkg.json index 4b0ca855f..dbef02fd0 100644 --- a/sdk/core/azure-core-amqp/vcpkg/vcpkg.json +++ b/sdk/core/azure-core-amqp/vcpkg/vcpkg.json @@ -20,7 +20,7 @@ { "name": "azure-core-cpp", "default-features": false, - "version>=": "1.11.3" + "version>=": "1.14.0-beta.1" }, "azure-macro-utils-c", "umock-c", diff --git a/sdk/core/azure-core-tracing-opentelemetry/test/ut/CMakeLists.txt b/sdk/core/azure-core-tracing-opentelemetry/test/ut/CMakeLists.txt index 3003a46b3..0f3d9b933 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/test/ut/CMakeLists.txt +++ b/sdk/core/azure-core-tracing-opentelemetry/test/ut/CMakeLists.txt @@ -13,12 +13,6 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang") add_compile_options(-Wno-error=deprecated-declarations) endif() -if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC") -# Disable deprecation warnings. - add_compile_options(/wd4996) -endif() - - project (azure-core-tracing-opentelemetry-test LANGUAGES CXX) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED True) diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index 0cf907c6a..2376adf3b 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -4,8 +4,14 @@ ### Features Added +- Added new constructor for `Azure::Core::Context` that takes a `std::chrono::system_clock::time_point` deadline. This enables creating a new context directly with a deadline. + ### Breaking Changes +- Deprecated the `Azure::Core::Context::ApplicationContext` object. + - If customer code is using `Azure::Core::Context::ApplicationContext`, the customer should instead create their own root context object which is used + wherever the customer would have previously used `Azure::Core::Context::ApplicationContext`, i.e. `Azure::Core::Context(deadline)` instead of `Azure::Core::Context::ApplicationContext.WithDeadline(deadline)`. + ### Bugs Fixed ### Other Changes diff --git a/sdk/core/azure-core/inc/azure/core/context.hpp b/sdk/core/azure-core/inc/azure/core/context.hpp index 75dc24f3d..a6f935db7 100644 --- a/sdk/core/azure-core/inc/azure/core/context.hpp +++ b/sdk/core/azure-core/inc/azure/core/context.hpp @@ -10,7 +10,6 @@ #include "azure/core/azure_assert.hpp" #include "azure/core/datetime.hpp" -#include "azure/core/dll_import_export.hpp" #include "azure/core/rtti.hpp" #include @@ -41,7 +40,34 @@ namespace Azure { namespace Core { }; /** - * @brief A context is a node within a tree that represents deadlines and key/value pairs. + * @brief A context is a node within a unidirectional tree that represents deadlines and key/value + * pairs. + * + * Most Azure Service Client operations accept a Context object. The Context object allows the + * caller to cancel the operation if it is taking too long, or to ensure that the operation + * completes before a specific deadline. This allows an application to apply timeouts to + * operations, or to cancel operations that need to be abandoned. + * + * After cancelling a Context, all service operations which have the cancelled context + * as a parent context will be cancelled. Cancellation is indicated by throwing an + * Azure::Core::OperationCancelledException from the operation. + * + * Context objects support the following operations to create new contexts: + * - WithDeadline(DateTime): creates a new child context with a deadline. + * - WithValue(Key, T): creates a new child context with a key/value pair. + * + * Context objects support the following operations to retrieve data: + * - GetDeadline(): gets the deadline for the context. + * - TryGetValue(Key, T): gets the value associated with a key. + * + * Context objects support two operations to manage the context: + * - Cancel(): cancels the context. + * - IsCancelled(): checks if the context is cancelled. + * + * Context objects support the following operation to throw if the context is cancelled: + * - ThrowIfCancelled(): throws an OperationCancelledException if the context is cancelled. + * + * */ class Context final { public: @@ -97,6 +123,14 @@ namespace Azure { namespace Core { return DateTime(DateTime::time_point(DateTime::duration(dtRepresentation))); } + ContextSharedState(ContextSharedState const&) = delete; + ContextSharedState(ContextSharedState&&) = delete; + ContextSharedState& operator=(ContextSharedState const&) = delete; + ContextSharedState&& operator=(ContextSharedState&&) = delete; + + /** + * @brief Creates a new ContextSharedState object with no deadline and no value. + */ explicit ContextSharedState() : Deadline(ToDateTimeRepresentation((DateTime::max)())), Value(nullptr) #if defined(AZ_CORE_RTTI) @@ -106,9 +140,16 @@ namespace Azure { namespace Core { { } + /** + * @brief Create a new ContextSharedState from another ContextSharedState with a deadline. + * + * @param parent The parent context to create a child context from. + * @param deadline The deadline for the new context. + * + */ explicit ContextSharedState( const std::shared_ptr& parent, - DateTime const& deadline) + DateTime const& deadline = (DateTime::max)()) : Parent(parent), Deadline(ToDateTimeRepresentation(deadline)), Value(nullptr) #if defined(AZ_CORE_RTTI) , @@ -117,6 +158,17 @@ namespace Azure { namespace Core { { } + /** + * @brief Create a new ContextSharedState from another ContextSharedState with a deadline and + * a key value pair. + * + * @tparam T The type of the value to be stored with the key. + * @param parent The parent context to create a child context from. + * @param deadline The deadline for the new context. + * @param key The key to associate with the value. + * @param value The value to associate with the key. + * + */ template explicit ContextSharedState( const std::shared_ptr& parent, @@ -142,13 +194,78 @@ namespace Azure { namespace Core { public: /** - * @brief Constructs a new context with no deadline, and no value associated. + * @brief Constructs a context with no deadline, and no value associated. * */ Context() : m_contextSharedState(std::make_shared()) {} /** - * @brief Creates a context with a deadline. + * @brief Constructs a context with a deadline + * object. + * + * @param deadline A point in time after which a context expires. + * + */ + explicit Context(DateTime const& deadline) + : m_contextSharedState(std::make_shared(nullptr, deadline)) + { + } + + /** + * @brief Copies a context. + * + * This operation copies one context to another. Context objects are copied by reference, + * so the new context will share the same state as the original context. This also means + * that cancelling one context cancels all contexts which are copied from the original + * context. + * + * @param other Another context to copy. + * + */ + Context(Context const&) = default; + + /** + * @brief Assigns a context. + * + * This operation assigns one context to another. Context objects are copied by reference, so + * the new context will share the same state as the original context. This also means that + * cancelling one context cancels all contexts which are copied from the original context. + * + * @param other Another context to assign. + * + * @return A new Context referencing the state of the original context. + */ + Context& operator=(Context const& other) = default; + + /** + * @brief Moves a context. + * + * This operation moves one context to another. + * + * @param other The context to move. + * + */ + Context(Context&& other) = default; + + /** + * @brief Moves a context. + * + * This operation moves one context to another. + * + * @param other The context to move. + * @return A new Context referencing the state of the original context. + * + */ + Context& operator=(Context&& other) = default; + + /** + * @brief Destroys a context. + * + */ + ~Context() = default; + + /** + * @brief Creates a context with a deadline from an existing Context object. * * @param deadline A point in time after which a context expires. * @@ -160,13 +277,14 @@ namespace Azure { namespace Core { } /** - * @brief Creates a context without a deadline, but with \p key and \p value associated with it. + * @brief Creates a new child context with \p key and \p value + * associated with it. * * @tparam T The type of the value to be stored with the key. * @param key A key to associate with this context. * @param value A value to associate with this context. * - * @return A child context with no deadline and the \p key and \p value associated with it. + * @return A child context with the \p key and \p value associated with it. */ template Context WithValue(Key const& key, T&& value) const { @@ -200,7 +318,7 @@ namespace Azure { namespace Core { */ template bool TryGetValue(Key const& key, T& outputValue) const { - for (auto ptr = m_contextSharedState; ptr; ptr = ptr->Parent) + for (std::shared_ptr ptr = m_contextSharedState; ptr; ptr = ptr->Parent) { if (ptr->Key == key) { @@ -217,7 +335,14 @@ namespace Azure { namespace Core { } /** - * @brief Cancels the context. + * @brief Cancels the context. All operations which share this Context will be cancelled. + * + * @note Cancellation of a Context is a best-faith effort. Because of the synchronous nature of + * Azure C++ SDK APIs, it is possible that the operation will not be cancelled immediately. Each + * operation explicitly checks the context's state to determine if it has been cancelled, + * those checks may not happen immediately, or at all. + * + * @note Once a context has been cancelled, the cancellation cannot be undone. * */ void Cancel() @@ -232,10 +357,9 @@ namespace Azure { namespace Core { */ bool IsCancelled() const { return GetDeadline() < std::chrono::system_clock::now(); } - /** - * @brief Checks if the context is cancelled. - * @throw #Azure::Core::OperationCancelledException if the context is cancelled. + /** @brief Throws if the context is cancelled. * + * @throw #Azure::Core::OperationCancelledException if the context is cancelled. */ void ThrowIfCancelled() const { @@ -245,10 +369,15 @@ namespace Azure { namespace Core { } } - /** - * @brief The application context (root). + /** @brief The `ApplicationContext` is a deprecated singleton Context object. + * + * @note: The `ApplicationContext` object is deprecated and will be removed in a future release. + * If your application is using `ApplicationContext`, you should create your own root context + * and use it where you would have otherwise used `ApplicationContext`. * */ - static const AZ_CORE_DLLEXPORT Context ApplicationContext; + [[deprecated( + "ApplicationContext is no longer supported. Instead customers should create their " + "own root context objects.")]] static const AZ_CORE_DLLEXPORT Context ApplicationContext; }; }} // namespace Azure::Core diff --git a/sdk/core/azure-core/inc/azure/core/operation.hpp b/sdk/core/azure-core/inc/azure/core/operation.hpp index 1b91b389b..2b31e0002 100644 --- a/sdk/core/azure-core/inc/azure/core/operation.hpp +++ b/sdk/core/azure-core/inc/azure/core/operation.hpp @@ -179,7 +179,7 @@ namespace Azure { namespace Core { { // In the cases where the customer doesn't want to use a context we new one up and pass it // through - return Poll(Context::ApplicationContext); + return Poll(Context{}); } /** diff --git a/sdk/core/azure-core/src/context.cpp b/sdk/core/azure-core/src/context.cpp index 1d6ce6388..10cbf25c7 100644 --- a/sdk/core/azure-core/src/context.cpp +++ b/sdk/core/azure-core/src/context.cpp @@ -5,14 +5,34 @@ using namespace Azure::Core; +// Disable deprecation warning +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + const Context Context::ApplicationContext; +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif // _MSC_VER + Azure::DateTime Azure::Core::Context::GetDeadline() const { // Contexts form a tree. Here, we walk from a node all the way back to the root in order to find // the earliest deadline value. auto result = (DateTime::max)(); - for (auto ptr = m_contextSharedState; ptr; ptr = ptr->Parent) + for (std::shared_ptr ptr = m_contextSharedState; ptr; ptr = ptr->Parent) { auto deadline = ContextSharedState::FromDateTimeRepresentation(ptr->Deadline); if (result > deadline) diff --git a/sdk/core/azure-core/test/perf/src/azure_core_perf_test.cpp b/sdk/core/azure-core/test/perf/src/azure_core_perf_test.cpp index 87bd2b70d..5c2e536ef 100644 --- a/sdk/core/azure-core/test/perf/src/azure_core_perf_test.cpp +++ b/sdk/core/azure-core/test/perf/src/azure_core_perf_test.cpp @@ -30,7 +30,7 @@ int main(int argc, char** argv) Azure::Core::Test::PipelineTest::GetTestMetadata(), Azure::Core::Test::UuidTest::GetTestMetadata()}; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/core/azure-core/test/ut/azure_libcurl_core_main_test.cpp b/sdk/core/azure-core/test/ut/azure_libcurl_core_main_test.cpp index 0b6435975..b29b3db71 100644 --- a/sdk/core/azure-core/test/ut/azure_libcurl_core_main_test.cpp +++ b/sdk/core/azure-core/test/ut/azure_libcurl_core_main_test.cpp @@ -50,9 +50,9 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique(req, std::move(connection), options); - session->Perform(Azure::Core::Context::ApplicationContext); + session->Perform(Azure::Core::Context{}); // Reading all the response - session->ReadToEnd(Azure::Core::Context::ApplicationContext); + session->ReadToEnd(Azure::Core::Context{}); // If all three of these conditions are true, the connection should be moved to the connection // pool. diff --git a/sdk/core/azure-core/test/ut/bodystream_test.cpp b/sdk/core/azure-core/test/ut/bodystream_test.cpp index 1ae5a4584..8ecb7c5e3 100644 --- a/sdk/core/azure-core/test/ut/bodystream_test.cpp +++ b/sdk/core/azure-core/test/ut/bodystream_test.cpp @@ -68,9 +68,9 @@ TEST(BodyStream, BadInput) { TestBodyStream tb; ASSERT_DEATH(tb.Read(NULL, 1), ""); - ASSERT_DEATH(tb.Read(NULL, 1, Azure::Core::Context::ApplicationContext), ""); + ASSERT_DEATH(tb.Read(NULL, 1, Azure::Core::Context{}), ""); ASSERT_DEATH(tb.ReadToCount(NULL, 1), ""); - ASSERT_DEATH(tb.ReadToCount(NULL, 1, Azure::Core::Context::ApplicationContext), ""); + ASSERT_DEATH(tb.ReadToCount(NULL, 1, Azure::Core::Context{}), ""); } TEST(MemoryBodyStream, BadInput) { ASSERT_DEATH(MemoryBodyStream(NULL, 1), ""); } @@ -100,7 +100,7 @@ TEST(FileBodyStream, Length) Azure::Core::IO::FileBodyStream stream(testDataPath); EXPECT_EQ(stream.Length(), FileSize); - auto readResult = stream.ReadToEnd(Azure::Core::Context::ApplicationContext); + auto readResult = stream.ReadToEnd(Azure::Core::Context{}); EXPECT_EQ(readResult.size(), FileSize); stream.Rewind(); @@ -120,7 +120,7 @@ TEST(FileBodyStream, Read) stream.Rewind(); - readResult = stream.ReadToEnd(Azure::Core::Context::ApplicationContext); + readResult = stream.ReadToEnd(Azure::Core::Context{}); EXPECT_EQ(readResult.size(), FileSize); stream.Rewind(); @@ -134,7 +134,7 @@ TEST(FileBodyStream, Read) stream.Rewind(); - readSize = stream.ReadToCount(buffer.data(), 10, Azure::Core::Context::ApplicationContext); + readSize = stream.ReadToCount(buffer.data(), 10, Azure::Core::Context{}); EXPECT_EQ(readSize, 10); EXPECT_EQ(buffer[10], 0); @@ -147,7 +147,7 @@ TEST(FileBodyStream, Read) stream.Rewind(); - readSize = stream.Read(buffer.data(), buffer.size(), Azure::Core::Context::ApplicationContext); + readSize = stream.Read(buffer.data(), buffer.size(), Azure::Core::Context{}); EXPECT_EQ(readSize, FileSize); EXPECT_EQ(buffer[FileSize], 0); } diff --git a/sdk/core/azure-core/test/ut/client_options_test.cpp b/sdk/core/azure-core/test/ut/client_options_test.cpp index d5bd0acd8..ed9038576 100644 --- a/sdk/core/azure-core/test/ut/client_options_test.cpp +++ b/sdk/core/azure-core/test/ut/client_options_test.cpp @@ -76,23 +76,21 @@ TEST(ClientOptions, copyWithOperator) options.PerRetryPolicies.emplace_back(std::make_unique()); // Now Copy - auto copyOptions = options; + ClientOptions copyOptions = options; // Compare EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); - auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); + auto result = copyOptions.Transport.Transport->Send(r, Context{}); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); - result = copyOptions.PerOperationPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); - result = copyOptions.PerRetryPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } @@ -113,17 +111,15 @@ TEST(ClientOptions, copyWithConstructor) EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); - auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); + auto result = copyOptions.Transport.Transport->Send(r, Context{}); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); - result = copyOptions.PerOperationPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); - result = copyOptions.PerRetryPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } @@ -151,17 +147,15 @@ TEST(ClientOptions, copyDerivedClassConstructor) EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); - auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); + auto result = copyOptions.Transport.Transport->Send(r, Context{}); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); - result = copyOptions.PerOperationPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); - result = copyOptions.PerRetryPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } @@ -182,24 +176,22 @@ TEST(ClientOptions, copyDerivedClassOperator) options.PerRetryPolicies.emplace_back(std::make_unique()); // Now Copy - auto copyOptions = options; + ServiceClientOptions copyOptions = options; // Compare EXPECT_EQ("I am not real!", copyOptions.ApiVersion); EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); - auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); + auto result = copyOptions.Transport.Transport->Send(r, Context{}); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); - result = copyOptions.PerOperationPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); - result = copyOptions.PerRetryPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } @@ -227,16 +219,14 @@ TEST(ClientOptions, moveConstruct) EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); - auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); + auto result = copyOptions.Transport.Transport->Send(r, Context{}); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); - result = copyOptions.PerOperationPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); - result = copyOptions.PerRetryPolicies[0]->Send( - r, NextHttpPolicy(0, {}), Context::ApplicationContext); + result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{}); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } diff --git a/sdk/core/azure-core/test/ut/context_test.cpp b/sdk/core/azure-core/test/ut/context_test.cpp index 45fe72bef..5b55358d1 100644 --- a/sdk/core/azure-core/test/ut/context_test.cpp +++ b/sdk/core/azure-core/test/ut/context_test.cpp @@ -1,14 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -#include -#include +#include "azure/core/context.hpp" #include #include #include #include -#include #include @@ -241,7 +239,7 @@ struct SomeStructForContext final TEST(Context, InstanceValue) { Context::Key const key; - auto contextP = Context::ApplicationContext.WithValue(key, SomeStructForContext()); + auto contextP = Context{}.WithValue(key, SomeStructForContext()); SomeStructForContext contextValueRef; EXPECT_TRUE(contextP.TryGetValue(key, contextValueRef)); EXPECT_EQ(contextValueRef.someField, 12345); @@ -251,7 +249,7 @@ TEST(Context, Ptr) { Context::Key const key; SomeStructForContext value; - auto contextP = Context::ApplicationContext.WithValue(key, &value); + auto contextP = Context{}.WithValue(key, &value); SomeStructForContext* contextValueRef; EXPECT_TRUE(contextP.TryGetValue(key, contextValueRef)); @@ -277,7 +275,7 @@ TEST(Context, NestedClassPtr) Context::Key const key; - auto context = Context::ApplicationContext.WithValue(key, sharedPtr); + auto context = Context{}.WithValue(key, sharedPtr); EXPECT_EQ(sharedPtr.use_count(), 2); std::shared_ptr foundPtr; diff --git a/sdk/core/azure-core/test/ut/curl_connection_pool_test.cpp b/sdk/core/azure-core/test/ut/curl_connection_pool_test.cpp index 67661c39e..61ecc1004 100644 --- a/sdk/core/azure-core/test/ut/curl_connection_pool_test.cpp +++ b/sdk/core/azure-core/test/ut/curl_connection_pool_test.cpp @@ -311,8 +311,7 @@ namespace Azure { namespace Core { namespace Test { // Now check the pool until the clean thread until finishes removing the connections or // fail after 5 minutes (indicates a problem with the clean routine) - auto timeOut - = Context::ApplicationContext.WithDeadline(std::chrono::system_clock::now() + 5min); + auto timeOut = Context{std::chrono::system_clock::now() + 5min}; bool poolIsEmpty = false; while (!poolIsEmpty && !timeOut.IsCancelled()) { @@ -373,13 +372,13 @@ namespace Azure { namespace Core { namespace Test { // .ConnectionPoolIndex[hostKey] // .begin(); // EXPECT_EQ( - // connectionIt->get()->ReadFromSocket(nullptr, 0, Context::ApplicationContext), + // connectionIt->get()->ReadFromSocket(nullptr, 0, Context{}), // 2000 - 1); // starting from zero // connectionIt = --(Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool // .ConnectionPoolIndex[hostKey] // .end()); // EXPECT_EQ( - // connectionIt->get()->ReadFromSocket(nullptr, 0, Context::ApplicationContext), + // connectionIt->get()->ReadFromSocket(nullptr, 0, Context{}), // 2000 - 1024); // // Check the pool will take other host-key @@ -603,7 +602,7 @@ namespace Azure { namespace Core { namespace Test { // Check that CURLE_SEND_ERROR is produced when trying to use the connection. auto session = std::make_unique(req, std::move(connection), options); - auto r = session->Perform(Azure::Core::Context::ApplicationContext); + auto r = session->Perform(Azure::Core::Context{}); EXPECT_EQ(CURLE_SEND_ERROR, r); } } @@ -623,7 +622,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique(req, std::move(connection), options); - auto r = session->Perform(Azure::Core::Context::ApplicationContext); + auto r = session->Perform(Azure::Core::Context{}); EXPECT_EQ(CURLE_OK, r); auto response = session->ExtractResponse(); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::SwitchingProtocols); @@ -652,7 +651,7 @@ namespace Azure { namespace Core { namespace Test { { // Create a pipeline to send the request and dispose after it. Azure::Core::Http::_internal::HttpPipeline pipeline({}, "test", "test", {}, {}); - auto response = pipeline.Send(req, Azure::Core::Context::ApplicationContext); + auto response = pipeline.Send(req, Azure::Core::Context{}); EXPECT_PRED2( [](Azure::Core::Http::HttpStatusCode a, Azure::Core::Http::HttpStatusCode b) { return a == b; diff --git a/sdk/core/azure-core/test/ut/curl_options_test.cpp b/sdk/core/azure-core/test/ut/curl_options_test.cpp index 53520ea12..72f10fb73 100644 --- a/sdk/core/azure-core/test/ut/curl_options_test.cpp +++ b/sdk/core/azure-core/test/ut/curl_options_test.cpp @@ -4,15 +4,16 @@ #include #include #include -#include #include -#include +#include #include #if defined(BUILD_CURL_HTTP_TRANSPORT_ADAPTER) #include "azure/core/http/curl_transport.hpp" -#include "openssl/x509.h" +#if defined(AZ_PLATFORM_POSIX) +#include +#endif #endif #include "transport_adapter_base_test.hpp" @@ -22,7 +23,6 @@ #include #include -#include namespace Azure { namespace Core { namespace Test { @@ -49,7 +49,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{})); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( @@ -79,7 +79,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{})); if (response) { auto responseCode = response->GetStatusCode(); @@ -136,7 +136,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context::ApplicationContext, + EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context{}, request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( [](int expected, int code) { return expected == code; }, expectedCode, @@ -162,7 +162,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context::ApplicationContext, + EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context{}, request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( [](int expected, int code) { return expected == code; }, expectedCode, @@ -188,7 +188,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context::ApplicationContext, + EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context{}, request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( [](int expected, int code) { return expected == code; }, expectedCode, @@ -220,7 +220,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{})); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( @@ -270,7 +270,7 @@ namespace Azure { namespace Core { namespace Test { #if defined(AZ_PLATFORM_LINUX) std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{})); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); // Clean the connection from the pool *Windows fails to clean if we leave to be clean upon @@ -279,11 +279,10 @@ namespace Azure { namespace Core { namespace Test { .ConnectionPoolIndex.clear()); #else EXPECT_THROW( - pipeline.Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + pipeline.Send(request, Azure::Core::Context{}), Azure::Core::Http::TransportException); try { - pipeline.Send(request, Azure::Core::Context::ApplicationContext); + pipeline.Send(request, Azure::Core::Context{}); } catch (Azure::Core::Http::TransportException& e) { @@ -313,7 +312,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{})); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( @@ -350,7 +349,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); std::unique_ptr response; - EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{})); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( diff --git a/sdk/core/azure-core/test/ut/curl_session_test_test.cpp b/sdk/core/azure-core/test/ut/curl_session_test_test.cpp index c9ebe3859..def4d7a03 100644 --- a/sdk/core/azure-core/test/ut/curl_session_test_test.cpp +++ b/sdk/core/azure-core/test/ut/curl_session_test_test.cpp @@ -46,7 +46,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(session->Perform(Azure::Core::Context{})); } TEST_F(CurlSession, chunkResponseSizeZero) @@ -83,7 +83,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(session->Perform(Azure::Core::Context{})); } // Clear the connections from the pool to invoke clean routine Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex @@ -128,15 +128,13 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(session->Perform(Azure::Core::Context{})); auto r = session->ExtractResponse(); r->SetBodyStream(std::move(session)); auto bodyS = r->ExtractBodyStream(); // Read the bodyStream to get all chunks - EXPECT_THROW( - bodyS->ReadToEnd(Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(bodyS->ReadToEnd(Azure::Core::Context{}), Azure::Core::Http::TransportException); } // Clear the connections from the pool to invoke clean routine Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex @@ -171,7 +169,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_THROW(session->Perform(Azure::Core::Context::ApplicationContext), std::invalid_argument); + EXPECT_THROW(session->Perform(Azure::Core::Context{}), std::invalid_argument); } TEST_F(CurlSession, emptyHeaderValue) @@ -202,7 +200,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(session->Perform(Azure::Core::Context{})); } TEST_F(CurlSession, headerValueWhitespace) @@ -233,7 +231,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(session->Perform(Azure::Core::Context{})); } TEST_F(CurlSession, chunkSegmentedResponse) @@ -310,13 +308,13 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(session->Perform(Azure::Core::Context{})); auto response = session->ExtractResponse(); response->SetBodyStream(std::move(session)); auto bodyS = response->ExtractBodyStream(); // Read the bodyStream to get all chunks - EXPECT_NO_THROW(bodyS->ReadToEnd(Azure::Core::Context::ApplicationContext)); + EXPECT_NO_THROW(bodyS->ReadToEnd(Azure::Core::Context{})); } // Clear the connections from the pool to invoke clean routine Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex @@ -348,7 +346,7 @@ namespace Azure { namespace Core { namespace Test { auto session = std::make_unique( request, std::move(uniqueCurlMock), transportOptions); - auto returnCode = session->Perform(Azure::Core::Context::ApplicationContext); + auto returnCode = session->Perform(Azure::Core::Context{}); EXPECT_EQ(CURLE_SEND_ERROR, returnCode); } // Check connection pool is empty (connection was not moved to the pool) diff --git a/sdk/core/azure-core/test/ut/global_context_test.cpp b/sdk/core/azure-core/test/ut/global_context_test.cpp index 43caed7f5..1bbdcfa47 100644 --- a/sdk/core/azure-core/test/ut/global_context_test.cpp +++ b/sdk/core/azure-core/test/ut/global_context_test.cpp @@ -13,13 +13,24 @@ #include #include -#include #include #include using namespace Azure::Core; +// Disable deprecation warning +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + TEST(Context, ApplicationContext) { Context appContext = Context::ApplicationContext; @@ -41,3 +52,10 @@ TEST(Context, ApplicationContext) Context appContext2 = Context::ApplicationContext; EXPECT_TRUE(appContext2.IsCancelled()); } +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif // _MSC_VER diff --git a/sdk/core/azure-core/test/ut/http_test.cpp b/sdk/core/azure-core/test/ut/http_test.cpp index d3abf52df..eadec7cfc 100644 --- a/sdk/core/azure-core/test/ut/http_test.cpp +++ b/sdk/core/azure-core/test/ut/http_test.cpp @@ -220,7 +220,7 @@ namespace Azure { namespace Core { namespace Test { // Change the offset of the stream to be non-zero by reading a byte. std::vector temp(2); - EXPECT_EQ(stream.ReadToCount(temp.data(), 1, Context::ApplicationContext), 1); + EXPECT_EQ(stream.ReadToCount(temp.data(), 1, Context{}), 1); EXPECT_EQ(temp[0], 1); EXPECT_EQ(temp[1], 0); @@ -242,7 +242,7 @@ namespace Azure { namespace Core { namespace Test { // Verify that StartTry rewound the stream back. auto getStream = req.GetBodyStream(); - EXPECT_EQ(getStream->ReadToCount(temp.data(), 2, Context::ApplicationContext), 2); + EXPECT_EQ(getStream->ReadToCount(temp.data(), 2, Context{}), 2); EXPECT_EQ(temp[0], 1); EXPECT_EQ(temp[1], 2); diff --git a/sdk/core/azure-core/test/ut/policy_test.cpp b/sdk/core/azure-core/test/ut/policy_test.cpp index 5abdb9e03..cdfcb1cc1 100644 --- a/sdk/core/azure-core/test/ut/policy_test.cpp +++ b/sdk/core/azure-core/test/ut/policy_test.cpp @@ -117,8 +117,7 @@ TEST(Policy, throwWhenNoTransportPolicy) Azure::Core::Http::_internal::HttpPipeline pipeline(policies); Azure::Core::Url url(""); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); - EXPECT_THROW( - pipeline.Send(request, Azure::Core::Context::ApplicationContext), std::invalid_argument); + EXPECT_THROW(pipeline.Send(request, Azure::Core::Context{}), std::invalid_argument); } TEST(Policy, throwWhenNoTransportPolicyMessage) @@ -140,7 +139,7 @@ TEST(Policy, throwWhenNoTransportPolicyMessage) try { - pipeline.Send(request, Azure::Core::Context::ApplicationContext); + pipeline.Send(request, Azure::Core::Context{}); } catch (const std::invalid_argument& ex) { @@ -159,7 +158,7 @@ TEST(Policy, RetryPolicyCounter) retryCounterState = 0; // Check when there's no info about retry on the context - auto initialContext = Context::ApplicationContext; + Azure::Core::Context initialContext; EXPECT_EQ(-1, RetryPolicy::GetRetryCount(initialContext)); // Pipeline with retry test @@ -196,7 +195,7 @@ TEST(Policy, RetryPolicyRetryCycle) HttpPipeline pipeline(policies); Request request(HttpMethod::Get, Url("url")); - pipeline.Send(request, Context::ApplicationContext); + pipeline.Send(request, Context{}); } // Makes sure that the context tree is not corrupted/broken by some policy @@ -221,6 +220,6 @@ TEST(Policy, RetryPolicyKeepContext) HttpPipeline pipeline(policies); Request request(HttpMethod::Get, Url("url")); - auto withValueContext = Context::ApplicationContext.WithValue(TheKey, std::string("TheValue")); + auto withValueContext = Context{}.WithValue(TheKey, std::string("TheValue")); pipeline.Send(request, withValueContext); } diff --git a/sdk/core/azure-core/test/ut/request_activity_policy_test.cpp b/sdk/core/azure-core/test/ut/request_activity_policy_test.cpp index 13f62465c..6eecba116 100644 --- a/sdk/core/azure-core/test/ut/request_activity_policy_test.cpp +++ b/sdk/core/azure-core/test/ut/request_activity_policy_test.cpp @@ -165,7 +165,7 @@ TEST(RequestActivityPolicy, Basic) Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( clientOptions, "My.Service", "my-service-cpp", "1.0b2"); - auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); + auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{}); Azure::Core::Context callContext = std::move(contextAndSpan.Context); Request request(HttpMethod::Get, Url("https://www.microsoft.com")); @@ -197,7 +197,7 @@ TEST(RequestActivityPolicy, Basic) clientOptions.Telemetry.TracingProvider = testTracer; Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( clientOptions, "Azure.Service", "service", "1.0.0.beta-2"); - auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); + auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{}); Azure::Core::Context callContext = std::move(contextAndSpan.Context); Request request(HttpMethod::Get, Url("https://www.microsoft.com")); diff --git a/sdk/core/azure-core/test/ut/service_tracing_test.cpp b/sdk/core/azure-core/test/ut/service_tracing_test.cpp index f82b449c3..7acfe7206 100644 --- a/sdk/core/azure-core/test/ut/service_tracing_test.cpp +++ b/sdk/core/azure-core/test/ut/service_tracing_test.cpp @@ -87,7 +87,7 @@ TEST(TracingContextFactory, SimpleServiceSpanTests) Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( clientOptions, "my.service", "my-service-cpp", "1.0b2"); - auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); + auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{}); EXPECT_FALSE(contextAndSpan.Context.IsCancelled()); } } @@ -184,7 +184,7 @@ TEST(TracingContextFactory, BasicServiceSpanTests) Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( clientOptions, "My.Service", "my-service-cpp", "1.0b2"); - auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); + auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{}); ServiceSpan span = std::move(contextAndSpan.Span); span.End(); @@ -200,7 +200,7 @@ TEST(TracingContextFactory, BasicServiceSpanTests) Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( clientOptions, "My.Service", "my-service-cpp", "1.0b2"); - auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); + auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{}); ServiceSpan span = std::move(contextAndSpan.Span); span.End(); @@ -221,7 +221,7 @@ TEST(TracingContextFactory, BasicServiceSpanTests) Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( clientOptions, "My.Service", "my-service-cpp", "1.0b2"); - auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); + auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{}); ServiceSpan span = std::move(contextAndSpan.Span); span.End(); diff --git a/sdk/core/azure-core/test/ut/transport_adapter_base_test.cpp b/sdk/core/azure-core/test/ut/transport_adapter_base_test.cpp index fce2281d2..cf667e04b 100644 --- a/sdk/core/azure-core/test/ut/transport_adapter_base_test.cpp +++ b/sdk/core/azure-core/test/ut/transport_adapter_base_test.cpp @@ -1,26 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -#include -#include - -#if defined(AZ_PLATFORM_POSIX) -#include -#elif defined(AZ_PLATFORM_WINDOWS) -#if !defined(WIN32_LEAN_AND_MEAN) -#define WIN32_LEAN_AND_MEAN -#endif -#if !defined(NOMINMAX) -#define NOMINMAX -#endif -#include -#endif - #include "transport_adapter_base_test.hpp" #include #include +#include #include +#include #include #include @@ -35,7 +22,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url host(AzureSdkHttpbinServer::Get()); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); CheckBodyFromBuffer(*response, expectedResponseBodySize); @@ -44,7 +31,7 @@ namespace Azure { namespace Core { namespace Test { request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); // Add a header and send again. RawResponse should return that header in the body request.SetHeader("123", "456"); - response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto body = response->GetBody(); @@ -60,7 +47,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url host("http://mt3.google.com/generate_204"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::NoContent); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); CheckBodyFromBuffer(*response, expectedResponseBodySize); @@ -75,7 +62,7 @@ namespace Azure { namespace Core { namespace Test { // loop sending request for (auto i = 0; i < 50; i++) { - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); checkResponseCode(response->GetStatusCode()); CheckBodyFromBuffer(*response, expectedResponseBodySize); @@ -88,7 +75,7 @@ namespace Azure { namespace Core { namespace Test { auto expectedResponseBodySize = 0; auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, host); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); CheckBodyFromBuffer(*response, expectedResponseBodySize); @@ -106,7 +93,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -129,7 +116,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Delete, host, &bodyRequest); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -145,7 +132,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Patch, host, &bodyRequest); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -164,7 +151,7 @@ namespace Azure { namespace Core { namespace Test { "sent to a client."); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); CheckBodyFromBuffer(*response, expectedResponseBodySize, expectedChunkResponse); @@ -183,7 +170,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); } } @@ -196,7 +183,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url host(AzureSdkHttpbinServer::Get()); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); CheckBodyFromStream(*response, expectedResponseBodySize); @@ -204,11 +191,11 @@ namespace Azure { namespace Core { namespace Test { request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false); // Add a header and send again. Response should return that header in the body request.SetHeader("123", "456"); - response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto body = response->ExtractBodyStream(); - std::vector responseBody = body->ReadToEnd(Azure::Core::Context::ApplicationContext); + std::vector responseBody = body->ReadToEnd(Context{}); auto jsonBody = json::parse(responseBody); // Look for the header we added in the second request. @@ -225,7 +212,7 @@ namespace Azure { namespace Core { namespace Test { // loop sending request for (auto i = 0; i < 50; i++) { - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); checkResponseCode(response->GetStatusCode()); CheckBodyFromStream(*response, expectedResponseBodySize); @@ -238,7 +225,7 @@ namespace Azure { namespace Core { namespace Test { auto expectedResponseBodySize = 0; auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, host, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); CheckBodyFromStream(*response, expectedResponseBodySize); @@ -256,7 +243,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -272,7 +259,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request( Azure::Core::Http::HttpMethod::Delete, host, &bodyRequest, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -288,7 +275,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request( Azure::Core::Http::HttpMethod::Patch, host, &bodyRequest, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); if (response->GetStatusCode() == Http::HttpStatusCode::Ok) @@ -310,7 +297,7 @@ namespace Azure { namespace Core { namespace Test { "sent to a client."); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); CheckBodyFromStream(*response, expectedResponseBodySize, expectedChunkResponse); @@ -322,7 +309,7 @@ namespace Azure { namespace Core { namespace Test { std::string expectedType("This is the Response Type"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, true); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); Azure::Response responseT(expectedType, std::move(response)); auto& r = responseT.RawResponse; @@ -352,7 +339,7 @@ namespace Azure { namespace Core { namespace Test { = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest); // Make transport adapter to read all stream content for uploading instead of chunks { - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); CheckBodyFromBuffer(*response, expectedResponseBodySize); @@ -369,7 +356,7 @@ namespace Azure { namespace Core { namespace Test { auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest, false); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode( response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::MethodNotAllowed); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -407,8 +394,8 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url hostPath(AzureSdkHttpbinServer::Delay() + "/2"); // 2 seconds delay on server for (int i = 0; i < 10; i++) { - Azure::Core::Context cancelThis = Azure::Core::Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::milliseconds(500)); + Azure::Core::Context cancelThis + = Context{std::chrono::system_clock::now() + std::chrono::milliseconds(500)}; auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, hostPath); @@ -461,9 +448,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url host("http://unresolvedHost.org/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::RequestFailedException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::RequestFailedException); } TEST_P(TransportAdapter, validNonAsciiHost) @@ -472,33 +457,25 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url host(u8"http://unresolvedHost\u6F22\u5B57.org/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } { Azure::Core::Url host("http://unresolvedHost\xE9\x87\x91.org/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } { Azure::Core::Url host(u8"http://unresolvedHost\uC328.org/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } { Azure::Core::Url host("http://\0/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } } @@ -508,25 +485,19 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url host("http://unresolvedHost\xC0\x41\x42\xFE\xFE\xFF\xFF.org/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } { Azure::Core::Url host("http://\xC0\x76\x77/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } { Azure::Core::Url host("http://\xD8\x00\x01\x00/get"); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); - EXPECT_THROW( - m_pipeline->Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException); } } @@ -539,7 +510,7 @@ namespace Azure { namespace Core { namespace Test { // test dynamic cast try { - auto result = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto result = m_pipeline->Send(request, Context{}); } catch (const Azure::Core::RequestFailedException& err) { @@ -568,7 +539,7 @@ namespace Azure { namespace Core { namespace Test { auto request = Azure::Core::Http::Request( Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false); { - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -594,7 +565,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false); // Make transport adapter to read default chunk size { - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -619,7 +590,7 @@ namespace Azure { namespace Core { namespace Test { auto request = Azure::Core::Http::Request( Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false); { - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Context{}); checkResponseCode(response->GetStatusCode()); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); @@ -670,7 +641,7 @@ namespace Azure { namespace Core { namespace Test { auto body = response.ExtractBodyStream(); EXPECT_NE(body, nullptr); - std::vector bodyVector = body->ReadToEnd(Azure::Core::Context::ApplicationContext); + std::vector bodyVector = body->ReadToEnd(Context{}); int64_t bodySize = body->Length(); EXPECT_EQ(bodySize, size); bodySize = bodyVector.size(); diff --git a/sdk/core/azure-core/test/ut/transport_policy_options.cpp b/sdk/core/azure-core/test/ut/transport_policy_options.cpp index 1454a4926..e41baf099 100644 --- a/sdk/core/azure-core/test/ut/transport_policy_options.cpp +++ b/sdk/core/azure-core/test/ut/transport_policy_options.cpp @@ -234,7 +234,7 @@ namespace Azure { namespace Core { namespace Test { auto body = response.ExtractBodyStream(); EXPECT_NE(body, nullptr); - std::vector bodyVector = body->ReadToEnd(Azure::Core::Context::ApplicationContext); + std::vector bodyVector = body->ReadToEnd(Azure::Core::Context{}); int64_t bodySize = body->Length(); EXPECT_EQ(bodySize, size); @@ -446,7 +446,7 @@ namespace Azure { namespace Core { namespace Test { HttpPipeline pipeline(CreateHttpPipeline(transportOptions)); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); - auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); + auto response = pipeline.Send(request, Azure::Core::Context{}); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); } catch (Azure::Core::Http::TransportException const&) @@ -506,7 +506,7 @@ namespace Azure { namespace Core { namespace Test { { auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); - auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); + auto response = pipeline.Send(request, Azure::Core::Context{}); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); } } @@ -521,8 +521,7 @@ namespace Azure { namespace Core { namespace Test { { auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); EXPECT_THROW( - pipeline.Send(request, Azure::Core::Context::ApplicationContext), - Azure::Core::Http::TransportException); + pipeline.Send(request, Azure::Core::Context{}), Azure::Core::Http::TransportException); } } { @@ -544,7 +543,7 @@ namespace Azure { namespace Core { namespace Test { { auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); - auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); + auto response = pipeline.Send(request, Azure::Core::Context{}); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); } } @@ -692,7 +691,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url url(AzureSdkHttpbinServer::Get()); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url); - auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); + auto response = pipeline.Send(request, Azure::Core::Context{}); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); } #endif @@ -816,7 +815,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url(TestProxyUrl() + "/record/start"), &postBody); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Azure::Core::Context{}); auto& responseHeaders = response->GetHeaders(); auto responseId = responseHeaders.find("x-recording-id"); return Azure::Response(responseId->second, std::move(response)); @@ -828,7 +827,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Http::HttpMethod::Post, Azure::Core::Url(TestProxyUrl() + "/record/stop")); request.SetHeader("x-recording-id", recordingId); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Azure::Core::Context{}); auto responseCode = response->GetStatusCode(); return Azure::Response( responseCode, std::move(response)); @@ -847,7 +846,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url(TestProxyUrl() + "/playback/start"), &postBody); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Azure::Core::Context{}); auto& responseHeaders = response->GetHeaders(); auto responseId = responseHeaders.find("x-recording-id"); return Azure::Response(responseId->second, std::move(response)); @@ -861,7 +860,7 @@ namespace Azure { namespace Core { namespace Test { Azure::Core::Url(TestProxyUrl() + "/playback/stop")); request.SetHeader("x-recording-id", recordingId); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Azure::Core::Context{}); auto responseCode = response->GetStatusCode(); return Azure::Response( responseCode, std::move(response)); @@ -881,7 +880,7 @@ namespace Azure { namespace Core { namespace Test { request.SetHeader("x-recording-id", recordingId); request.SetHeader("x-recording-mode", (isRecording ? "record" : "playback")); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Azure::Core::Context{}); std::string responseBody(response->GetBody().begin(), response->GetBody().end()); return Azure::Response(responseBody, std::move(response)); } @@ -891,7 +890,7 @@ namespace Azure { namespace Core { namespace Test { auto request = Azure::Core::Http::Request( Azure::Core::Http::HttpMethod::Get, Azure::Core::Url(TestProxyUrl() + "/Admin/IsAlive")); - auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); + auto response = m_pipeline->Send(request, Azure::Core::Context{}); auto statusCode = response->GetStatusCode(); return Azure::Response(statusCode, std::move(response)); } diff --git a/sdk/core/perf/README.md b/sdk/core/perf/README.md index 53f1310d8..4e3840877 100644 --- a/sdk/core/perf/README.md +++ b/sdk/core/perf/README.md @@ -154,7 +154,7 @@ int main(int argc, char** argv) }}}; // Call the `Run` method with a context, the tests and the application arguments to launch the program. - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/core/perf/test/src/random_stream_test.cpp b/sdk/core/perf/test/src/random_stream_test.cpp index e78764b32..5787ed239 100644 --- a/sdk/core/perf/test/src/random_stream_test.cpp +++ b/sdk/core/perf/test/src/random_stream_test.cpp @@ -16,11 +16,11 @@ TEST(circular_stream, basic) std::vector buffer2(chunk); // 1st read - auto count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context::ApplicationContext); + auto count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context{}); EXPECT_EQ(count, chunk); // 2nd read - count = r_stream->Read(buffer2.data(), chunk, Azure::Core::Context::ApplicationContext); + count = r_stream->Read(buffer2.data(), chunk, Azure::Core::Context{}); EXPECT_EQ(count, chunk); for (size_t i = 0; i != chunk; i++) { @@ -28,7 +28,7 @@ TEST(circular_stream, basic) } // 3nd read - count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context::ApplicationContext); + count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context{}); EXPECT_EQ(count, chunk); for (size_t i = 0; i != chunk; i++) { @@ -36,7 +36,7 @@ TEST(circular_stream, basic) } // 4nd read - count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context::ApplicationContext); + count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context{}); EXPECT_EQ(count, 0U); // should not change buffer for (size_t i = 0; i != chunk; i++) diff --git a/sdk/eventhubs/azure-messaging-eventhubs/test/perf/src/azure_eventhubs_perf_test.cpp b/sdk/eventhubs/azure-messaging-eventhubs/test/perf/src/azure_eventhubs_perf_test.cpp index 38e5958d7..0a3631ab4 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/test/perf/src/azure_eventhubs_perf_test.cpp +++ b/sdk/eventhubs/azure-messaging-eventhubs/test/perf/src/azure_eventhubs_perf_test.cpp @@ -12,7 +12,7 @@ int main(int argc, char** argv) std::vector tests{ Azure::Messaging::EventHubs::PerfTest::Batch::BatchTest::GetTestMetadata()}; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/test/ut/consumer_client_test.cpp b/sdk/eventhubs/azure-messaging-eventhubs/test/ut/consumer_client_test.cpp index d7e0ba3f2..ae247897b 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/test/ut/consumer_client_test.cpp +++ b/sdk/eventhubs/azure-messaging-eventhubs/test/ut/consumer_client_test.cpp @@ -385,12 +385,9 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test { EXPECT_EQ(totalReceived, numberOfEvents); // We have consumed all the events. Attempting to consume one more should block. - { - Azure::Core::Context timeout = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::seconds(3)); - EXPECT_THROW( - partitionClient.ReceiveEvents(50, timeout), Azure::Core::OperationCancelledException); - } + Azure::Core::Context timeout{Azure::DateTime::clock::now() + std::chrono::seconds(3)}; + EXPECT_THROW( + partitionClient.ReceiveEvents(50, timeout), Azure::Core::OperationCancelledException); } eventhubNamespace.DeleteEventHub(eventHubName); } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/test/ut/processor_test.cpp b/sdk/eventhubs/azure-messaging-eventhubs/test/ut/processor_test.cpp index 1931e5d60..724f18515 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/test/ut/processor_test.cpp +++ b/sdk/eventhubs/azure-messaging-eventhubs/test/ut/processor_test.cpp @@ -86,8 +86,8 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test { void TestWithLoadBalancer(Models::ProcessorStrategy processorStrategy) { - Azure::Core::Context context = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::minutes(5)); + Azure::Core::Context context + = Azure::Core::Context{Azure::DateTime::clock::now() + std::chrono::minutes(5)}; std::string eventHubName{GetEnv("EVENTHUB_NAME")}; @@ -163,8 +163,7 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test { void TestWithLoadBalancerSingleThreaded(Models::ProcessorStrategy processorStrategy) { - Azure::Core::Context context = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::minutes(5)); + Azure::Core::Context context{Azure::DateTime::clock::now() + std::chrono::minutes(5)}; Azure::Messaging::EventHubs::ConsumerClientOptions consumerClientOptions; consumerClientOptions.ApplicationID @@ -217,8 +216,7 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test { void TestPartitionAcquisition(Models::ProcessorStrategy processorStrategy) { - Azure::Core::Context context = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::minutes(5)); + Azure::Core::Context context{Azure::DateTime::clock::now() + std::chrono::minutes(5)}; Azure::Messaging::EventHubs::ConsumerClientOptions consumerClientOptions; consumerClientOptions.ApplicationID @@ -579,8 +577,7 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test { } // Attempts to retrieve a partition client should throw because there are no clients available. - auto context = Azure::Core::Context::ApplicationContext.WithDeadline( - Azure::DateTime::clock::now() + std::chrono::milliseconds(50)); + Azure::Core::Context context{Azure::DateTime::clock::now() + std::chrono::milliseconds(50)}; EXPECT_ANY_THROW(processor.NextPartitionClient(context)); while (!partitionClients.empty()) diff --git a/sdk/identity/azure-identity/samples/azure_cli_credential.cpp b/sdk/identity/azure-identity/samples/azure_cli_credential.cpp index 4f3e14ccf..c339da944 100644 --- a/sdk/identity/azure-identity/samples/azure_cli_credential.cpp +++ b/sdk/identity/azure-identity/samples/azure_cli_credential.cpp @@ -17,7 +17,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", azureCliCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(Azure::Core::Context{}); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/chained_token_credential.cpp b/sdk/identity/azure-identity/samples/chained_token_credential.cpp index cd678b9f3..6bbcebb69 100644 --- a/sdk/identity/azure-identity/samples/chained_token_credential.cpp +++ b/sdk/identity/azure-identity/samples/chained_token_credential.cpp @@ -27,7 +27,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", chainedTokenCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/client_certificate_credential.cpp b/sdk/identity/azure-identity/samples/client_certificate_credential.cpp index df2f7abf7..f5577c139 100644 --- a/sdk/identity/azure-identity/samples/client_certificate_credential.cpp +++ b/sdk/identity/azure-identity/samples/client_certificate_credential.cpp @@ -27,7 +27,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", clientCertificateCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/client_secret_credential.cpp b/sdk/identity/azure-identity/samples/client_secret_credential.cpp index e2feb3072..b69f2002e 100644 --- a/sdk/identity/azure-identity/samples/client_secret_credential.cpp +++ b/sdk/identity/azure-identity/samples/client_secret_credential.cpp @@ -26,7 +26,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", clientSecretCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/default_azure_credential.cpp b/sdk/identity/azure-identity/samples/default_azure_credential.cpp index 90d406ce4..e98a9dbb1 100644 --- a/sdk/identity/azure-identity/samples/default_azure_credential.cpp +++ b/sdk/identity/azure-identity/samples/default_azure_credential.cpp @@ -21,7 +21,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", defaultAzureCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/environment_credential.cpp b/sdk/identity/azure-identity/samples/environment_credential.cpp index bbac3c865..4b6e5af81 100644 --- a/sdk/identity/azure-identity/samples/environment_credential.cpp +++ b/sdk/identity/azure-identity/samples/environment_credential.cpp @@ -19,7 +19,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", environmentCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/managed_identity_credential.cpp b/sdk/identity/azure-identity/samples/managed_identity_credential.cpp index e52a11dd8..1c50eca10 100644 --- a/sdk/identity/azure-identity/samples/managed_identity_credential.cpp +++ b/sdk/identity/azure-identity/samples/managed_identity_credential.cpp @@ -19,7 +19,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", managedIdentityCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/samples/workload_identity_credential.cpp b/sdk/identity/azure-identity/samples/workload_identity_credential.cpp index 350765444..b098b061a 100644 --- a/sdk/identity/azure-identity/samples/workload_identity_credential.cpp +++ b/sdk/identity/azure-identity/samples/workload_identity_credential.cpp @@ -23,7 +23,7 @@ int main() Azure::Service::Client azureServiceClient("serviceUrl", workloadIdentityCredential); // Step 3: Start using the Azure Service Client. - azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); + azureServiceClient.DoSomething(); std::cout << "Success!" << std::endl; } diff --git a/sdk/identity/azure-identity/test/perf/src/azure_identity_perf_test.cpp b/sdk/identity/azure-identity/test/perf/src/azure_identity_perf_test.cpp index d6809dc3f..7810a89c7 100644 --- a/sdk/identity/azure-identity/test/perf/src/azure_identity_perf_test.cpp +++ b/sdk/identity/azure-identity/test/perf/src/azure_identity_perf_test.cpp @@ -16,7 +16,7 @@ int main(int argc, char** argv) Azure::Identity::Test::EnvironmentCredentialTest::GetTestMetadata(), Azure::Identity::Test::SecretCredentialTest::GetTestMetadata()}; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/identity/azure-identity/test/ut/azure_cli_credential_test.cpp b/sdk/identity/azure-identity/test/ut/azure_cli_credential_test.cpp index cd7994a6d..e53b9ac40 100644 --- a/sdk/identity/azure-identity/test/ut/azure_cli_credential_test.cpp +++ b/sdk/identity/azure-identity/test/ut/azure_cli_credential_test.cpp @@ -297,8 +297,7 @@ TEST(AzureCliCredential, ContextCancelled) TokenRequestContext trc; trc.Scopes.push_back("https://storage.azure.com/.default"); - auto context = Context::ApplicationContext.WithDeadline( - std::chrono::system_clock::now() + std::chrono::hours(24)); + Context context{std::chrono::system_clock::now() + std::chrono::hours(24)}; std::atomic thread1Started(false); diff --git a/sdk/identity/azure-identity/test/ut/token_credential_test.cpp b/sdk/identity/azure-identity/test/ut/token_credential_test.cpp index e9468b553..9b799ebb6 100644 --- a/sdk/identity/azure-identity/test/ut/token_credential_test.cpp +++ b/sdk/identity/azure-identity/test/ut/token_credential_test.cpp @@ -68,8 +68,7 @@ TEST_F(TokenCredentialTest, ClientSecret) tokenRequestContext.Scopes = {"https://vault.azure.net/.default"}; tokenRequestContext.MinimumExpiration = std::chrono::hours(1000000); - auto const token = clientSecretCredential->GetToken( - tokenRequestContext, Azure::Core::Context::ApplicationContext); + auto const token = clientSecretCredential->GetToken(tokenRequestContext, Azure::Core::Context{}); EXPECT_FALSE(token.Token.empty()); EXPECT_GE(token.ExpiresOn, std::chrono::system_clock::now()); @@ -90,8 +89,7 @@ TEST_F(TokenCredentialTest, EnvironmentCredential) tokenRequestContext.Scopes = {"https://vault.azure.net/.default"}; tokenRequestContext.MinimumExpiration = std::chrono::hours(1000000); - auto const token = clientSecretCredential->GetToken( - tokenRequestContext, Azure::Core::Context::ApplicationContext); + auto const token = clientSecretCredential->GetToken(tokenRequestContext, Azure::Core::Context{}); EXPECT_FALSE(token.Token.empty()); EXPECT_GE(token.ExpiresOn, std::chrono::system_clock::now()); diff --git a/sdk/identity/azure-identity/vcpkg/vcpkg.json b/sdk/identity/azure-identity/vcpkg/vcpkg.json index 1437a3fca..df328c228 100644 --- a/sdk/identity/azure-identity/vcpkg/vcpkg.json +++ b/sdk/identity/azure-identity/vcpkg/vcpkg.json @@ -18,7 +18,7 @@ { "name": "azure-core-cpp", "default-features": false, - "version>=": "1.9.0" + "version>=": "1.14.0-beta.1" }, { "name": "openssl", diff --git a/sdk/keyvault/azure-security-keyvault-certificates/test/perf/src/azure_security_keyvault_certificates_perf_test.cpp b/sdk/keyvault/azure-security-keyvault-certificates/test/perf/src/azure_security_keyvault_certificates_perf_test.cpp index 86b3aaf71..aebf51c41 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/test/perf/src/azure_security_keyvault_certificates_perf_test.cpp +++ b/sdk/keyvault/azure-security-keyvault-certificates/test/perf/src/azure_security_keyvault_certificates_perf_test.cpp @@ -12,7 +12,7 @@ int main(int argc, char** argv) std::vector tests{ Azure::Security::KeyVault::Certificates::Test::GetCertificate::GetTestMetadata()}; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/keyvault/azure-security-keyvault-keys/test/perf/src/azure_security_keyvault_keys_perf_test.cpp b/sdk/keyvault/azure-security-keyvault-keys/test/perf/src/azure_security_keyvault_keys_perf_test.cpp index 4d27b4f4f..3a7460e3d 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/test/perf/src/azure_security_keyvault_keys_perf_test.cpp +++ b/sdk/keyvault/azure-security-keyvault-keys/test/perf/src/azure_security_keyvault_keys_perf_test.cpp @@ -12,7 +12,7 @@ int main(int argc, char** argv) std::vector tests{ Azure::Security::KeyVault::Keys::Test::GetKey::GetTestMetadata()}; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/keyvault/azure-security-keyvault-keys/test/ut/key_client_delete_test_live.cpp b/sdk/keyvault/azure-security-keyvault-keys/test/ut/key_client_delete_test_live.cpp index 97d173175..d688d6ffe 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/test/ut/key_client_delete_test_live.cpp +++ b/sdk/keyvault/azure-security-keyvault-keys/test/ut/key_client_delete_test_live.cpp @@ -49,7 +49,7 @@ TEST_F(KeyVaultKeyClient, DeleteKey) // for so long if something happens and no exception is thrown (paranoid scenario) auto duration = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); - auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); + Azure::Core::Context cancelToken{duration}; auto keyResponseLRO = client.StartDeleteKey(keyName); auto expectedStatusToken = keyName; @@ -124,7 +124,7 @@ TEST_F(KeyVaultKeyClient, DoubleDelete) { auto duration = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); - auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); + Azure::Core::Context cancelToken{duration}; auto keyResponseLRO = client.StartDeleteKey(keyName); auto keyResponse = keyResponseLRO.PollUntilDone(m_testPollingIntervalMs, cancelToken); } @@ -197,7 +197,7 @@ TEST_F(KeyVaultKeyClient, CreateDeletedKey) { auto duration = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); - auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); + Azure::Core::Context cancelToken{duration}; auto keyResponseLRO = client.StartDeleteKey(keyName); auto keyResponse = keyResponseLRO.PollUntilDone(m_testPollingIntervalMs, cancelToken); } @@ -281,7 +281,7 @@ TEST_F(KeyVaultKeyClient, GetDeletedKey) // Wait until key is deleted auto duration = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); - auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); + Azure::Core::Context cancelToken{duration}; auto keyResponseLRO = client.StartDeleteKey(keyName); auto expectedStatusToken = m_keyVaultUrl diff --git a/sdk/keyvault/azure-security-keyvault-keys/vcpkg/vcpkg.json b/sdk/keyvault/azure-security-keyvault-keys/vcpkg/vcpkg.json index 94ca3da71..9857f937f 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/vcpkg/vcpkg.json +++ b/sdk/keyvault/azure-security-keyvault-keys/vcpkg/vcpkg.json @@ -18,7 +18,7 @@ { "name": "azure-core-cpp", "default-features": false, - "version>=": "1.9.0" + "version>=": "1.14.0-beta.1" }, { "name": "vcpkg-cmake", diff --git a/sdk/keyvault/azure-security-keyvault-secrets/test/perf/src/azure_security_keyvault_secrets_perf_test.cpp b/sdk/keyvault/azure-security-keyvault-secrets/test/perf/src/azure_security_keyvault_secrets_perf_test.cpp index 932159fcc..95d95e69a 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/test/perf/src/azure_security_keyvault_secrets_perf_test.cpp +++ b/sdk/keyvault/azure-security-keyvault-secrets/test/perf/src/azure_security_keyvault_secrets_perf_test.cpp @@ -12,7 +12,7 @@ int main(int argc, char** argv) std::vector tests{ Azure::Security::KeyVault::Secrets::Test::GetSecret::GetTestMetadata()}; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/storage/azure-storage-blobs/samples/CMakeLists.txt b/sdk/storage/azure-storage-blobs/samples/CMakeLists.txt index a6cb133c0..fb83d78c1 100644 --- a/sdk/storage/azure-storage-blobs/samples/CMakeLists.txt +++ b/sdk/storage/azure-storage-blobs/samples/CMakeLists.txt @@ -26,3 +26,7 @@ create_per_service_target_build_for_sample(storage transactional-checksum) add_executable(blob-query blob_query.cpp) target_link_libraries(blob-query PRIVATE azure-storage-blobs get-env-helper) create_per_service_target_build_for_sample(storage blob-query) + +add_executable(blob_list_operation_with_timeout blob_list_operation_with_timeout.cpp) +target_link_libraries(blob_list_operation_with_timeout PRIVATE azure-storage-blobs get-env-helper) +create_per_service_target_build_for_sample(storage blob_list_operation_with_timeout) diff --git a/sdk/storage/azure-storage-blobs/samples/blob_list_operation_with_timeout.cpp b/sdk/storage/azure-storage-blobs/samples/blob_list_operation_with_timeout.cpp new file mode 100644 index 000000000..5b8f47804 --- /dev/null +++ b/sdk/storage/azure-storage-blobs/samples/blob_list_operation_with_timeout.cpp @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#include +#include + +#include +#include + +std::string GetConnectionString() +{ + const static std::string ConnectionString = ""; + + if (!ConnectionString.empty()) + { + return ConnectionString; + } + const static std::string envConnectionString = std::getenv("AZURE_STORAGE_CONNECTION_STRING"); + if (!envConnectionString.empty()) + { + return envConnectionString; + } + throw std::runtime_error("Cannot find connection string."); +} + +int main() +{ + using namespace Azure::Storage::Blobs; + + const std::string containerName = "sample-container"; + const std::string blobName = "sample-blob"; + const std::string blobContent = "Hello Azure!"; + + { + // Create some containers and blobs for test + for (int i = 0; i < 2; ++i) + { + // @begin_snippet: CreateBlobContext + Azure::Core::Context cancelledIn5s{ + std::chrono::system_clock::now() + std::chrono::seconds(5)}; + + auto containerClient = BlobContainerClient::CreateFromConnectionString( + GetConnectionString(), containerName + std::to_string(i)); + containerClient.CreateIfNotExists({}, cancelledIn5s); + for (int j = 0; j < 3; ++j) + { + BlockBlobClient blobClient + = containerClient.GetBlockBlobClient(blobName + std::to_string(j)); + blobClient.UploadFrom( + reinterpret_cast(blobContent.data()), + blobContent.size(), + {}, + cancelledIn5s); + } + // @end_snippet: CreateBlobContext + } + } + + auto serviceClient = BlobServiceClient::CreateFromConnectionString(GetConnectionString()); + + for (auto containerPage = serviceClient.ListBlobContainers(); containerPage.HasPage(); + containerPage.MoveToNextPage()) + { + for (auto& container : containerPage.BlobContainers) + { + // Below is what you want to do with each container + std::cout << "blob container: " << container.Name << std::endl; + for (auto blobPage = serviceClient.GetBlobContainerClient(container.Name).ListBlobs(); + blobPage.HasPage(); + blobPage.MoveToNextPage()) + { + for (auto& blob : blobPage.Blobs) + { + // Below is what you want to do with each blob + std::cout << " blob: " << blob.Name << std::endl; + } + } + } + } + + return 0; +} diff --git a/sdk/storage/azure-storage-blobs/test/perf/CMakeLists.txt b/sdk/storage/azure-storage-blobs/test/perf/CMakeLists.txt index 66b92dcfc..65679ed82 100644 --- a/sdk/storage/azure-storage-blobs/test/perf/CMakeLists.txt +++ b/sdk/storage/azure-storage-blobs/test/perf/CMakeLists.txt @@ -46,11 +46,6 @@ target_include_directories( $ ) -if (MSVC) - # allow msvc to use getenv() - target_compile_options(azure-storage-blobs-perf PUBLIC /wd4996) -endif() - # link the `azure-perf` lib together with any other library which will be used for the tests. target_link_libraries(azure-storage-blobs-perf PRIVATE Azure::azure-storage-blobs azure-perf) diff --git a/sdk/storage/azure-storage-blobs/test/perf/inc/azure/storage/blobs/test/upload_blob_test.hpp b/sdk/storage/azure-storage-blobs/test/perf/inc/azure/storage/blobs/test/upload_blob_test.hpp index 9b30a7b47..7869e3298 100644 --- a/sdk/storage/azure-storage-blobs/test/perf/inc/azure/storage/blobs/test/upload_blob_test.hpp +++ b/sdk/storage/azure-storage-blobs/test/perf/inc/azure/storage/blobs/test/upload_blob_test.hpp @@ -48,8 +48,7 @@ namespace Azure { namespace Storage { namespace Blobs { namespace Test { BlobsTest::Setup(); long size = m_options.GetMandatoryOption("Size"); - m_uploadBuffer = Azure::Perf::RandomStream::Create(size)->ReadToEnd( - Azure::Core::Context::ApplicationContext); + m_uploadBuffer = Azure::Perf::RandomStream::Create(size)->ReadToEnd(Azure::Core::Context{}); } /** diff --git a/sdk/storage/azure-storage-blobs/test/perf/src/azure_storage_blobs_perf_test.cpp b/sdk/storage/azure-storage-blobs/test/perf/src/azure_storage_blobs_perf_test.cpp index ce495ade9..de022bcc6 100644 --- a/sdk/storage/azure-storage-blobs/test/perf/src/azure_storage_blobs_perf_test.cpp +++ b/sdk/storage/azure-storage-blobs/test/perf/src/azure_storage_blobs_perf_test.cpp @@ -31,7 +31,7 @@ int main(int argc, char** argv) Azure::Storage::Blobs::Test::DownloadBlobWithPipelineOnly::GetTestMetadata() }; - Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); + Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv); return 0; } diff --git a/sdk/storage/azure-storage-common/vcpkg/vcpkg.json b/sdk/storage/azure-storage-common/vcpkg/vcpkg.json index f9c017b65..816e5f63e 100644 --- a/sdk/storage/azure-storage-common/vcpkg/vcpkg.json +++ b/sdk/storage/azure-storage-common/vcpkg/vcpkg.json @@ -18,7 +18,7 @@ { "name": "azure-core-cpp", "default-features": false, - "version>=": "1.12.0" + "version>=": "1.14.0-beta.1" }, { "name": "libxml2",