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