### CMake: Installing Userver Components and Examples Source: https://github.com/userver-framework/userver/blob/develop/samples/CMakeLists.txt This CMake snippet defines how to install userver components and example files. It uses custom macros `_userver_directory_install` and `_userver_install_component` to manage the installation process, specifying components, source directories, and destinations. ```cmake _userver_directory_install( COMPONENT examples DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION share/userver ) _userver_install_component(MODULE examples DEPENDS "") ``` -------------------------------- ### Run Userver Redis Service Example Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/redis_service.md Commands to start the userver-samples-redis_service. This can be done via 'make start-userver-samples-redis_service' which utilizes testsuite scripts, or by manually starting the DB server and running the service executable with a static configuration file. ```bash make start-userver-samples-redis_service ``` ```bash ./samples/redis_service/userver-samples-redis_service -c ``` -------------------------------- ### Run Userver gRPC Sample (Testsuite) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_service.md Command to start the userver gRPC sample application using the testsuite's start target. This automatically sets up configurations and launches the service. ```bash make start-userver-samples-grpc_service ``` -------------------------------- ### Main Function Setup - C++ Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/auth_postgres.md Illustrates the complete `main()` function setup for the userver service. It includes component list construction, registration of the authorization checker factory, and starting the daemon. ```cpp // samples/postgres_auth/postgres_service.cpp #include #include #include #include "auth_bearer.hpp" #include "postgres_service.hpp" namespace postgres_auth { void Register(components::ComponentList& component_list) { component_list.Emplace("postgres-user-auth"); component_list.Emplace( "auth-checker-factory", [](const components::ComponentConfig& config, const components::ComponentContext& context) { return std::make_unique(config, context); }); component_list.Emplace(); } } // namespace postgres_auth int main(int argc, char* argv[]) { // Register custom components if any // ... return components::Run(argc, argv); } ``` -------------------------------- ### Run Userver gRPC Sample (Manual) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_service.md Instructions to manually start the userver gRPC sample application. This requires specifying the paths to the static configuration and config variables files. ```bash ./samples/grpc_service/userver-samples-grpc_service -c --config-vars ``` -------------------------------- ### Userver Config Service: Main Function Setup Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/config_service.md This C++ snippet shows the main function setup for a userver service that includes a dynamic configuration server. It demonstrates adding the necessary components, such as `components::DynamicConfigClient`, `components::DynamicConfigClientUpdater`, and the custom `ConfigDistributor`, to the `components::MinimalServerComponentList` before starting the server with static configuration. ```cpp #include #include #include #include #include #include #include #include #include #include // Assuming ConfigDistributor and its methods are defined as shown previously. // ... (ConfigDistributor class definition here) namespace components { // Forward declaration for MinimalServerComponentList if not included elsewhere extern template class ComponentList; } // namespace components int main(int argc, char* argv[]) { // Define kStaticConfig (usually loaded from a file or string literal) const std::string kStaticConfig = R"( #include "config_vars.yaml" #include #include dynamic-config-client: config-url: http://localhost:8083/ http-retries: 5 http-timeout: 20s service-name: configs-service dynamic-config-client-updater: update-interval: 5s full-update-interval: 1m config-settings: false first-update-fail-ok: true server: http_port: 8080 # ... other server configurations config-distributor: path: /configs methods: ["GET"] )"; // Create a component list and register required components components::ComponentList components; components.Add(); components.Add(); components.Add(); components.Add(); // Register our custom config distributor // Add other necessary components like Logger, Tracer, etc. // Start the userver server with the static configuration return server::Run(argc, argv, components, kStaticConfig); } ``` -------------------------------- ### Start Userver PostgreSQL Auth Sample Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/auth_postgres.md Commands to start the Userver PostgreSQL authentication sample service. The 'make' command utilizes a testsuite target for automated setup, while manual startup requires running the executable with a configuration file. ```bash make start-userver-samples-postgres_auth ``` ```bash ./samples/postgres_service/userver-samples-postgres_auth -c ``` -------------------------------- ### Main Function: Register and Start Server Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_service.md The main function initializes the userver application, registers the gRPC client and service components, and starts the server. This is the entry point for the application. ```cpp int main(int argc, char* argv[]) { userver::components::Minicapsule capsule{}; capsule.RegisterComponent(); capsule.RegisterComponent(); capsule.RegisterComponent(); return capsule.Run(argc, argv); } ``` -------------------------------- ### Run a userver service in debug mode Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md Starts the userver service in debug mode, allowing you to test its functionality without a full production environment setup. After starting, you can send requests to verify its responsiveness. ```shell make start-debug ``` -------------------------------- ### Build and Run Kafka Service Sample (Bash) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/kafka_service.md Provides the bash commands to build and run the userver Kafka service sample. This includes creating a build directory, configuring with CMake, and making the service. It also outlines starting the service using testsuite targets or manually. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-kafka_service ``` ```bash make start-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 ``` -------------------------------- ### Install Docker on Linux Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md Provides the shell command to install Docker on Linux systems using curl. It also includes notes on configuring Docker for usage without sudo and for starting the service on boot. ```shell curl https://get.docker.com/ | sudo sh ``` -------------------------------- ### Kafka Unit Test Setup and Producer Test (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/kafka_service.md Illustrates C++ code for setting up Kafka unit tests using the `kafka::utest::KafkaCluster` fixture. It includes necessary includes and a sample test for a producer function. ```cpp #include #include namespace kafka_sample { // Assume Produce function exists and is defined elsewhere // void Produce(const ::kafka::Producer& producer, const std::string& topic, const std::string& key, const std::string& payload); UTEST_F(KafkaCluster, Producer) { // ... producer test logic ... } } // namespace kafka_sample ``` ```cpp UTEST_F(KafkaCluster, Producer) { const std::string topic = "test-topic"; const std::string key = "test-key"; const std::string payload = "test-payload"; // Call the producer function from your service logic // Produce(producer_, topic, key, payload); // Assertions to verify message was sent (e.g., check logs or mock interactions) ASSERT_TRUE(true); // Placeholder assertion } ``` -------------------------------- ### Initialize Git repository for a userver project Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md Initializes a Git repository in the project root and stages all files for the initial commit. This is an optional step to start version control for your service project. ```shell git init && git add . && git commit -m "Initial commit" ``` -------------------------------- ### Running the TCP Server Sample Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/tcp_full.md Details how to start the built TCP full-duplex server sample. It covers using the testsuite's start target for automated setup and running the executable directly with a specified configuration file. ```bash # Using testsuite start target: make start-userver-samples-tcp_full_duplex_service # Running manually: ./samples/tcp_full_duplex_service/userver-samples-tcp_full_duplex_service -c ``` -------------------------------- ### Register Multiple Dependencies with Easy Library Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/libraries/easy.md This example demonstrates how to use multiple dependencies with the easy::HttpWith class in userver. It shows the structure for defining a class that aggregates several dependencies, allowing for more complex service setups. ```cpp #include #include #include #include #include #include #include namespace samples { class ActionClient : public components::LoggableComponent { public: static constexpr std::string_view kName = "action-client"; ActionClient(const components::ComponentContext& context) { // Initialize HTTP client component http_client_ = &context.FindComponent(); } ~ActionClient() = default; private: clients::http::Component* http_client_; }; class ActionDep { public: ActionDep(const components::ComponentContext& context) { // Retrieve the HTTP client component action_client_ = &context.FindComponent(); } static void RegisterOn(easy::HttpBase& app) { // Register the ActionClient component app.AddHttpServerComponent(ActionClient::kName); } private: ActionClient* action_client_; }; class MainApp { public: MainApp(const components::ComponentContext& context) { // Retrieve dependencies action_client_ = &context.FindComponent(); action_dep_ = &context.FindComponent(); } static void Register(easy::HttpWith& app) { // Register components and their dependencies ActionClient::RegisterOn(app); ActionDep::RegisterOn(app); } private: ActionClient* action_client_; ActionDep* action_dep_; }; } // namespace samples int main(int argc, char** argv) { return easy::HttpWithMain(argc, argv, "custom_dependency_sample", &samples::MainApp::Register); } ``` -------------------------------- ### Build and Run Multipart Service Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/multipart_service.md Steps to compile and run the userver multipart service example. This involves creating a build directory, configuring with CMake, and then building the service executable. The service can be started manually or via a make target. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-multipart_service ``` ```bash make start-userver-samples-hello_service ``` ```bash ./samples/multipart_service/userver-samples-multipart_service -c ``` -------------------------------- ### Minimal Middleware Implementation in C++ Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/http_server_middlewares.md Demonstrates a basic C++ implementation of a middleware in userver. This minimal example focuses on passing execution downstream without any specific logic. It serves as a starting point for creating custom middlewares. Dependencies include the userver framework. ```cpp namespace { struct MyMiddlewares { // Called by handler_manager void operator()(Herald& herald, ::userver::server::http::HttpRequest& request, ::userver::server::http::HttpResponse& response) const { // No-op } }; } // namespace ``` -------------------------------- ### Key-Value Storage Service with Easy Library (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/libraries/easy.md This example implements a key-value storage service using the userver 'easy' library. It allows storing values by keys via HTTP POST and retrieving them via HTTP GET. The service integrates with PostgreSQL using `easy::PgDep` and demonstrates how to manage database schemas. ```cpp #include #include #include #include #include #include namespace handlers { class KeyValueHandler : public server::handlers::HttpHandlerBase { public: static constexpr std::string_view kName = "key-value"; KeyValueHandler(const components::ComponentConfig& config, const components::ComponentContext& context) : HttpHandlerBase(config) { auto& pg_pool = context.GetComponent(config.ParseOptional("db_pool")); // Register handler for POST requests to store key-value pairs Register(server::http::HttpMethod::kPost, [this, &pg_pool](const server::http::HttpRequest& request) { const auto& key = request.GetArg("key"); const auto& value = request.GetArg("value"); auto statement = pg_pool.Statement("INSERT INTO data(key, value) VALUES($1, $2)"); statement.Bind(key, value); statement.Execute(); return server::http::response::Ok(); }); // Register handler for GET requests to retrieve values by key Register(server::http::HttpMethod::kGet, [this, &pg_pool](const server::http::HttpRequest& request) { const auto& key = request.GetArg("key"); auto statement = pg_pool.Statement("SELECT value FROM data WHERE key = $1"); statement.Bind(key); auto result = statement.Execute(); if (result.IsEmpty()) return server::http::response::NotFound(); return server::http::response::Ok(result.front().front().AsString()); }); } }; } // namespace handlers int main(int argc, char** argv) { return components::Run(argc, argv); } ``` ```cmake cmake_minimum_required(VERSION 3.16) project(userver-easy-samples-key-value) find_package(userver REQUIRED) add_executable(userver-easy-samples-key-value main.cpp ) target_link_libraries(userver-easy-samples-key-value PRIVATE userver_components userver_ydb_postgres ) userver_testsuite_add_simple(DUMP_CONFIG True) ``` ```python pytest_plugins = "userver.pytest_plugins.userver" def test_key_value(service_client, pg_master): # Create table if it doesn't exist pg_master.exec("CREATE TABLE IF NOT EXISTS data (key TEXT PRIMARY KEY, value TEXT)") # Test POST request to store a value response_post = service_client.post("/kv?key=mykey&value=myvalue") assert response_post.status_code == 200 # Test GET request to retrieve the value response_get = service_client.get("/kv?key=mykey") assert response_get.status_code == 200 assert response_get.text == "myvalue" # Test GET request for a non-existent key response_not_found = service_client.get("/kv?key=nonexistent") assert response_not_found.status_code == 404 ``` -------------------------------- ### Running a Userver Sample Service Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/hello_service.md Starts a userver sample service. This can be done using the 'make start-userver-samples-hello_service' command, which utilizes the testsuite's start target to configure and launch the service. Alternatively, the service can be started manually with a specified configuration file. ```bash make start-userver-samples-hello_service ./samples/hello_service/userver-samples-hello_service -c ``` -------------------------------- ### Userver C++ HTTP Service Example Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/landing.md This C++ code demonstrates a simple userver service that handles HTTP GET requests. It listens on the '/kv' URL, parses a JSON request to get a 'key', queries a PostgreSQL database for the value associated with that key, and returns the result as JSON. It utilizes userver's easy API for simplified setup and asynchronous database operations. ```cpp #include #include "schemas/key_value.hpp" int main(int argc, char* argv[]) { using namespace userver; easy::HttpWith(argc, argv) // Handles multiple HTTP requests to `/kv` URL concurrently .Get("/kv", [](formats::json::Value request_json, const easy::PgDep& dep) { // JSON parser and serializer are generated from JSON schema by userver auto key = request_json.As().key; // Asynchronous execution of the SQL query in transaction. Current thread // handles other requests while the response from the DB is being received: auto res = dep.pg().Execute( storages::postgres::ClusterHostType::kSlave, // Query is converted into a prepared statement. Subsequent requests // send only parameters in a binary form and meta information is // discarded on the DB side, significantly saving network bandwidth. "SELECT value FROM key_value_table WHERE key=$1", key ); schemas::KeyValue response{key, res[0][0].As()}; return formats::json::ValueBuilder{response}.ExtractValue(); }); } ``` -------------------------------- ### Build Userver Redis Service Example Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/redis_service.md Instructions to build the userver-samples-redis_service from the userver root directory using CMake and make. This process creates the necessary executables for the Redis service sample. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-redis_service ``` -------------------------------- ### Install Arch/Manjaro Dependencies with AUR Helper Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/dependencies.md Installs userver build dependencies on Arch Linux or Manjaro using an AUR helper (pikaur example). It downloads dependency information and uses the helper to install them, filtering out packages requiring makepkg. ```bash DEPS_FILE="https://raw.githubusercontent.com/userver-framework/userver/refs/heads/develop/scripts/docs/en/deps/arch.md" && \ pikaur -S $(wget -q -O - ${DEPS_FILE} | sed 's/^makepkg|//g') ``` -------------------------------- ### gRPC Middleware Service Tutorial Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/roadmap_and_changelog.md A new tutorial sample demonstrating a gRPC middleware service has been added. This provides a practical example for developers looking to implement custom middleware logic for gRPC services within the userver framework. ```documentation * New @ref scripts/docs/en/userver/tutorial/grpc_middleware_service.md sample. ``` -------------------------------- ### Valkey/Redis Client Usage Example Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/redis.md Demonstrates how to use the storages::redis::Client to interact with Valkey or Redis instances. This includes setting up the Redis component and making basic client requests. ```cpp #include // ... Assuming Redis component is initialized and configured ... storages::redis::Client redis_client = components::Component(); // Example: Set a key-value pair redis_client.SSet("mykey", "myvalue"); // Example: Get a value by key auto value = redis_client.Get("mykey"); // Example: Execute a command with arguments redis_client.Cmd("INCR", "counter"); ``` -------------------------------- ### Start userver Flatbuffer Sample Service Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/flatbuf_service.md This command initiates the userver Flatbuffer sample service. It can be executed directly after building, using `make start-userver-samples-flatbuf_service`, which utilizes the testsuite to set up configuration and start the service. Alternatively, the service can be started manually by providing the path to the static configuration file. ```bash # Using testsuite: make start-userver-samples-flatbuf_service # Manual start: ./samples/flatbuf_service/userver-samples-flatbuf_service -c ``` -------------------------------- ### Create a new userver service project Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md This command generates a new service project directory with specified features like gRPC, MongoDB, or PostgreSQL. It's the starting point for creating new microservices with userver. Ensure userver is installed or the create-service script is accessible. ```shell userver-create-service [--grpc] [--mongo] [--postgresql] myservice ``` -------------------------------- ### GreeterServiceComponent Class Definition Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_service.md Defines the GreeterServiceComponent, a userver component that registers and manages the GreeterService. This component is responsible for starting and stopping the gRPC service. ```cpp class GreeterServiceComponent final : public api::GreeterServiceBase::Component { public: GreeterServiceComponent(const userver::components::ComponentConfig&, const userver::components::ComponentContext&); ~GreeterServiceComponent(); private: void SayHello(CallContextDefault& call) override; void SayHelloStream(CallContextStreamResponse& call) override; void SayHelloStreamRequest(CallContextStreamRequest& call) override; void SayHelloBidirectionalStream(CallContextBidirectionalStream& call) override; }; ``` -------------------------------- ### Project Setup and Userver Linking (CMake) Source: https://github.com/userver-framework/userver/blob/develop/libraries/easy/samples/2_key_value/CMakeLists.txt This CMakeLists.txt file configures a C++ project named 'userver-easy-samples-key-value'. It finds the 'userver' package with the 'easy' component, adds the main.cpp file as an executable, and links it against the userver::easy library. It also configures the userver testsuite. ```cmake project(userver-easy-samples-key-value CXX) find_package( userver COMPONENTS easy REQUIRED ) add_executable(${PROJECT_NAME} "main.cpp") target_link_libraries(${PROJECT_NAME} userver::easy) userver_testsuite_add_simple(DUMP_CONFIG True) ``` -------------------------------- ### Cache Fault Tolerance Configuration (YAML) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/caches.md Configuration example for enabling fault tolerance in a userver cache, allowing it to start even if the initial update fails. ```yaml first-update-fail-ok-cache: update-interval: 60s update-jitter: 10s full-update-interval: 1000s first-update-fail-ok: true ``` -------------------------------- ### Start PostgreSQL Service Sample (Bash) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/postgres_service.md Instructions to start the PostgreSQL service sample. This can be done using a make target or by manually running the compiled executable with a specified static configuration file. ```bash make start-userver-samples-postgres_service ./samples/postgres_service/userver-samples-postgres_service -c ``` -------------------------------- ### Link to ugrpc CMake Library Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_service.md This snippet shows how to link the userver gRPC library in your CMakeLists.txt file. Ensure userver is installed and discoverable by CMake. ```cmake ugrpc ``` -------------------------------- ### Start Userver Config Service Sample Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/config_service.md Starts the userver-samples-config_service using a make target, which utilizes a testsuite script to set up configurations and launch the service. ```bash make start-userver-samples-config_service ``` -------------------------------- ### C++ Main Function - Userver Framework Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/redis_service.md The main entry point for the Userver application. It sets up the minimal component list, adds the custom component, and starts the server with the provided static configuration. ```cpp #include #include #include "main.hpp" // Assuming KeyValue is declared here int main(int argc, char* argv[]) { userver::components::MinimalServerComponentList components; // Add components here components.Append(); components.Append(); return components.Run(argc, argv); } ``` -------------------------------- ### userver_testsuite_add_simple Function for Testsuite Tests Source: https://github.com/userver-framework/userver/blob/develop/cmake/README.md Defines functions for setting up 'testsuite tests' as described in the userver functional testing documentation. The `userver_testsuite_add_simple()` function is provided as an example of how to initiate this setup. ```cmake userver_testsuite_add_simple() ``` -------------------------------- ### C++ gRPC Client Usage Example with Userver Source: https://context7.com/userver-framework/userver/llms.txt Demonstrates how to use the Userver framework to create a gRPC client for the Greeter service. It shows making a unary 'SayHello' RPC call with specified timeouts. ```cpp // gRPC client usage example class GreeterClient { public: explicit GreeterClient(api::GreeterServiceClient& raw_client) : raw_client_(raw_client) {} std::string SayHello(std::string name) const { api::GreetingRequest request; request.set_name(std::move(name)); ugrpc::client::CallOptions options; options.timeout = std::chrono::seconds{5}; auto call = raw_client_.SayHello(request, options); auto response = call.Finish(); return response.greeting(); } private: api::GreeterServiceClient& raw_client_; }; ``` -------------------------------- ### Getting and Using a Custom Logger (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/logging.md Provides an example of how to retrieve a custom logger instance by name from the `components::Logging` component and how to direct log messages to it using `LOG_XXX_TO`. ```cpp auto& logging_component = context.FindComponent<::components::Logging>(); logging::LoggerPtr my_logger = logging_component.GetLogger("my_logger_name"); LOG_INFO_TO(*my_logger) << "Look, I am a new logger!"; ``` -------------------------------- ### Hello World Service with Easy Library (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/libraries/easy.md Demonstrates a basic 'Hello World' service using the userver 'easy' library. It sets up an HTTP handler for the '/hello' route that responds with 'Hello world' to any request. This example includes the C++ source, CMake build file, and test suite configuration for simple testing. ```cpp #include #include #include #include #include namespace userver { namespace handlers { class HelloWorldHandler : public HttpHandlerBase { public: static constexpr std::string_view kName = "hello-world"; HelloWorldHandler(const components::ComponentConfig&, const components::ComponentContext&) : HttpHandlerBase() {} std::string HandleRequestThrow(const server::http::HttpRequest&, server::request::RequestContext&) const override { return "Hello world"; } }; } // namespace handlers } // namespace userver int main(int argc, char** argv) { return components::Run(argc, argv); } ``` ```cmake cmake_minimum_required(VERSION 3.16) project(userver-easy-samples-hello-world) find_package(userver REQUIRED) add_executable(userver-easy-samples-hello-world main.cpp ) target_link_libraries(userver-easy-samples-hello-world PRIVATE userver_components ) userver_testsuite_add_simple(DUMP_CONFIG True) ``` ```python pytest_plugins = "userver.pytest_plugins.userver" def test_hello_world(service_client): response = service_client.get("/hello") assert response.status_code == 200 assert response.text == "Hello world" ``` -------------------------------- ### Building a Userver Sample Service with CMake Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/hello_service.md Builds a sample userver service using CMake and make. This involves creating a build directory, configuring the project with CMake specifying the release build type, and then compiling the service. ```bash mkdir build_release cd build_releasecmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-hello_service ``` -------------------------------- ### Declare Kafka Consumer Component (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/kafka_service.md Declares a userver component that utilizes a kafka::ConsumerScope for asynchronous message consumption from Kafka topics. The consumer is started upon component initialization. ```cpp #include namespace kafka_sample { class ConsumerComponent { public: static constexpr std::string_view kName = "kafka-consumer"; ConsumerComponent(const components::ComponentConfig&, const components::ComponentContext&); ~ConsumerComponent(); private: kafka::ConsumerScope consumer_scope_; }; } // namespace kafka_sample ``` -------------------------------- ### Testing Userver Service with Curl Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/hello_service.md Sends a request to a running userver service using curl to test its functionality. This example sends a GET request to the '/hello' endpoint on localhost. ```bash $ curl 127.0.0.1:8080/hello ``` -------------------------------- ### Component Configuration for TaskProcessor Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/task_processors_guide.md Example of configuring task processors within the component system's static configuration. This snippet demonstrates how to define and name different task processors that will be available for use within the application. ```cpp @snippet components/common_component_list_test.cpp Sample components manager config component config ``` -------------------------------- ### Userver CMake Component Naming Convention Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/roadmap_and_changelog.md This example shows the new `::` component naming convention in CMake for userver. This change ensures that CMake component names work correctly regardless of how the userver framework is installed (e.g., CPM, add_subdirectory, find_package). ```cmake target_link_libraries(your_target PRIVATE userver::core) ``` -------------------------------- ### Configure Userver Project with CMake Source: https://github.com/userver-framework/userver/blob/develop/libraries/easy/samples/0_hello_world/CMakeLists.txt This snippet sets up the CMake build system for a Userver project. It defines the minimum CMake version, names the project, finds the necessary 'userver' package components, and links the executable target to the Userver library. Dependencies include the CMake build system and the Userver library. ```cmake cmake_minimum_required(VERSION 3.14) project(userver-easy-samples-hello-world CXX) find_package( userver COMPONENTS easy REQUIRED ) add_executable(${PROJECT_NAME} "main.cpp") target_link_libraries(${PROJECT_NAME} userver::easy) ``` -------------------------------- ### Handler Middleware Component Configuration in YAML Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/http_server_middlewares.md An example of YAML configuration for a userver handler-specific middleware component. This snippet shows how to define and configure a middleware that can be applied to individual handlers, specifying its behavior through configuration values. Relevant for per-handler middleware setup. ```yaml components: handler-middleware: class-name: configurable-middleware-factory middlewares: handler-middleware.header-value: "some-value" # ... other configurations ``` -------------------------------- ### Initialize and Start Userver Service (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/production_service.md Initializes and starts the component system for a production-ready Userver service using the provided command line arguments. This function is the entry point for the application. It requires the path to the static configuration file to be passed as a command-line argument. ```cpp utils::DaemonMain(argc, argv); ``` -------------------------------- ### Build Steps for MongoDB Service Sample Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/mongo_service.md Provides the shell commands to compile and build the MongoDB service sample application from the userver root directory. It involves creating a build directory, configuring CMake with the release build type, and then executing the make command. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-mongo_service ``` -------------------------------- ### Asynchronous Task Execution with libtorrent on fs_task_processor Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/task_processors_guide.md Shows an example of executing a task involving the libtorrent library, which performs file system operations, on the `fs_task_processor`. This uses `engine::Async` with a custom task name for better tracing. ```cpp auto result = engine::Async(fs_task_processor_, "torrent/validate", [path]() { auto files = libtorrent::discover_files(path); // searches FS return libtorrent::validate_hashes(files); // reads files and computes hashes }).Get(); ``` -------------------------------- ### Use Kafka Consumer in Component (C++) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/kafka_service.md Demonstrates how to find a Kafka consumer instance and start asynchronous message processing by passing a callback to ConsumerScope::Start. The callback invokes the Consume function and commits offsets on success. ```cpp ConsumerComponent::ConsumerComponent(const components::ComponentConfig& config, const components::ComponentContext& context) : consumer_scope_(kafka::ConsumerScope::Create(config, context, "my-consumer-group")) { consumer_scope_.Start(std::bind(kafka_sample::Consume, std::ref(consumer_scope_), std::placeholders::_1)); } ConsumerComponent::~ConsumerComponent() = default; ``` -------------------------------- ### Sample Pytest Redis Configuration (Multiple Setups) Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/redis_service.md Python snippet for configuring pytest to handle multiple Redis setups (cluster, standalone) simultaneously. This is useful when the service needs to interact with Redis in different configurations. ```python # @snippet redis/functional_tests/integration_tests/tests/conftest.py Sample pytest redis configuration ``` -------------------------------- ### YAML Sample Secdist Static Configuration - Userver Framework Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/redis_service.md Provides an example of static configuration for the secdist (secure distribution) provider, which is used by components like `components::Redis` to retrieve sensitive connection information. ```yaml userver.components.secdist.cache_path: "/path/to/secure_data.json" ``` -------------------------------- ### CMake Environment Setup Function in userver Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/roadmap_and_changelog.md The `userver_setup_environment()` function is now the primary method for setting up the build environment in userver's CMake configuration. This replaces the older `SetupEnvironment.cmake` include and streamlines the process of configuring the build, including default requirements for `userver_testsuite_add_simple()`. ```cmake - before: ```cmake include(third_party/userver/cmake/SetupEnvironment.cmake) add_subdirectory(third_party/userver) ``` - after: ```cmake add_subdirectory(third_party/userver) userver_setup_environment() ``` ``` -------------------------------- ### Send a request to the userver service Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md This command uses curl to send an HTTP GET request to the running userver service at the default address and port, with a 'userver' name parameter. It demonstrates how to interact with a basic service endpoint. ```shell curl http://127.0.0.1:8080/hello?name=userver ``` -------------------------------- ### gRPC CallRequestHook Implementation - C++ Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/grpc/server_middleware_implementation.md Implements the gRPC CallRequestHook in C++. This example shows how to define the behavior of the middleware when a call starts and finishes, including basic logging. It leverages userver's component system for initialization. ```cpp #include "my_middleware.hpp" #include #include #include namespace my_middleware { namespace { struct MiddlewareDependencyBuilder { std::shared_ptr logger; }; } // namespace CallRequestHook::CallRequestHook(const components::ComponentConfig& config, const components::ComponentContext& context) : logger_(context.FindComponent()) { // Middleware config options can be read from config here // For example: auto option = config.HasMember("my-option") ? config["my-option"].As() : "default"; } const grpc::Service* CallRequestHook::GetService() const { // Return a service if this middleware registers its own RPCs, otherwise nullptr. return nullptr; } void CallRequestHook::OnCallStart(grpc::ServerContext& context, const CallRequestHook& hook, std::shared_ptr call) { LOG_INFO() << "Call started: " << call->method(); // You can access request data or modify context here } void CallRequestHook::OnCallFinish(const CallRequestHook& hook, std::shared_ptr call) { LOG_INFO() << "Call finished: " << call->method(); // You can access response data or the final status here } } // namespace my_middleware ``` -------------------------------- ### CMake Project Setup and Executable Definition Source: https://github.com/userver-framework/userver/blob/develop/samples/dns-resolver/CMakeLists.txt This snippet configures the CMake project, finds required packages like Boost, defines the main executable for the DNS resolver, and links necessary libraries. It assumes the userver and Boost libraries are available in the CMake environment. ```cmake project(userver-samples-dns-resolver CXX) find_package(Boost REQUIRED CONFIG COMPONENTS program_options) add_executable(${PROJECT_NAME} "resolver.cpp") target_link_libraries(${PROJECT_NAME} userver::core Boost::program_options) ``` -------------------------------- ### Creating a New Service with userver-create-service Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/roadmap_and_changelog.md This command-line script is used to generate a new service project structure within the Userver framework. It replaces the older GitHub service templates and simplifies the initial setup of new services. It requires the script to be available in the Userver installation. ```bash userver-create-service my_new_service ``` -------------------------------- ### Running Userver Benchmarks in Shell Source: https://github.com/userver-framework/userver/blob/develop/third_party/moodycamel/README.md This snippet shows the shell commands to build and run the benchmarks for the Userver framework. It navigates to the build directory, compiles the benchmarks, and then executes them. This is useful for performance analysis and comparison. ```Shell cd build make benchmarks bin/benchmarks ``` -------------------------------- ### Static Configuration for Middleware Server - YAML Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/grpc/server_middleware_implementation.md Example of static YAML configuration for a middleware server in userver. This defines the middleware component, specifying its type and any associated settings, allowing for flexible and declarative setup of server behavior. ```yaml idm-server: service-port: 8082 middlewares: - name: my-middleware path: "/path/to/my_middleware.so" priority: 100 ``` -------------------------------- ### Main function for gRPC Middleware Sample Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_middleware_service.md The main entry point for the gRPC middleware sample application. It demonstrates how to register the custom gRPC server and client middleware components and start the userver application. ```cpp #include #include "samples/grpc_middleware_service/src/middlewares/client/auth.hpp" #include "samples/grpc_middleware_service/src/middlewares/server/auth.hpp" int main(int argc, char* argv[]) { return components::Run(argc, argv); } ``` -------------------------------- ### Main Function for MongoDB Service Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/mongo_service.md The main entry point of the MongoDB service application. It initializes the component list with essential components, including the custom MongoDB service component, and starts the userver server with the provided static configuration. ```cpp #include #include #include "mongo_service.hpp" // Assuming MongoService is defined in mongo_service.hpp int main(int argc, char* argv[]) { // Initialize the component list with minimal server components and the custom MongoService auto component_list = components::MinimalServerComponentList() .Append(); // Run the userver application with the component list and command-line arguments return userver::engine::RunForest(argc, argv, component_list); } ``` -------------------------------- ### Build Userver gRPC Sample Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/tutorial/grpc_service.md Commands to build the userver gRPC sample application using CMake. This involves creating a build directory, configuring with CMake, and compiling the target. ```bash mkdir build_release cd build_release cmake -DCMAKE_BUILD_TYPE=Release .. make userver-samples-grpc_service ``` -------------------------------- ### Build and test a userver service project Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md These commands compile the debug version of your service and run its tests. Successful execution indicates that the service is built correctly and its core functionalities are working as expected. Database installations might be required for tests to pass. ```shell make build-debug && \ make test-debug ``` -------------------------------- ### Link userver libraries in CMakeLists.txt Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/build/build.md This CMake snippet shows how to link your project's objects with specific userver components. The target_link_libraries command is used to establish the dependency. For example, linking userver::postgresql makes PostgreSQL functionality available to your project. ```cmake target_link_libraries(${PROJECT_NAME}_objs PUBLIC userver::postgresql) ``` -------------------------------- ### Create HTTP Service with EasyHttp in C++ Source: https://github.com/userver-framework/userver/blob/develop/scripts/docs/en/userver/roadmap_and_changelog.md Demonstrates creating a simple HTTP service with a '/hello' endpoint using the EasyHttp utility in C++. This simplifies service initialization and routing. ```cpp 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 }); } ```