### Start() Source: https://userver.tech/d2/d52/classurabbitmq_1_1ConsumerBase.html Starts consuming messages from the broker. If the consumer is already running, this method has no effect. It is designed not to throw; any initial setup failures will result in the library attempting to restart the consumer in the background. ```APIDOC ## Start() ### Description Initiates message consumption from the RabbitMQ broker. Calling this on an already running consumer has no effect. This method is non-throwing; background restarts will handle initial setup failures. ### Method `void Start()` ``` -------------------------------- ### main function setup Source: https://userver.tech/d1/de1/easy_2samples_26__pg__service__template__no__http__with_2src_2main_8cpp_source.html Initializes the component list for a minimal server, appending various components like TestsuiteSupport, HTTP client, DNS client, ActionClient, DepsComponent, Postgres, and a custom handler. Finally, it starts the daemon with the configured component list. ```cpp auto component_list = components::MinimalServerComponentList() .Append() .AppendComponentList(clients::http::ComponentList()) .Append() .Append() .Append() .Append("postgres") .Append("/log-POST"); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### Starting the Service Source: https://userver.tech/d4/d31/md_en_2userver_2tutorial_2postgres__service.html Demonstrates how to start the Userver PostgreSQL service sample manually after building. ```bash make start-userver-samples-postgres_service ``` ```bash ./samples/postgres_service/userver-samples-postgres_service -c ``` -------------------------------- ### start() Source: https://userver.tech/d8/d81/classpytest__userver_1_1grpc_1_1MockserverSession.html Starts the gRPC mock server. It is recommended to use the async context manager syntax for starting the mockserver whenever possible. ```APIDOC ## start() ### Description Starts the server. ### Method `start(_self_) ### Notes Prefer starting mockserver using the async contextmanager syntax if possible. ``` -------------------------------- ### Start Standalone Service with Service Runner Source: https://userver.tech/df/d07/md_en_2userver_2functional__testing.html Example of how to start a standalone service with mocks and database using the `--service-runner-mode` flag. Requires the `-s` flag to disable console output capture. ```bash ./build-debug/runtests-service_template -s --service-runner-mode ``` -------------------------------- ### Start() Source: https://userver.tech/dd/d33/classurabbitmq_1_1ConsumerBase-members.html Starts the consumer. ```APIDOC ## Start() ### Description Starts the consumer, initiating message consumption. ### Method `void Start()` ``` -------------------------------- ### RedisTest Fixture Example Source: https://userver.tech/d8/d84/classstorages_1_1redis_1_1utest_1_1RedisTest.html Demonstrates how to use the RedisTest fixture to interact with Redis. Includes setup with RedisLocal and basic list operations. Ensure Redis or Valkey is running and accessible. ```cpp #include using RedisTest = storages::redis::utest::RedisTest; UTEST_F(RedisTest, Sample) { auto client = GetClient(); client->Rpush("sample_list", "a", {}).Get(); client->Rpush("sample_list", "b", {}).Get(); const auto length = client->Llen("sample_list", {}).Get(); EXPECT_EQ(length, 2); } ``` -------------------------------- ### Start Source: https://userver.tech/d0/d68/classserver_1_1Server.html Starts the server. ```APIDOC ## Start ### Description Starts the server. ### Method N/A (Method within the Server class) ### Endpoint N/A ### Parameters None ### Response None ``` -------------------------------- ### AnyStorage Usage Example Source: https://userver.tech/d7/d1c/classutils_1_1AnyStorage.html Demonstrates basic usage of AnyStorage, including Emplace, Get, and Set operations. The data is rewritten if already stored. ```cpp #include struct MyStorage {}; const utils::AnyStorageDataTag kChar; const utils::AnyStorageDataTag kInt; const utils::AnyStorageDataTag kStr; const utils::AnyStorageDataTag kStr2; struct BoolStorage {}; const utils::AnyStorageDataTag kBool; TEST(AnyStorage, Simple) { utils::AnyStorage storage; EXPECT_EQ(storage.GetOptional(kInt), nullptr); storage.Emplace(kInt, 1); storage.Emplace(kStr, std::string{"1"}); EXPECT_EQ(*storage.GetOptional(kInt), 1); EXPECT_EQ(storage.Get(kInt), 1); EXPECT_EQ(storage.Get(kStr), "1"); storage.Set(kInt, 2); storage.Set(kStr, std::string{"2"}); EXPECT_EQ(storage.Get(kInt), 2); EXPECT_EQ(storage.Get(kStr), "2"); storage.Emplace(kStr, std::string{"3"}); storage.Emplace(kStr, std::string{"4"}); EXPECT_EQ(storage.Get(kStr), "4"); } ``` -------------------------------- ### start Source: https://userver.tech/d5/d02/classpytest__userver_1_1chaos_1_1BaseGate.html Opens the socket and starts accepting tasks. ```APIDOC ## start() ### Description Opens the socket and starts accepting tasks. ### Method start ``` -------------------------------- ### Minimal Server Component List Setup Source: https://userver.tech/d9/dfb/samples_2static_service_2main_8cpp-example.html Configures the minimal server component list, appending the custom MessagesHandler, FsCache, and HttpHandlerStatic. This is the entry point for starting the Userver application. ```cpp int main(int argc, char* argv[]) { const auto component_list = components::MinimalServerComponentList() .Append("handler-messages") .Append("fs-cache-main") .Append(); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### Start HTTP Caching Sample Source: https://userver.tech/dc/d8a/md_en_2userver_2tutorial_2http__caching.html Start the compiled sample using 'make start-userver-samples-http_caching' or manually with the executable and configuration file. ```bash make start-userver-samples-http_caching ``` ```bash ./samples/http_caching/userver-samples-http_caching -c ``` -------------------------------- ### Setup Environment CMake Function Source: https://userver.tech/dd/d6f/md_en_2userver_2roadmap__and__changelog__v1.html Illustrates the change in CMake setup for userver, moving from including a setup script to calling a dedicated function after adding the subdirectory. ```cmake include(third_party/userver/cmake/SetupEnvironment.cmake) add_subdirectory(third_party/userver) ``` ```cmake add_subdirectory(third_party/userver) userver_setup_environment() ``` -------------------------------- ### Start Source: https://userver.tech/d0/d40/classcongestion__control_1_1v2_1_1Controller-members.html Starts the controller. ```APIDOC ## Start ### Description Starts the controller. ### Method POST ### Endpoint N/A (Method within a class) ``` -------------------------------- ### Start Source: https://userver.tech/db/d27/classugrpc_1_1server_1_1Server-members.html Starts the gRPC server, making it ready to accept incoming requests. ```APIDOC ## Start ### Description Initiates the operation of the gRPC server. Once started, the server will begin listening for and processing incoming client requests. ### Method `Start()` ``` -------------------------------- ### Install Userver via CMake Source: https://userver.tech/dd/d6f/md_en_2userver_2roadmap__and__changelog__v1.html Userver can now be installed using the `cmake --install` command. Refer to userver_install for detailed information. ```bash cmake --install ``` -------------------------------- ### Static Configuration Example Source: https://userver.tech/d2/d09/classugrpc_1_1client_1_1middlewares_1_1log_1_1Component.html An example demonstrating how to configure the grpc-client-logging component to enable logs for gRPC clients in production. ```APIDOC ## Static configuration example: grpc-client-logging: msg-log-level: info msg-size-log-limit: 512 In this example, we enable logs for gRPC clients in production. ``` -------------------------------- ### Static Configuration Example for OnLogRotate Source: https://userver.tech/dc/dde/classserver_1_1handlers_1_1OnLogRotate.html Example of how to configure the OnLogRotate handler in a static configuration file. ```yaml handler-log-level: path: /service/log-level/{level} method: GET,PUT task_processor: monitor-task-processor ``` -------------------------------- ### service_start_timeout() Source: https://userver.tech/namespacemembers_s.html Gets the start timeout for the service, from pytest_userver.plugins.service. ```APIDOC ## service_start_timeout() ### Description Gets the start timeout for the service, from pytest_userver.plugins.service. ### Module pytest_userver.plugins.service ``` -------------------------------- ### Dynamic Debug Log GET Request Output Example Source: https://userver.tech/d6/dc0/dynamic__debug__log_8hpp_source.html This example demonstrates the output format for a GET request to the dynamic debug log handler. It lists logging locations and their current status (0 for disabled, 1 for enabled via handler). ```text project/src/some.cpp:13 0 project/src/some.cpp:23 0 project/src/some.cpp:42 1 project/src/some.cpp:113 0 userver/core/src/server/server.cpp:131 0 ``` -------------------------------- ### Build and Run Instructions Source: https://userver.tech/d4/d31/md_en_2userver_2tutorial_2postgres__service.html Provides commands to build the Userver release version and run the PostgreSQL service sample. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-postgres_service ``` -------------------------------- ### Configure multiple Redis setups in pytest Source: https://userver.tech/d3/da2/md_en_2userver_2tutorial_2redis__service.html Example fixture demonstrating how to configure sentinel, cluster, and standalone Redis setups simultaneously for functional testing. ```python @pytest.fixture(scope='session') def service_env(redis_sentinels, redis_cluster_nodes, redis_cluster_replicas, redis_standalone_node): cluster_shards = [ {'name': f'shard{idx}'} for idx in range( len(redis_cluster_nodes) // (redis_cluster_replicas + 1), ) ] ``` -------------------------------- ### Static Configuration Example Source: https://userver.tech/d1/de3/classugrpc_1_1server_1_1middlewares_1_1deadline__propagation_1_1Component.html Example of how to configure the deadline propagation middleware in YAML. ```APIDOC ## Static Configuration Example: grpc-server-deadline-propagation: prefer-absolute-deadline: true ``` -------------------------------- ### Main Component List Setup Source: https://userver.tech/d1/d3e/samples_2http_caching_2main_8cpp-example.html Sets up the minimal server component list, including HttpCachedTranslations and GreetUser handler, for the userver application. ```cpp int main(int argc, char* argv[]) { const auto component_list = components::MinimalServerComponentList() .Append() .Append() .Append() .Append() .Append() .AppendComponentList(clients::http::ComponentList()); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### Build and Run Kafka Service Sample Source: https://userver.tech/d9/d1c/md_en_2userver_2tutorial_2kafka__service.html Steps to build and run the Kafka service sample. Ensure Kafka binaries are in KAFKA_HOME and topics are defined. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-kafka_service ``` ```bash KAFKA_HOME=/etc/kafka TESTSUITE_KAFKA_CUSTOM_TOPICS=test-topic-1:1,test-topic-2:1 make start-userver-samples-kafka_service ``` ```bash ./samples/kafka_service/userver-samples-kafka_service -c ``` -------------------------------- ### Example cURL Requests to MongoDB Service Source: https://userver.tech/d5/d81/md_en_2userver_2tutorial_2mongo__service.html Demonstrates sending PATCH and GET requests to the /v1/translations endpoint using cURL. Includes an example of fetching data and parsing JSON output. ```bash $ curl -X PATCH 'http://localhost:8090/v1/translations?key=hello&lang=ru&value=Привки' $ curl -X PATCH 'http://localhost:8090/v1/translations?key=hello&lang=ru&value=Дратути' $ curl -X PATCH 'http://localhost:8090/v1/translations?key=hello&lang=ru&value=Здрасьте' $ curl -s http://localhost:8090/v1/translations?last_update=2021-11-01T12:00:00Z | jq ``` -------------------------------- ### Static Configuration Example Source: https://userver.tech/d8/d1f/classcomponents_1_1DynamicConfigClient.html An example of how to configure the DynamicConfigClient component in the service configuration. ```APIDOC ## Static configuration example: ```yaml dynamic-config-client: get-configs-overrides-for-service: true service-name: common_component_list-service http-timeout: 20s http-retries: 5 config-url: http://localhost:8083/ configs-stage: $configs_stage ``` ``` -------------------------------- ### Run TCP Service Sample Source: https://userver.tech/dc/d93/md_en_2userver_2tutorial_2tcp__service.html Demonstrates how to start the TCP service manually using the compiled binary and a static configuration file. ```bash ./samples/tcp_service/userver-samples-tcp_service -c ``` -------------------------------- ### StartServer Method Source: https://userver.tech/d8/d3d/classugrpc_1_1tests_1_1ServiceWithClientFixture.html Starts the gRPC test server with optional client factory settings. Ensure this is called before making any client requests. ```cpp void StartServer(client::ClientFactorySettings &&settings = {}) ``` -------------------------------- ### Alert Declaration Example Source: https://userver.tech/dc/d2f/alerts_2source_8hpp_source.html This snippet shows how to declare an alert source. It is used in the context of logging component setup. ```cpp /// @snippet core/src/logging/component.cpp alert_declaration ``` -------------------------------- ### uservice_oneshot Test Example Source: https://userver.tech/df/d07/md_en_2userver_2functional__testing.html This example demonstrates how to use the uservice_oneshot fixture to test a service's initial state. It starts a new service instance for the test and stops it upon completion, allowing for checks like initial metrics. ```python import pytest @pytest.mark.uservice_oneshot async def test_initial_metrics(service_client, monitor_client): metric = await monitor_client.single_metric('sample-metrics.foo') assert metric.value == 0 ``` -------------------------------- ### Main Function for Service Setup Source: https://userver.tech/df/daf/samples_2flatbuf_service_2main_8cpp-example.html Sets up the component list for the server, including custom FlatBuffers components and client components. This is the entry point for the daemon. ```cpp int main(int argc, char* argv[]) { auto component_list = components::MinimalServerComponentList() // .Append() // .Append() // .AppendComponentList(clients::http::ComponentList()) // .Append(); // return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### Basic HTTP Server with Hello World Route Source: https://userver.tech/db/d04/easy_2samples_20__hello__world_2main_8cpp_source.html This snippet demonstrates how to set up a basic HTTP server using userver's easy interface. It defines a route '/hello' that responds with 'Hello world' to any request. Ensure userver is properly configured and linked. ```cpp #include #include int main(int argc, char* argv[]) { easy::HttpWith<>(argc, argv) .DefaultContentType(http::content_type::kTextPlain) .Route("/hello", [](const server::http::HttpRequest& /*req*/) { return "Hello world"; // Just return the string as a response body }); } ``` -------------------------------- ### TaskProcessor Utilities Source: https://userver.tech/d8/d03/task__processor__fwd_8hpp_source.html Provides functions to get the queue size and worker count of a TaskProcessor, and to register a hook that runs when a thread starts. ```APIDOC ## GetQueueSize ### Description Gets the approximate count of ready-to-run tasks on the specified task processor. ### Signature std::size_t GetQueueSize(const TaskProcessor& task_processor) noexcept ## GetWorkerCount ### Description Gets the number of worker threads in the specified task processor. ### Signature std::size_t GetWorkerCount(const TaskProcessor& task_processor) noexcept ## RegisterThreadStartedHook ### Description Registers a function to be executed on all threads when a task processor is created. This is useful for pre-initializing thread-local variables that have heavy constructors, such as those involving blocking system calls or file access. ### Note This is a low-level function and may not be needed for typical use cases. ### Signature void RegisterThreadStartedHook(std::function hook) ``` -------------------------------- ### StartServer Source: https://userver.tech/d1/d4d/classugrpc_1_1tests_1_1ServiceBase-members.html Starts the server with the given client factory settings. ```APIDOC ## StartServer ### Description Starts the server with the given client factory settings. ### Signature `void StartServer(client::ClientFactorySettings &&settings={})` ``` -------------------------------- ### Concurrent Read/Write Example Source: https://userver.tech/dd/dcf/classengine_1_1io_1_1Socket.html Demonstrates safe concurrent reading and writing to a socket. Ensure proper setup and include the necessary headers. ```cpp #include #include #include #include // Assuming 'listener' is an initialized engine::io::Socket object // and 'deadline' is a valid engine::Deadline object // Example usage within a test or async context: // engine::io::Socket& socket = listener.socket; // auto read_task = engine::AsyncNoSpan([&socket, &deadline] { // for (char expected_data = 0; expected_data <= 100; ++expected_data) { // char c = 0; // const auto recvfrom = socket.RecvSomeFrom(&c, 1, deadline); // EXPECT_EQ(1, recvfrom.bytes_received); // EXPECT_EQ(expected_data, c); // } // }); // const auto& addr = socket.Getsockname(); // for (char send_data = 0; send_data <= 100; ++send_data) { // const auto bytes_sent = socket.SendAllTo(addr, &send_data, 1, deadline); // EXPECT_EQ(bytes_sent, 1); // } // read_task.Get(); ``` -------------------------------- ### HttpServerMock Usage Example Source: https://userver.tech/d2/d6c/http__server__mock_8hpp_source.html This snippet demonstrates the basic usage of HttpServerMock. It shows how to create an instance with a handler and how to get the base URL. ```cpp #include #include #include USERVER_NAMESPACE_BEGIN namespace utest { /// @brief Toy HTTP server for testing; for raw TCP or TLS testing use utest::SimpleServer. /// /// In constructor opens specified ports in localhost address and listens on /// them. On each HTTP request calls user callback. /// /// ## Example usage: /// @snippet core/utest/src/utest/http_server_mock_test.cpp Sample HttpServerMock usage class HttpServerMock { public: /// Structure with HTTP request that is passed to the HttpHandler callback struct HttpRequest { clients::http::HttpMethod method{clients::http::HttpMethod::kGet}; std::string path; std::multimap query; clients::http::Headers headers; std::string body; }; struct HttpRequest {…}; /// Structure with HTTP response to return from the HttpHandler callback struct HttpResponse { int response_status{200}; clients::http::Headers headers; std::string body; }; struct HttpResponse {…}; /// Callback that is invoked on each HTTP request using HttpHandler = std::function; HttpServerMock(HttpHandler http_handler, SimpleServer::Protocol protocol = SimpleServer::kTcpIpV4); /// Returns URL to the server, for example 'http://127.0.0.1:8080' std::string GetBaseUrl() const; std::uint64_t GetConnectionsOpenedCount() const; private: friend class HttpConnection; HttpHandler http_handler_; SimpleServer server_; }; } // namespace utest USERVER_NAMESPACE_END ``` -------------------------------- ### Main Function with Component List Source: https://userver.tech/d9/d1c/md_en_2userver_2tutorial_2kafka__service.html Set up the main function by adding all required components, including Kafka consumer and producer components, and then run the server using utils::DaemonRun. ```cpp int main(int argc, char* argv[]) { const auto components_list = components::MinimalServerComponentList() .Append() .Append() .Append("kafka-consumer") .Append("kafka-producer") .Append() .Append() .Append() .AppendComponentList(clients::http::ComponentList()) .Append() .Append(); return utils::DaemonMain(argc, argv, components_list); } ``` -------------------------------- ### Get Initial Secdist Configuration Source: https://userver.tech/dd/d27/secdist_8hpp_source.html Retrieves the secdist data that was loaded when the service started. This method does not support secdist updates during service operation. ```cpp const storages::secdist::SecdistConfig& Get() const; ``` -------------------------------- ### Main Service Setup with Dependencies Source: https://userver.tech/d7/d21/libraries_2easy_2samples_25_pg_service_template_2src_2main_8cpp-example.html Sets up the main application with custom dependencies (ActionDep and PgDep) and configures an HTTP POST endpoint '/log'. This endpoint inserts data into a PostgreSQL table and then uses the ActionDep to send a request to the action service. ```cpp #include // Note: this is for the purposes of samples only #include #include #include #include int main(int argc, char* argv[]) { using Deps = easy::Dependencies; easy::HttpWith(argc, argv) .DefaultContentType(http::content_type::kTextPlain) .Post("/log", [](const server::http::HttpRequest& req, const Deps& deps) { const auto& action = req.GetArg("action"); deps.pg().Execute( storages::postgres::ClusterHostType::kMaster, "INSERT INTO events_table(action) VALUES($1)", action ); return deps.CreateActionRequest(action)->body(); }); } ``` -------------------------------- ### Configure YDB Client in Userver Source: https://userver.tech/d4/d1e/plugins_2ydb_2client_8py_source.html Example of configuring the YDB client using a configuration object. This setup is typically done during application initialization. ```python ydb_config = ydb_config.YdbConfig( endpoint=self.config.ydb_endpoint, database=self.config.ydb_database, token=self.config.ydb_token, ) ``` -------------------------------- ### Initialize and Use StorageMock Source: https://userver.tech/d6/dec/classdynamic__config_1_1StorageMock.html Demonstrates initializing StorageMock with specific configurations and using it with a DummyClient. It also shows how to extend the storage and test exception handling. ```cpp #include class DummyClient; std::string DummyFunction(const dynamic_config::Snapshot& config) { return config[kDummyConfig].bar; } UTEST(DynamicConfig, Snippet) { // The 'StorageMock' will only contain the specified configs, and nothing more dynamic_config::StorageMock storage{ {kDummyConfig, {42, "what"}}, {kIntConfig, 5}, }; EXPECT_EQ(DummyFunction(storage.GetSnapshot()), "what"); // 'DummyClient' stores 'dynamic_config::Source' for access to latest configs DummyClient client{storage.GetSource()}; UEXPECT_NO_THROW(client.DoStuff()); storage.Extend({{kDummyConfig, {-10000, "invalid"}}}); UEXPECT_THROW(client.DoStuff(), std::runtime_error); } ``` -------------------------------- ### Main Function with Component List Source: https://userver.tech/d1/d00/samples_2postgres_service_2main_8cpp-example.html Sets up the main server components for the application, including the KeyValue service, Postgres client, HTTP clients, and test support components. ```cpp int main(int argc, char* argv[]) { const auto component_list = components::MinimalServerComponentList() .Append() .Append("key-value-database") .AppendComponentList(clients::http::ComponentList()) .Append() .Append() .Append(); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### TLS Server and Client Communication Example Source: https://userver.tech/df/d00/classengine_1_1io_1_1TlsWrapper.html Demonstrates setting up a TLS server and client to exchange data. The server initializes an SslCtx, starts TLS, and sends data, while the client connects, starts TLS, and receives data. Ensure proper certificate and key loading for the server. ```cpp #include // ... other includes and setup ... // Usage example: TcpListener tcp_listener; auto [server, client] = tcp_listener.MakeSocketPair(deadline); auto server_task = utils::Async( "tls-server", [deadline](auto&& server) { crypto::SslCtx ssl_ctx = crypto::SslCtx::CreateServerTlsContext( crypto::LoadCertificatesChainFromString(cert), crypto::PrivateKey::LoadFromString(key) ); auto tls_server = io::TlsWrapper::StartTlsServer(std::forward(server), ssl_ctx, deadline); if (tls_server.SendAll(kData.data(), kData.size(), deadline) != kData.size()) { throw std::runtime_error("Couldn't send data"); } }, std::move(server) ); auto tls_client = io::TlsWrapper::StartTlsClient(std::move(client), {}, deadline); std::vector buffer(kData.size()); const auto bytes_rcvd = tls_client.RecvAll(buffer.data(), buffer.size(), deadline); ``` -------------------------------- ### Proxy Handler Configuration with Digest Auth Source: https://userver.tech/d6/d31/md_en_2userver_2tutorial_2digest__auth__postgres.html Example configuration for an HTTP handler using 'digest-proxy' as the authorization type. This indicates a proxy-based digest authentication setup. ```yaml handler-hello-proxy: path: /v1/hello-proxy task_processor: main-task-processor method: GET auth: # Authorization config for this handler types: - digest-proxy realm: registred@userver.com ``` -------------------------------- ### YDB Client Initialization with Driver Config and Credentials Source: https://userver.tech/d4/d1e/plugins_2ydb_2client_8py_source.html Example of initializing the YDB client with a driver configuration and explicit credentials. This offers flexibility in connection and authentication setup. ```python driver_config = ydb_driver.DriverConfig(endpoint="grpc://localhost:2136", database="/local") client = ydb_client.Client(driver_config=driver_config, credentials=ydb_driver.Credentials(token='my_token')) ``` -------------------------------- ### Initialize and Run userver Daemon Source: https://userver.tech/db/d69/md_en_2userver_2tutorial_2production__service.html Initializes the component system and starts the service using provided command-line arguments. Ensure the static config file path is passed via command line. ```cpp #include #include #include #include #include #include int main(int argc, char* argv[]) { const auto component_list = components::ComponentList() .AppendComponentList(components::CommonComponentList()) .AppendComponentList(components::CommonServerComponentList()) .Append() .Append() .Append() // Put your handlers and components here ; return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### Main Function with Component Registration Source: https://userver.tech/dc/d93/md_en_2userver_2tutorial_2tcp__service.html The `main` function sets up the minimal component list, appends the custom `samples::tcp::Hello` component, and starts the userver daemon with the provided configuration. ```cpp int main(int argc, const char* const argv[]) { const auto component_list = components::MinimalComponentList().Append(); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### LruCacheWrapper Usage Example Source: https://userver.tech/dd/ddb/classcache_1_1LruCacheWrapper.html Demonstrates the basic usage of LruCacheWrapper, including initialization, getting values, and invalidating keys. The update function is used to generate values when keys are not present. ```cpp #include auto cache_ptr = std::make_shared>(1, 1); cache::LruCacheWrapper wrapper(cache_ptr, [](const std::string& /*key*/) { static std::atomic counter{0}; return ++counter; }); const std::string key = "my-key"; EXPECT_EQ(std::nullopt, wrapper.GetOptional(key)); EXPECT_EQ(1, wrapper.Get(key)); EXPECT_EQ(std::make_optional(1), wrapper.GetOptional(key)); wrapper.InvalidateByKey(key); EXPECT_EQ(2, wrapper.Get(key)); EXPECT_EQ(std::make_optional(2), wrapper.GetOptional(key)); ``` -------------------------------- ### Example Usage of StorageContext in Middleware Source: https://userver.tech/d6/d48/classugrpc_1_1server_1_1MiddlewareCallContext.html Demonstrates how to use GetStorageContext() to store and retrieve custom data within middleware and handlers. Use Emplace to store data and Get to retrieve it. ```cpp In authentication middleware: if (password_is_correct) { // Username is authenticated, set it in per-call storage context context.GetStorageContext().Emplace(kAuthUsername, username); } In client handler: const auto& username = context.GetStorageContext().Get(kAuthUsername); auto msg = fmt::format("Hello, {}!", username); ``` -------------------------------- ### Main function to initialize and run the server Source: https://userver.tech/d4/d95/md_en_2userver_2tutorial_2config__service.html Initializes the Userver component list by appending the custom ConfigDistributor and starts the server with the provided static configuration. This is the entry point for the service. ```cpp int main(int argc, char* argv[]) { const auto component_list = components::MinimalServerComponentList().Append(); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### HTTP Client - waitany Source: https://userver.tech/d2/d1c/wait__any_8hpp_source.html Example of using WaitAny to get ready HTTP requests as soon as possible. This snippet demonstrates a practical application for optimizing network request handling. ```cpp #include #include #include #include namespace { struct Request { engine::Task task; std::string url; }; } async std::string ClientWaitAny(const http::Client& client, std::vector urls) { std::vector requests; requests.reserve(urls.size()); for (const auto& url : urls) { requests.push_back({engine::Async("http_request", [&client, url]() { return client.CreateRequest() suya(url).Do().get().text(); }), url}); } std::vector tasks; tasks.reserve(requests.size()); for (auto& req : requests) { tasks.push_back(&req.task); } const auto index = engine::WaitAny(tasks); if (!index) { throw std::runtime_error("All requests cancelled"); } return requests[*index].url; } ``` -------------------------------- ### Accessing Log Level Handler Source: https://userver.tech/db/d69/md_en_2userver_2tutorial_2production__service.html Example cURL commands to get and set the log level using the log-level handler. Ensure you are using the correct listener port (e.g., 8085). ```bash $ curl http://localhost:8085/service/log-level/ {"init-log-level":"info","current-log-level":"info"} $ curl -X PUT 'http://localhost:8085/service/log-level/warning' {"init-log-level":"info","current-log-level":"warning"} ``` -------------------------------- ### Build and Run Redis Service Sample Source: https://userver.tech/d3/da2/md_en_2userver_2tutorial_2redis__service.html Instructions for building and running the Redis service sample using CMake and Make. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-redis_service ``` ```bash make start-userver-samples-redis_service ``` ```bash ./samples/redis_service/userver-samples-redis_service -c ``` -------------------------------- ### Functional Test Example for MongoDB Service Source: https://userver.tech/d5/d81/md_en_2userver_2tutorial_2mongo__service.html Write an asynchronous functional test using `service_client` and the `mongodb` fixture. This test performs PATCH and GET requests and verifies data in the database directly. ```python async def test_mongo(service_client, mongodb): data = { ('hello', 'ru', 'Привет'), ('hello', 'en', 'hello'), ('welcome', 'ru', 'Добро пожаловать'), ('welcome', 'en', 'Welcome'), } # mongodb.get_aliases() shows the available databases translations_db = mongodb.translations for key, lang, value in data: response = await service_client.patch( '/v1/translations', params={'key': key, 'lang': lang, 'value': value}, ) assert response.status == 201 # Checking content of the database via direct access assert translations_db.find_one({'key': key, 'lang': lang})['value'] == value response = await service_client.get('/v1/translations') assert response.status_code == 200 assert 'application/json' in response.headers['Content-Type'] assert response.json()['content'] == { 'hello': {'en': 'hello', 'ru': 'Привет'}, 'welcome': {'ru': 'Добро пожаловать', 'en': 'Welcome'}, } ``` -------------------------------- ### Run Userver gRPC Service Sample Source: https://userver.tech/d6/daa/md_en_2userver_2tutorial_2grpc__service.html Commands to start the userver gRPC service sample. You can either use the 'make start' command or run the executable directly with configuration files. ```bash make start-userver-samples-grpc_service ``` ```bash ./samples/grpc_service/userver-samples-grpc_service -c --config-vars ``` -------------------------------- ### Asynchronous Hedged Redis Request Example Source: https://userver.tech/df/d70/redis_2include_2userver_2storages_2redis_2hedged__request_8hpp_source.html Shows how to initiate an asynchronous hedged GET request to Redis. This returns a future that can be used to retrieve the result later. Requires similar parameters as the synchronous version. ```cpp auto future = ::redis::MakeHedgedRedisRequestAsync( redis_client_shared_ptr, &storages::redis::Client::Hget, redis_cc, hedging_settings, key, field); auto result = future.Get(); ``` -------------------------------- ### USERVER_VERSION_FULL Examples Source: https://userver.tech/d7/dad/version_8hpp_source.html Illustrates how different version strings are converted into the USERVER_VERSION_FULL numerical format. Note the handling of release candidates (rc). ```text 2.1 -> 20100 2.16 -> 21600 2.16-rc -> 21599 3.0 -> 30000 3.0-rc -> 29999 ``` -------------------------------- ### Get UTF-8 code point position in C++ Source: https://userver.tech/d5/dc9/text__light_8hpp_source.html Returns the byte position in a UTF-8 encoded string where a code point at a given logical position starts. Returns the string's length if the position is out of bounds. ```cpp /// returns number of utf-8 code points, text must be in utf-8 encoding /// @throws std::runtime_error if not a valid UTF8 text std::size_t GetCodePointsCount(std::string_view text); /// Removes the longest (possible empty) suffix of `str` which is a proper /// prefix of some utf-8 multibyte character. If `str` is not in utf-8 it may /// remove some suffix of length up to 3. void TrimTruncatedEnding(std::string& str); /// @see void TrimTruncatedEnding(std::string& str) /// @warning this **does not** change the original string void TrimViewTruncatedEnding(std::string_view& view); /// Returns position in `text` where utf-8 code point with position `pos` starts /// OR `text.length()` if `text` contains less than or equal to `pos` points ``` -------------------------------- ### Start FlatBuf Service Source: https://userver.tech/d8/d91/md_en_2userver_2tutorial_2flatbuf__service.html Start the FlatBuf service sample using the provided make command or by running the executable directly with a configuration file. ```bash make start-userver-samples-flatbuf_service ``` ```bash ./samples/flatbuf_service/userver-samples-flatbuf_service -c ``` -------------------------------- ### Get Storage Context for Per-Call Custom Data Source: https://userver.tech/db/d19/server_2call__context_8hpp_source.html Use GetStorageContext() to access a per-call storage for passing data between middleware and handlers. Example shows setting username in authentication middleware and retrieving it in a client handler. ```cpp utils::AnyStorage& GetStorageContext(); ``` ```cpp if (password_is_correct) { // Username is authenticated, set it in per-call storage context context.GetStorageContext().Emplace(kAuthUsername, username); } ``` ```cpp const auto& username = context.GetStorageContext().Get(kAuthUsername); auto msg = fmt::format("Hello, {}!", username); ``` -------------------------------- ### Main Application Setup with Custom Dependencies Source: https://userver.tech/d3/df3/libraries_2easy_2samples_24_custom_dependency_2main_8cpp-example.html Sets up the userver application with custom dependencies including 'ActionDep' and 'PgDep'. Configures the HTTP server to handle POST requests to '/log', interacting with both the database and the custom dependency. ```cpp int main(int argc, char* argv[]) { using Deps = easy::Dependencies; easy::HttpWith(argc, argv) .DbSchema(kSchema) .DefaultContentType(http::content_type::kTextPlain) .Post("/log", [](const server::http::HttpRequest& req, const Deps& deps) { const auto& action = req.GetArg("action"); deps.pg().Execute( storages::postgres::ClusterHostType::kMaster, "INSERT INTO events_table(action) VALUES($1)", action ); return deps.CreateActionRequest(action)->body(); }); } ``` -------------------------------- ### ExpirableLruCache Usage Example Source: https://userver.tech/d1/d22/classcache_1_1ExpirableLruCache.html Demonstrates the basic usage of ExpirableLruCache, including setting max lifetime, putting and getting elements, and observing expiration. Ensure mock time functions are used for predictable testing of expiration. ```cpp #include using Key = std::string; using Value = int; using Cache = cache::ExpirableLruCache; Cache cache(/*ways*/ 1, /*way_size*/ 1); cache.SetMaxLifetime(std::chrono::seconds(3)); // by default not bounded utils::datetime::MockNowSet(std::chrono::system_clock::now()); const Key key1 = "first-key"; const Key key2 = "second-key"; cache.Put(key1, 41); EXPECT_EQ(41, cache.GetOptionalNoUpdate(key1)); cache.Put(key2, 42); EXPECT_EQ(std::nullopt, cache.GetOptionalNoUpdate(key1)); EXPECT_EQ(42, cache.GetOptionalNoUpdate(key2)); utils::datetime::MockSleep(std::chrono::seconds(2)); EXPECT_EQ(42, cache.GetOptionalNoUpdate(key2)); utils::datetime::MockSleep(std::chrono::seconds(2)); EXPECT_EQ(std::nullopt, cache.GetOptionalNoUpdate(key2)); ``` -------------------------------- ### Get and use Task Processor in Component Source: https://userver.tech/db/d90/md_en_2userver_2task__processors__guide.html Demonstrates how to retrieve a task processor by name from the component context and use it to start a new asynchronous task. Avoid running blocking system calls on the main task processor. ```cpp #include #include #include #include #include namespace myservice::smth { Component::Component(const components::ComponentConfig& config, const components::ComponentContext& context) : components::ComponentBase(config, context), config_( // Searching for some component to initialize members context.FindComponent().GetSource() // getting "client" from a component ) { // Reading config values from static config [[maybe_unused]] auto url = config["some-url"].As(); const auto fs_tp_name = config["fs-task-processor"].As(); // Starting a task on a separate task processor from config auto& fs_task_processor = context.GetTaskProcessor(fs_tp_name); utils::Async(fs_task_processor, "my-component/fs-work", [] { /*...*/ }).Get(); // ... } } // namespace myservice::smth ``` -------------------------------- ### ParameterStore Sample Source: https://userver.tech/d6/d9a/postgresql_2include_2userver_2storages_2postgres_2parameter__store_8hpp_source.html Demonstrates how to use ParameterStore for dynamic query construction. Note that storages::postgres::Cluster::Execute with explicitly provided arguments can be slightly faster. ```cpp class ParameterStore { public: ParameterStore() = default; ParameterStore(const ParameterStore&) = delete; ParameterStore(ParameterStore&&) = default; ParameterStore& operator=(const ParameterStore&) = delete; ParameterStore& operator=(ParameterStore&&) = default; /// @brief Adds a parameter to the end of the parameter list. /// @note Currently only enums and built-in/system types are supported. template ParameterStore& PushBack(const T& param) { static_assert( io::IsTypeMappedToSystem() || io::IsTypeMappedToSystemArray() || (std::is_enum_v && io::traits::kIsMappedToPg && std::is_same_v::Mapping, io::CppToUserPg::Type>>), "Currently only built-in and enum types can be used in ParameterStore" ); data_.Write(kNoUserTypes, param); return *this; } /// Returns whether the parameter list is empty. bool IsEmpty() const { return data_.Size() == 0; } /// Returns current size of the list. size_t Size() const { return data_.Size(); } /// @cond const detail::DynamicQueryParameters& GetInternalData() const { return data_; } /// @endcond private: static UserTypes kNoUserTypes; detail::DynamicQueryParameters data_; }; ``` -------------------------------- ### YDB Client Initialization with YdbConfig, TLS, Custom Headers, and Token Source: https://userver.tech/d4/d1e/plugins_2ydb_2client_8py_source.html Example of initializing the YDB client using YdbConfig with TLS, custom headers, and a token. This provides a comprehensive setup using YdbConfig for connection and authentication. ```python ydb_config = ydb_config.YdbConfig( endpoint="grpc://localhost:2136", database="/local", token="my_token", ssl_context=ydb_driver.SslContext( root_certificates=open("path/to/root.crt").read(), ), http_headers=[ ("x-custom-header", "value"), ("authorization", "Bearer my_token"), ], ) client = ydb_client.Client(config=ydb_config) ``` -------------------------------- ### StartServer Source: https://userver.tech/d8/d3d/classugrpc_1_1tests_1_1ServiceWithClientFixture.html Starts the gRPC server with optional client factory settings. ```APIDOC ## StartServer void StartServer (client::ClientFactorySettings &&settings={}) Starts the gRPC server with optional client factory settings. Definition at line 71 of file service_fixtures.hpp. ``` -------------------------------- ### Set() - Overload 2 Source: https://userver.tech/d2/d39/classcomponents_1_1MongoCache.html Sets the new value of the cache. As a result, the `Get()` member function starts returning the value passed into this function after the `Update()` finishes. Warning: Do not forget to update cache::UpdateStatisticsScope, otherwise the behavior is undefined. ```APIDOC ## Set() [2/2] | void components::CachingComponentBase< MongoCacheTraits::DataType >::Set | ( | std::unique_ptr< const MongoCacheTraits::DataType > | _value_ptr_| ) | protected inherited Sets the new value of cache. As a result the `Get()` member function starts returning the value passed into this function after the `Update()` finishes. Warning Do not forget to update cache::UpdateStatisticsScope, otherwise the behavior is undefined. Definition at line 174 of file caching_component_base.hpp. ``` -------------------------------- ### StartServer(client::ClientFactorySettings && _settings_ = {}) Source: https://userver.tech/dc/da7/classugrpc_1_1tests_1_1ServiceBase.html Starts the gRPC server and establishes a connection for clients. This should be called after all services have been registered. ```APIDOC ## StartServer(client::ClientFactorySettings && _settings_ = {}) ### Description Starts the server and connects a grpc channel to it. Should be called after the services are registered. ### Parameters * `_settings_` (`client::ClientFactorySettings &&`, optional) - Settings for the client factory. Defaults to an empty settings object. ### Method `void ugrpc::tests::ServiceBase::StartServer(client::ClientFactorySettings && _settings_ = {})` ``` -------------------------------- ### Initialize and Run Userver Service Source: https://userver.tech/df/d0f/md_en_2userver_2tutorial_2multipart__service.html Adds the Multipart component to the component list and starts the userver service with the provided static configuration. ```cpp int main(int argc, char* argv[]) { const auto component_list = components::MinimalServerComponentList().Append(); return utils::DaemonMain(argc, argv, component_list); } ``` -------------------------------- ### ServiceFixtureBase Members Source: https://userver.tech/d8/d3e/classugrpc_1_1tests_1_1ServiceFixtureBase-members.html This section details the protected members of the ServiceFixtureBase class, which are primarily used for internal testing and setup within the ugrpc framework. These members allow for configuration, starting, stopping, and accessing server and statistics components during test execution. ```APIDOC ## Protected Members of ugrpc::tests::ServiceFixtureBase ### ExtendDynamicConfig - **Signature**: `ExtendDynamicConfig(const std::vector< dynamic_config::KeyValue > &)` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Extends the dynamic configuration with provided key-value pairs. ### GetConfigSource - **Signature**: `GetConfigSource() const` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Retrieves the configuration source. ### GetServer - **Signature**: `GetServer() noexcept` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Returns a reference to the server instance. ### GetStatistics - **Signature**: `GetStatistics(std::string prefix, std::vector< utils::statistics::Label > require_labels={})` - **Inherited From**: `ugrpc::tests::ServiceFixtureBase` - **Description**: Retrieves statistics based on a prefix and required labels. ### GetStatisticsStorage - **Signature**: `GetStatisticsStorage()` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Returns the statistics storage. ### MakeClient - **Signature**: `MakeClient()` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Creates a client instance. ### operator= - **Signature**: `operator=(ServiceBase &&)=delete` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Deleted move assignment operator to prevent accidental moves. ### RegisterService - **Signature**: `RegisterService(server::ServiceBase &service)` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Registers a service implementation. - **Signature**: `RegisterService(server::GenericServiceBase &service)` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Registers a generic service implementation. ### ServiceBase Constructor - **Signature**: `ServiceBase()` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Default constructor for ServiceBase. - **Signature**: `ServiceBase(server::ServerConfig &&server_config)` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Constructor that takes a server configuration. - **Signature**: `ServiceBase(ServiceBase &&)=delete` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Deleted move constructor to prevent accidental moves. ### SetClientMiddlewares - **Signature**: `SetClientMiddlewares(client::Middlewares middlewares)` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Sets middlewares for the client. ### SetServerMiddlewares - **Signature**: `SetServerMiddlewares(server::Middlewares middlewares)` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Sets middlewares for the server. ### StartServer - **Signature**: `StartServer(client::ClientFactorySettings &&settings={})` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Starts the server with optional client factory settings. ### StopServer - **Signature**: `StopServer() noexcept` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Stops the server. ### ~ServiceBase Destructor - **Signature**: `~ServiceBase()` - **Inherited From**: `ugrpc::tests::ServiceBase` - **Description**: Virtual destructor for ServiceBase. ```