-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi_server.cpp
More file actions
295 lines (249 loc) · 9.89 KB
/
Copy pathapi_server.cpp
File metadata and controls
295 lines (249 loc) · 9.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#include <yaml-cpp/yaml.h>
#include "api_server.hpp"
#include "auth_middleware.hpp"
#include "database_manager.hpp"
#include "config_service.hpp"
#include "config_tool_adapter.hpp"
#include "open_api_doc_generator.hpp"
#include "open_api_page.hpp"
#include "rate_limit_middleware.hpp"
#include "mcp_session_manager.hpp"
#include "mcp_client_capabilities.hpp"
namespace flapi {
APIServer::APIServer(std::shared_ptr<ConfigManager> cm,
std::shared_ptr<DatabaseManager> db_manager,
bool config_service_enabled,
const std::string& config_service_token)
: configManager(cm), dbManager(db_manager), openAPIDocGenerator(std::make_shared<OpenAPIDocGenerator>(cm, db_manager)), requestHandler(dbManager, cm)
{
// Initialize MCP session manager
mcpSessionManager = std::make_shared<MCPSessionManager>();
// Initialize MCP client capabilities detector
mcpCapabilitiesDetector = std::make_shared<MCPClientCapabilitiesDetector>();
// Create ConfigToolAdapter for configuration management tools
// Only initialize if config-service is enabled
std::unique_ptr<ConfigToolAdapter> config_tool_adapter;
if (config_service_enabled) {
try {
config_tool_adapter = std::make_unique<ConfigToolAdapter>(cm, db_manager);
CROW_LOG_INFO << "ConfigToolAdapter initialized - config MCP tools available";
} catch (const std::exception& e) {
CROW_LOG_WARNING << "Failed to initialize ConfigToolAdapter: " << e.what();
config_tool_adapter = nullptr;
}
} else {
CROW_LOG_DEBUG << "Config service disabled - config MCP tools will not be available";
config_tool_adapter = nullptr;
}
// Initialize MCP route handlers (always enabled in unified configuration)
// Port will be passed when registering routes
CROW_LOG_INFO << "Initializing MCP Route Handlers...";
try {
mcpRouteHandlers = std::make_unique<MCPRouteHandlers>(cm, db_manager, mcpSessionManager,
mcpCapabilitiesDetector,
std::move(config_tool_adapter));
CROW_LOG_DEBUG << "MCP Route Handlers initialized successfully";
} catch (const std::exception& e) {
CROW_LOG_ERROR << "Failed to initialize MCP Route Handlers: " << e.what();
mcpRouteHandlers = nullptr;
}
CROW_LOG_INFO << "APIServer MCP Route Handlers status: " << (mcpRouteHandlers ? "initialized" : "failed to initialize");
// Initialize ConfigService with token authentication
configService = std::make_shared<ConfigService>(configManager, config_service_enabled, config_service_token);
createApp();
setupRoutes();
setupCORS();
setupHeartbeat();
CROW_LOG_INFO << "APIServer initialized with MCP support";
}
APIServer::~APIServer() {
heartbeatWorker->stop();
}
void APIServer::createApp()
{
// Configure middlewares
app.get_middleware<RateLimitMiddleware>().setConfig(configManager);
app.get_middleware<AuthMiddleware>().initialize(configManager);
}
void APIServer::setupRoutes() {
CROW_LOG_INFO << "Setting up routes...";
CROW_LOG_INFO << "APIServer setupRoutes called - MCP Route Handlers available: " << (mcpRouteHandlers ? "yes" : "no");
CROW_ROUTE(app, "/")([](){
CROW_LOG_INFO << "Root route accessed";
std::string logo = R"(
___
___( o)> Welcome to
\ <_. ) flAPI
`---'
Fast and Flexible API Framework
powered by DuckDB
)";
return crow::response(200, "text/plain", logo);
});
configService->setDocGenerator(openAPIDocGenerator);
configService->registerRoutes(app);
CROW_ROUTE(app, "/config")
.methods("GET"_method)
([this](const crow::request& req, crow::response& res) {
res = getConfig();
res.end();
});
CROW_ROUTE(app, "/config")
.methods("DELETE"_method)
([this](const crow::request& req, crow::response& res) {
CROW_LOG_INFO << "Config refresh requested";
res = refreshConfig();
res.end();
});
CROW_ROUTE(app, "/doc")
.methods("GET"_method)
([this]() {
return generateOpenAPIPage(configManager);
});
CROW_ROUTE(app, "/doc.yaml")
.methods("GET"_method)
([this]() {
return generateOpenAPIDoc();
});
// Register MCP routes BEFORE the catch-all route
// This ensures /mcp/jsonrpc matches before the catch-all /<path> route
if (mcpRouteHandlers) {
mcpRouteHandlers->registerRoutes(app, configManager->getHttpPort());
} else {
CROW_LOG_WARNING << "MCP Route Handlers not initialized, skipping MCP route registration";
}
// Endpoint route (supports GET, POST, PUT, PATCH, DELETE)
// Must be registered LAST so specific routes (like /mcp/jsonrpc) match first
CROW_ROUTE(app, "/<path>")
.methods("GET"_method, "POST"_method, "PUT"_method, "PATCH"_method, "DELETE"_method)
([this](const crow::request& req, crow::response& res, std::string path) {
handleDynamicRequest(req, res);
// Note: don't call res.end() here - handlers already call it
});
CROW_LOG_INFO << "Routes set up completed";
}
void APIServer::setupCORS() {
auto& cors = app.get_middleware<crow::CORSHandler>();
cors.global()
.headers("*")
.methods("GET"_method, "POST"_method, "PUT"_method, "PATCH"_method, "DELETE"_method);
}
void APIServer::setupHeartbeat() {
heartbeatWorker = std::make_shared<HeartbeatWorker>(configManager, *this);
heartbeatWorker->start();
}
void APIServer::handleDynamicRequest(const crow::request& req, crow::response& res)
{
std::string path = req.url;
// Match endpoint by both path and HTTP method
std::string method = crow::method_name(req.method);
const auto& endpoint = configManager->getEndpointForPathAndMethod(path, method);
if (!endpoint) {
res.code = 404;
res.body = "Not Found";
res.end();
return;
}
std::vector<std::string> paramNames;
std::map<std::string, std::string> pathParams;
bool matched = RouteTranslator::matchAndExtractParams(endpoint->urlPath, path, paramNames, pathParams);
if (!matched) {
res.code = 404;
res.body = "Not Found";
res.end();
return;
}
// Build auth params from middleware context for template variable injection
auto& auth_ctx = app.get_context<AuthMiddleware>(req);
std::map<std::string, std::string> auth_params;
if (auth_ctx.authenticated) {
auth_params["__auth_username"] = auth_ctx.username;
auth_params["__auth_email"] = auth_ctx.email;
auth_params["__auth_type"] = auth_ctx.auth_type;
auth_params["__auth_authenticated"] = "true";
std::string roles;
for (const auto& r : auth_ctx.roles) {
if (!roles.empty()) {
roles += ",";
}
roles += r;
}
auth_params["__auth_roles"] = roles;
}
requestHandler.handleRequest(req, res, *endpoint, pathParams, auth_params);
}
crow::response APIServer::getConfig() {
try {
crow::json::wvalue config;
config["flapi"] = configManager->getFlapiConfig();
config["endpoints"] = configManager->getEndpointsConfig();
return crow::response(200, config.dump(2));
} catch (const std::exception& e) {
CROW_LOG_ERROR << "Error in getConfig: " << e.what();
return crow::response(500, std::string("Internal Server Error: ") + e.what());
}
}
crow::response APIServer::refreshConfig() {
try {
configManager->refreshConfig();
return crow::response(200, "Configuration refreshed successfully");
} catch (const std::exception& e) {
CROW_LOG_ERROR << "Failed to refresh configuration: " << e.what();
return crow::response(500, std::string("Failed to refresh configuration: ") + e.what());
}
}
crow::response APIServer::generateOpenAPIDoc() {
YAML::Node doc = openAPIDocGenerator->generateDoc(app);
// Convert YAML::Node to string
std::stringstream ss;
ss << doc;
return crow::response(200, ss.str());
}
void APIServer::run(int port) {
if (port > 0) {
configManager->setHttpPort(port);
}
const auto& https = configManager->getHttpsConfig();
if (https.enabled) {
CROW_LOG_INFO << "HTTPS enabled: serving TLS on port " << configManager->getHttpPort();
CROW_LOG_DEBUG << " cert: " << https.ssl_cert_file;
CROW_LOG_DEBUG << " key: " << https.ssl_key_file;
app.port(configManager->getHttpPort())
.server_name("flAPI")
.multithreaded()
.use_compression(crow::compression::GZIP)
.ssl_file(https.ssl_cert_file, https.ssl_key_file)
.run();
} else {
CROW_LOG_INFO << "Server starting on port " << configManager->getHttpPort() << "...";
app.port(configManager->getHttpPort())
.server_name("flAPI")
.multithreaded()
.use_compression(crow::compression::GZIP)
.run();
}
}
void APIServer::requestForEndpoint(const EndpointConfig& endpoint, const std::unordered_map<std::string, std::string>& pathParams)
{
auto req = crow::request();
req.method = crow::HTTPMethod::Get;
req.url = endpoint.urlPath;
std::stringstream qs;
for (const auto& [key, value] : pathParams) {
qs << key << "=" << value << "&";
}
req.url_params = qs.str();
auto res = crow::response();
app.handle_full(req, res);
}
void APIServer::stop() {
heartbeatWorker->stop();
app.stop();
}
std::shared_ptr<CacheManager> APIServer::getCacheManager() const {
return dbManager->getCacheManager();
}
std::shared_ptr<DatabaseManager> APIServer::getDatabaseManager() const {
return dbManager;
}
} // namespace flapi