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