userver: /data/code/userver/libraries/easy/src/easy.cpp Source File
Loading...
Searching...
No Matches
easy.cpp
1#include <userver/easy.hpp>
2
3#include <fstream>
4#include <iostream>
5#include <unordered_map>
6
7#include <fmt/ranges.h>
8#include <boost/algorithm/string/replace.hpp>
9#include <boost/program_options.hpp>
10
11#include <fmt/format.h>
12#include <fmt/ranges.h>
13
14#include <userver/clients/dns/component.hpp>
15#include <userver/clients/http/component.hpp>
16#include <userver/clients/http/middlewares/pipeline_component.hpp>
17#include <userver/components/component_context.hpp>
18#include <userver/components/minimal_server_component_list.hpp>
19#include <userver/components/run.hpp>
20#include <userver/server/handlers/http_handler_base.hpp>
21#include <userver/storages/postgres/component.hpp>
22#include <userver/testsuite/testsuite_support.hpp>
23#include <userver/utils/daemon_run.hpp>
24
25USERVER_NAMESPACE_BEGIN
26
27namespace easy {
28
29namespace {
30
31constexpr std::string_view kConfigBase = R"~(# yaml
32components_manager:
33 task_processors: # Task processor is an executor for coroutine tasks
34 main-task-processor: # Make a task processor for CPU-bound coroutine tasks.
35 worker_threads: 4 # Process tasks in 4 threads.
36
37 fs-task-processor: # Make a separate task processor for filesystem bound tasks.
38 worker_threads: 1
39
40 default_task_processor: main-task-processor # Task processor in which components start.
41
42 components: # Configuring components that were registered via component_list)~";
43
44constexpr std::string_view kConfigServerTemplate = R"~(
45 server:
46 listener: # configuring the main listening socket...
47 port: {} # ...to listen on this port and...
48 task_processor: main-task-processor # ...process incoming requests on this task processor.
49)~";
50
51constexpr std::string_view kConfigLoggingTemplate = R"~(
52 logging:
53 fs-task-processor: fs-task-processor
54 loggers:
55 default:
56 file_path: '@stderr'
57 level: {}
58 overflow_behavior: discard # Drop logs if the system is too busy to write them down.
59)~";
60
61constexpr std::string_view kConfigHandlerTemplate{
62 "path: {0} # Registering handler by URL '{0}'.\n"
63 "method: {1}\n"
64 "task_processor: main-task-processor # Run it on CPU bound task processor\n"
65};
66
67struct SharedPyaload {
68 std::unordered_map<std::string, HttpBase::Callback> http_functions;
69 std::optional<http::ContentType> default_content_type;
70 std::string db_schema;
71};
72
73SharedPyaload globals{};
74
75} // anonymous namespace
76
77namespace impl {
78
79DependenciesBase::~DependenciesBase() = default;
80
81} // namespace impl
82
83class HttpBase::Handle final : public server::handlers::HttpHandlerBase {
84public:
85 Handle(const components::ComponentConfig& config, const components::ComponentContext& context)
86 : HttpHandlerBase(config, context),
87 deps_{context.FindComponent<impl::DependenciesBase>()},
88 callback_{globals.http_functions.at(config.Name())}
89 {}
90
91 std::string HandleRequestThrow(const server::http::HttpRequest& request, server::request::RequestContext&)
92 const override {
93 if (globals.default_content_type) {
94 request.GetHttpResponse().SetContentType(*globals.default_content_type);
95 }
96 return callback_(request, deps_);
97 }
98
99private:
100 const impl::DependenciesBase& deps_;
101 HttpBase::Callback& callback_;
102};
103
104HttpBase::HttpBase(int argc, const char* const argv[])
105 : argc_{argc},
106 argv_{argv},
107 static_config_{kConfigBase},
109{}
110
111HttpBase::~HttpBase() {
112 static_config_.append(fmt::format(kConfigServerTemplate, port_));
113 static_config_.append(fmt::format(kConfigLoggingTemplate, ToString(level_)));
114
115 namespace po = boost::program_options;
116 po::variables_map vm;
117 auto desc = utils::BaseRunOptions();
118 std::string config_dump;
119 std::string schema_dump;
120
121 // clang-format off
122 desc.add_options()
123 ("dump-config", po::value(&config_dump)->implicit_value(""), "path to dump the server config")
124 ("dump-db-schema", po::value(&schema_dump)->implicit_value(""), "path to dump the DB schema")
125 ("config,c", po::value<std::string>(), "path to server config")
126 ;
127 // clang-format on
128
129 po::store(po::parse_command_line(argc_, argv_, desc), vm);
130 po::notify(vm);
131
132 if (vm.count("help")) {
133 std::cerr << desc << '\n';
134 return;
135 }
136
137 if (vm.count("dump-config")) {
138 if (config_dump.empty()) {
139 std::cout << static_config_ << std::endl;
140 } else {
141 std::ofstream(config_dump) << static_config_;
142 }
143 return;
144 }
145
146 if (vm.count("dump-db-schema")) {
147 if (schema_dump.empty()) {
148 std::cout << schema_dump << std::endl;
149 } else {
150 std::ofstream(schema_dump) << globals.db_schema;
151 }
152 return;
153 }
154
155 if (argc_ <= 1) {
156 components::Run(components::InMemoryConfig{static_config_}, component_list_);
157 } else {
158 const auto ret = utils::DaemonMain(vm, component_list_);
159 if (ret != 0) {
160 std::exit(ret); // NOLINT(concurrency-mt-unsafe)
161 }
162 }
163}
164
165void HttpBase::DefaultContentType(http::ContentType content_type) { globals.default_content_type = content_type; }
166
167void HttpBase::Route(std::string_view path, Callback&& func, std::initializer_list<server::http::HttpMethod> methods) {
168 auto component_name = fmt::format("{}-{}", path, fmt::join(methods, ","));
169
170 globals.http_functions.emplace(component_name, std::move(func));
171 component_list_.Append<Handle>(component_name);
172 AddComponentConfig(component_name, fmt::format(kConfigHandlerTemplate, path, fmt::join(methods, ",")));
173}
174
175void HttpBase::AddComponentConfig(std::string_view component, std::string_view config) {
176 static_config_ += fmt::format("\n {}:", component);
177 if (config.empty()) {
178 static_config_ += " {}\n";
179 } else {
180 if (config.back() == '\n') {
181 config = std::string_view{config.data(), config.size() - 1};
182 }
183 static_config_ += boost::algorithm::replace_all_copy("\n" + std::string{config}, "\n", "\n ");
184 static_config_ += '\n';
185 }
186}
187
188void HttpBase::DbSchema(std::string_view schema) { globals.db_schema = schema; }
189
190const std::string& HttpBase::GetDbSchema() noexcept { return globals.db_schema; }
191
192void HttpBase::Port(std::uint16_t port) { port_ = port; }
193
194void HttpBase::LogLevel(logging::Level level) { level_ = level; }
195
196PgDep::PgDep(const components::ComponentContext& context)
197 : pg_cluster_(context.FindComponent<components::Postgres>("postgres").GetCluster())
198{
199 const auto& db_schema = HttpBase::GetDbSchema();
200 if (!db_schema.empty()) {
201 pg_cluster_->Execute(storages::postgres::ClusterHostType::kMaster, db_schema);
202 }
203}
204
205void PgDep::RegisterOn(HttpBase& app) {
207 "postgres",
208 "dbconnection#env: POSTGRESQL\n"
209 "dbconnection#fallback: 'postgresql://testsuite@localhost:15433/postgres'\n"
210 "blocking_task_processor: fs-task-processor\n"
211 "dns_resolver: async\n"
212 );
213
214 app.TryAddComponent<components::TestsuiteSupport>(components::TestsuiteSupport::kName, "");
216 clients::dns::Component>(clients::dns::Component::kName, "fs-task-processor: fs-task-processor");
217}
218
219HttpDep::HttpDep(const components::ComponentContext& context)
220 : http_(context.FindComponent<components::HttpClient>().GetHttpClient())
221{}
222
223void HttpDep::RegisterOn(easy::HttpBase& app) {
224 app.TryAddComponent<components::HttpClientCore>(
225 components::HttpClientCore::kName,
226 "pool-statistics-disable: false\n"
227 "thread-name-prefix: http-client\n"
228 "threads: 2\n"
229 "fs-task-processor: fs-task-processor\n"
230 );
232 clients::http::MiddlewarePipelineComponent>(clients::http::MiddlewarePipelineComponent::kName, "");
234 components::HttpClient::kName,
235 fmt::format("core-component: {}\n", components::HttpClientCore::kName)
236 );
237}
238
239} // namespace easy
240
241USERVER_NAMESPACE_END