OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
OdbDesignServerApp.cpp
Go to the documentation of this file.
9#include "macros.h"
11#include <grpcpp/grpcpp.h>
12#include <grpcpp/health_check_service_interface.h>
13#include <grpcpp/ext/proto_server_reflection_plugin.h>
14#include <iostream>
15#include <utility>
16#include <memory>
17#include <string>
18#include <App/DesignCache.h>
19#include "OdbServerAppBase.h"
20#include <crow/middlewares/cors.h>
21#include <grpcpp/security/server_credentials.h>
22#include <grpcpp/server.h>
23#include <grpcpp/server_builder.h>
24#include <grpcpp/resource_quota.h>
25#include <filesystem>
26#include <cstdlib>
27#include <algorithm>
28#include <limits>
29
30using namespace Odb::Lib::App;
31
32namespace Odb::App::Server
33{
35 : OdbServerAppBase(argc, argv)
36 {
37 }
38
40 {
41 m_vecControllers.push_back(std::make_shared<HelloWorldController>(*this));
42 m_vecControllers.push_back(std::make_shared<FileUploadController>(*this));
43 m_vecControllers.push_back(std::make_shared<FileModelController>(*this));
44 m_vecControllers.push_back(std::make_shared<HealthCheckController>(*this));
45 m_vecControllers.push_back(std::make_shared<DesignsController>(*this));
46 }
47
48 void OdbDesignServerApp::RunGrpcServer(const std::string& server_address, std::shared_ptr<Odb::Lib::App::DesignCache> cache)
49 {
50 if (!cache)
51 {
52 std::cerr << "ERROR: DesignCache is null, cannot start gRPC server" << std::endl;
53 return;
54 }
55
56 // Load gRPC service configuration
57 // Check GRPC_CONFIG_PATH environment variable first, then try executable directory, then current directory
58 std::string configPath;
59 const char* envConfig = std::getenv("GRPC_CONFIG_PATH");
60 if (envConfig != nullptr && envConfig[0] != '\0')
61 {
62 std::filesystem::path p(envConfig);
63 std::error_code ec;
64 p = std::filesystem::weakly_canonical(p, ec);
65
66 std::filesystem::path exeDir = std::filesystem::weakly_canonical(args().executableDirectory(), ec);
67 std::filesystem::path currentDir = std::filesystem::current_path(ec);
68
69 bool isValidPath = false;
70 // Check if p is contained within exeDir or currentDir
71 if (std::filesystem::proximate(p, exeDir, ec).string().find("..") == std::string::npos ||
72 std::filesystem::proximate(p, currentDir, ec).string().find("..") == std::string::npos)
73 {
74 isValidPath = true;
75 }
76
77 if (!ec && p.extension() == ".json" && isValidPath && std::filesystem::is_regular_file(p, ec))
78 {
79 configPath = p.string();
80 }
81 else
82 {
83 std::cerr << "WARNING: GRPC_CONFIG_PATH must be a valid path to an existing .json file within allowed directories. Falling back to default locations." << std::endl;
84 envConfig = nullptr; // trigger fallback
85 }
86 }
87
88 if (envConfig == nullptr || envConfig[0] == '\0')
89 {
90 // Try executable directory first (where config.json should be)
91 std::filesystem::path exeDir = args().executableDirectory();
92 std::filesystem::path configInExeDir = exeDir / "config.json";
93
94 // Try current working directory as fallback
95 std::filesystem::path configInCwd = "config.json";
96
97 // Check executable directory first, then current directory
98 if (std::filesystem::exists(configInExeDir))
99 {
100 configPath = configInExeDir.string();
101 }
102 else if (std::filesystem::exists(configInCwd))
103 {
104 configPath = configInCwd.string();
105 }
106 else
107 {
108 // Default to executable directory (will show "not found" message)
109 configPath = configInExeDir.string();
110 }
111 }
113 std::cout << loadResult.message << std::endl;
114
115 OdbDesignServer::Services::OdbDesignServiceImpl service(cache, loadResult.config);
116
117 grpc::EnableDefaultHealthCheckService(true);
118 grpc::reflection::InitProtoReflectionServerBuilderPlugin();
119
120 grpc::ServerBuilder builder;
121
122 // Apply message size limits from configuration
123 // Convert MB to bytes (multiply by 1024*1024)
124 const int64_t maxReceiveBytes = static_cast<int64_t>(loadResult.config->max_receive_message_size_mb) * 1024 * 1024;
125 const int64_t maxSendBytes = static_cast<int64_t>(loadResult.config->max_send_message_size_mb) * 1024 * 1024;
126 // gRPC takes int message sizes. Narrowing a value above INT_MAX bytes
127 // (~2047 MB) would wrap negative, and gRPC treats a negative limit as
128 // unlimited — silently disabling the guard. Clamp instead.
129 constexpr int64_t maxIntBytes = static_cast<int64_t>(std::numeric_limits<int>::max());
130 if (maxReceiveBytes > maxIntBytes)
131 {
132 std::cerr << "WARNING: max_receive_message_size_mb exceeds " << maxIntBytes / (1024 * 1024)
133 << " MB; clamping gRPC receive limit to INT_MAX bytes" << std::endl;
134 }
135 if (maxSendBytes > maxIntBytes)
136 {
137 std::cerr << "WARNING: max_send_message_size_mb exceeds " << maxIntBytes / (1024 * 1024)
138 << " MB; clamping gRPC send limit to INT_MAX bytes" << std::endl;
139 }
140 builder.SetMaxReceiveMessageSize(static_cast<int>(std::min(maxReceiveBytes, maxIntBytes)));
141 builder.SetMaxSendMessageSize(static_cast<int>(std::min(maxSendBytes, maxIntBytes)));
142
143 std::cout << "gRPC max message sizes: receive=" << loadResult.config->max_receive_message_size_mb
144 << "MB (" << maxReceiveBytes << " bytes)"
145 << ", send=" << loadResult.config->max_send_message_size_mb
146 << "MB (" << maxSendBytes << " bytes)" << std::endl;
147 // Apply compression configuration
148 if (loadResult.config->compression_level != GRPC_COMPRESS_LEVEL_NONE)
149 {
150 builder.SetDefaultCompressionLevel(loadResult.config->compression_level);
151 std::cout << "gRPC compression level: "
152 << OdbDesignServer::Config::CompressionLevelToString(loadResult.config->compression_level)
153 << std::endl;
154 }
155 else
156 {
157 std::cout << "gRPC compression: disabled" << std::endl;
158 }
159
160 // Apply thread pool limits via ResourceQuota
161 grpc::ResourceQuota quota;
162 quota.SetMaxThreads(loadResult.config->max_threads);
163 builder.SetResourceQuota(quota);
164 builder.SetSyncServerOption(grpc::ServerBuilder::SyncServerOption::MIN_POLLERS,
165 loadResult.config->min_pollers);
166
167 std::cout << "gRPC thread pool: max_threads=" << loadResult.config->max_threads
168 << ", min_pollers=" << loadResult.config->min_pollers << std::endl;
169
170 // Apply keepalive channel arguments
171 builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS,
172 loadResult.config->keepalive_time_s * 1000);
173 builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS,
174 loadResult.config->keepalive_timeout_s * 1000);
175 builder.AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS,
176 loadResult.config->keepalive_permit_without_calls ? 1 : 0);
177 builder.AddChannelArgument(GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS,
178 (loadResult.config->keepalive_time_s * 1000) / 2);
179
180 std::cout << "gRPC keepalive: time=" << loadResult.config->keepalive_time_s
181 << "s, timeout=" << loadResult.config->keepalive_timeout_s
182 << "s, permit_without_calls="
183 << (loadResult.config->keepalive_permit_without_calls ? "true" : "false")
184 << std::endl;
185
186 builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
187 builder.RegisterService(&service);
188
189 // Build server and transfer ownership to base via shared_ptr
190 std::unique_ptr<grpc::Server> serverUnique = builder.BuildAndStart();
191 if (!serverUnique) {
192 std::cerr << "ERROR: Failed to start gRPC server on " << server_address << std::endl;
193 return;
194 }
195 std::cout << "gRPC server listening on " << server_address << std::endl;
196
197 // Share ownership so base class can Shutdown() it from another thread
198 std::shared_ptr<grpc::Server> serverShared(std::move(serverUnique));
199 set_grpc_server(serverShared);
200
201 // Wait for shutdown signal
202 serverShared->Wait();
203 std::cout << "gRPC server shut down." << std::endl;
204
205 // Release ownership after shutdown (base will also reset on its side)
206 set_grpc_server(nullptr);
207 }
208
210 {
211 // CORS
212 auto& cors = crow_app().get_middleware<crow::CORSHandler>();
213 if (Utils::IsProduction())
214 {
215 cors.global()
216 .headers("*")
217 .origin("*");
218 }
219 else
220 {
221 cors.global()
222 .headers("*")
223 .origin("*");
224 }
225
226 // add authentication
227 bool disableAuth = args().disableAuthentication();
228 auto basicRequestAuth = std::make_unique<BasicRequestAuthentication>(BasicRequestAuthentication(disableAuth));
229 request_auth(std::move(basicRequestAuth));
230
231 return true;
232 }
233}
void RunGrpcServer(const std::string &server_address, std::shared_ptr< Odb::Lib::App::DesignCache > cache) override
const OdbDesignArgs & args() const override
RequestAuthenticationBase & request_auth() override
RouteController::Vector m_vecControllers
void set_grpc_server(std::shared_ptr< grpc::Server > server)
std::filesystem::path executableDirectory() const
const char * CompressionLevelToString(grpc_compression_level level)
static LoadResult LoadFromFile(const std::string &configPath)