Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
App.hpp
Go to the documentation of this file.
1#pragma once
3#include <vector>
4#include <thread>
5
14#ifdef ORBIT_ENABLE_HTTP3
16#else
17namespace orbit::server { class QuicConnectionManager; }
18#endif
19#include <atomic>
20#include <chrono>
21#include <functional>
22#include <memory>
23#include <mutex>
24
25namespace orbit::server {
26
27class Scheduler; // src/server/Scheduler.hpp
28
36class App {
37public:
44
45 // Delete copy constructors
46 App(const App&) = delete;
47 App& operator=(const App&) = delete;
48
49 // Middleware
55
62
68 App& use(const std::string& prefix, routing::Middleware m);
69
72
73 // Route Grouping
80 App& group(const std::string& prefix, std::function<void(routing::Router&)> callback) {
81 router_.group(prefix, std::move(callback));
82 return *this;
83 }
84
92 return router_.route(path, method);
93 }
94
95 // Fluent routing API
102 App& get(const std::string& path, routing::RouteHandler handler);
110 App& get(const std::string& path, std::vector<routing::Middleware> mws, routing::RouteHandler handler);
111
118 App& post(const std::string& path, routing::RouteHandler handler);
126 App& post(const std::string& path, std::vector<routing::Middleware> mws, routing::RouteHandler handler);
127
134 App& put(const std::string& path, routing::RouteHandler handler);
142 App& put(const std::string& path, std::vector<routing::Middleware> mws, routing::RouteHandler handler);
143
150 App& patch(const std::string& path, routing::RouteHandler handler);
158 App& patch(const std::string& path, std::vector<routing::Middleware> mws, routing::RouteHandler handler);
159
166 App& del(const std::string& path, routing::RouteHandler handler);
174 App& del(const std::string& path, std::vector<routing::Middleware> mws, routing::RouteHandler handler);
175
182 App& options(const std::string& path, routing::RouteHandler handler);
190 App& options(const std::string& path, std::vector<routing::Middleware> mws, routing::RouteHandler handler);
191
192#define ORBIT_DEFINE_ROUTER_TEMPLATES(METHOD) \
193 template <typename Handler> \
194 App& METHOD(const std::string& path, Handler&& handler) { \
195 return METHOD(path, routing::wrap_handler(std::forward<Handler>(handler))); \
196 } \
197 template <typename Handler> \
198 App& METHOD(const std::string& path, std::vector<routing::Middleware> mws, Handler&& handler) { \
199 return METHOD(path, std::move(mws), routing::wrap_handler(std::forward<Handler>(handler))); \
200 }
201
208#undef ORBIT_DEFINE_ROUTER_TEMPLATES
209
210 // WebSockets
217 App& ws(const std::string& path, std::vector<routing::Middleware> mws, routing::WsHandler handler) {
218 router_.ws(path, std::move(mws), std::move(handler));
219 return *this;
220 }
221
222 App& ws(const std::string& path, routing::WsHandler handler) {
223 router_.ws(path, std::move(handler));
224 return *this;
225 }
226
236 std::vector<size_t> connections_per_event_loop() const;
237
244
246 std::lock_guard<std::mutex> lock(loop_mutex_);
247 if (!thread_pool_) throw std::runtime_error("Server not started");
248 return *thread_pool_;
249 }
250
257
259 const routing::Router& router() const { return router_; }
260
264 std::vector<std::string> validate_routes() const { return router_.validate_routes(); }
265
266 // Metrics
275 App& enable_metrics(const std::string& path = "/metrics");
276
277 // Lifecycle and timers
288 App& on_start(std::function<void(App&)> hook);
289
297 App& on_stop(std::function<void(App&)> hook);
298
311 TimerHandle run_every(std::chrono::milliseconds interval, std::function<void()> callback);
312
315 TimerHandle run_after(std::chrono::milliseconds delay, std::function<void()> callback);
316
317 // OpenAPI & Swagger UI
339 App& enable_openapi(const std::string& title = "Orbit Framework API",
340 const std::string& version = "1.0.0",
341 const std::string& docs_path = "/docs",
342 const std::string& json_path = "/swagger.json",
343 const std::string& assets_url = "https://unpkg.com/swagger-ui-dist@5.11.0");
344
345 // Start the server (blocking)
349 void listen();
350
351 // Stop the server gracefully
356 void stop();
357
365 void shutdown();
366
376 bool reload_tls(std::string* error = nullptr);
377 void shutdown(std::chrono::seconds timeout);
378
385 App& enable_health_checks(const std::string& liveness = "/healthz", const std::string& readiness = "/readyz");
386
388 bool is_draining() const { return draining_.load(); }
389
390 // Hot reload the server
395
396private:
399 // One listening socket per event loop, all on the same port (SO_REUSEPORT).
400 // Declared before the loops, which refer to them.
401 std::vector<std::unique_ptr<Listener>> listeners_;
402#ifdef ORBIT_ENABLE_HTTP3
403 std::unique_ptr<network::UdpSocket> quic_socket_;
404 std::unique_ptr<QuicConnectionManager> quic_manager_;
405#endif
406 std::unique_ptr<network::TlsContext> tls_context_;
407 // event_loops_[0] runs on the thread that called listen() and handles
408 // signals, TLS reloads and QUIC; the others run on loop_threads_.
409 // max_connections budget shared by the loops when there are several.
410 // Declared before the loops, which refer to it.
411 std::atomic<size_t> open_connections_{0};
412 std::vector<std::unique_ptr<EventLoop>> event_loops_;
413 std::vector<std::thread> loop_threads_;
414 // Shared by every loop. Declared after the loops so it is destroyed, and
415 // its workers joined, before them: queued handlers hold connections that
416 // use a loop's proactor.
417 std::unique_ptr<concurrency::ThreadPool> thread_pool_;
418 // Declared after the pool, so it stops before the pool goes away.
419 std::unique_ptr<Scheduler> scheduler_;
420 std::vector<std::function<void(App&)>> start_hooks_;
421 std::vector<std::function<void(App&)>> stop_hooks_;
422 std::atomic<bool> started_{false};
423 std::atomic<bool> stop_hooks_ran_{false};
425 // listen() creates the loops on the server thread while stop() may run
426 // on any thread (a test, a signal, an admin endpoint).
427 mutable std::mutex loop_mutex_;
428 bool stop_requested_ = false; // guarded by loop_mutex_; a stop before the loop exists still applies
429 unsigned seen_signal_seq_ = 0; // loop thread only
430 std::chrono::steady_clock::time_point next_tls_check_{}; // loop thread only
431 std::atomic<bool> draining_{false};
432};
433
434} // namespace server
#define ORBIT_DEFINE_ROUTER_TEMPLATES(METHOD)
Definition App.hpp:192
Definition ThreadPool.hpp:13
Definition OpenApi.hpp:20
A builder class for fluent route configuration.
Definition Router.hpp:63
Manages routing of HTTP requests to their appropriate handlers.
Definition Router.hpp:46
openapi::OpenApiRegistry & openapi()
The OpenAPI registry for this router tree (shared by its groups).
Definition Router.hpp:58
std::vector< std::string > validate_routes() const
Finds routes registered more than once: the same HTTP method and exact path pattern (text,...
void ws(const std::string &path, WsHandler handler)
void group(const std::string &prefix, std::function< void(Router &)> callback)
Creates a route group with a specific prefix.
RouteBuilder route(const std::string &path, http::HttpMethod method=http::HttpMethod::GET)
Initiates a route builder for a specific path and method.
Definition Router.hpp:95
The main application class for the Orbit Framework.
Definition App.hpp:36
App & get(const std::string &path, routing::RouteHandler handler)
Registers a GET route.
std::mutex loop_mutex_
Definition App.hpp:427
std::vector< std::thread > loop_threads_
Definition App.hpp:413
App & ws(const std::string &path, std::vector< routing::Middleware > mws, routing::WsHandler handler)
Registers a WebSocket route.
Definition App.hpp:217
void shutdown()
Stops the server gracefully (what SIGTERM/SIGINT do): stop accepting, mark the app not ready,...
bool is_draining() const
True once shutdown() (or SIGTERM/SIGINT) has started draining.
Definition App.hpp:388
App & patch(const std::string &path, routing::RouteHandler handler)
Registers a PATCH route.
std::unique_ptr< concurrency::ThreadPool > thread_pool_
Definition App.hpp:417
App & options(const std::string &path, routing::RouteHandler handler)
Registers an OPTIONS route.
App & ws(const std::string &path, routing::WsHandler handler)
Definition App.hpp:222
App & del(const std::string &path, routing::RouteHandler handler)
Registers a DELETE route.
TimerHandle run_every(std::chrono::milliseconds interval, std::function< void()> callback)
Calls callback every interval, on a worker thread, from when the server starts (or now,...
std::vector< size_t > connections_per_event_loop() const
Retrieves the application's thread pool.
App & operator=(const App &)=delete
void listen()
Starts the server and blocks the current thread.
void stop()
Stops the server immediately: open connections are dropped. Safe to call from any thread,...
App(const config::ServerConfig &config)
Constructs a new App instance.
config::ServerConfig config_
Definition App.hpp:397
App & put(const std::string &path, std::vector< routing::Middleware > mws, routing::RouteHandler handler)
Registers a PUT route with middleware.
App & use(const std::string &prefix, routing::Middleware m)
Runs m only for requests under prefix ("/api" and "/api/...").
const config::ServerConfig & effective_config() const
The configuration in effect: once listen() has started, "auto" settings (event_loops = 0,...
Definition App.hpp:243
App & patch(const std::string &path, std::vector< routing::Middleware > mws, routing::RouteHandler handler)
Registers a PATCH route with middleware.
App & post(const std::string &path, std::vector< routing::Middleware > mws, routing::RouteHandler handler)
Registers a POST route with middleware.
App & post(const std::string &path, routing::RouteHandler handler)
Registers a POST route.
App & enable_metrics(const std::string &path="/metrics")
Enables Prometheus metrics endpoint.
App & options(const std::string &path, std::vector< routing::Middleware > mws, routing::RouteHandler handler)
Registers an OPTIONS route with middleware.
App(const App &)=delete
App & not_found(routing::RouteHandler handler)
Answers requests that match no route instead of "404 Not Found".
TimerHandle run_after(std::chrono::milliseconds delay, std::function< void()> callback)
void shutdown(std::chrono::seconds timeout)
std::vector< std::unique_ptr< EventLoop > > event_loops_
Definition App.hpp:412
App & enable_health_checks(const std::string &liveness="/healthz", const std::string &readiness="/readyz")
Adds health endpoints for orchestrators such as Kubernetes: liveness answers 200 while the process ru...
App & put(const std::string &path, routing::RouteHandler handler)
Registers a PUT route.
App & group(const std::string &prefix, std::function< void(routing::Router &)> callback)
Creates a route group with a specific prefix.
Definition App.hpp:80
std::vector< std::unique_ptr< Listener > > listeners_
Definition App.hpp:401
bool stop_requested_
Definition App.hpp:428
std::vector< std::string > validate_routes() const
Definition App.hpp:264
void on_error(routing::ErrorHandler handler)
Registers a global error handler for the application.
std::vector< std::function< void(App &)> > stop_hooks_
Definition App.hpp:421
std::unique_ptr< Scheduler > scheduler_
Definition App.hpp:419
std::chrono::steady_clock::time_point next_tls_check_
Definition App.hpp:430
std::atomic< bool > draining_
Definition App.hpp:431
unsigned seen_signal_seq_
Definition App.hpp:429
std::atomic< bool > stop_hooks_ran_
Definition App.hpp:423
App & use(routing::Middleware m)
Registers a global middleware.
std::unique_ptr< network::TlsContext > tls_context_
Definition App.hpp:406
App & get(const std::string &path, std::vector< routing::Middleware > mws, routing::RouteHandler handler)
Registers a GET route with middleware.
std::vector< std::function< void(App &)> > start_hooks_
Definition App.hpp:420
const routing::Router & router() const
The router every request goes through (orbit::testing::Client uses it).
Definition App.hpp:259
App & on_stop(std::function< void(App &)> hook)
Runs hook once when the server stops: at the first shutdown() (or SIGTERM/SIGINT) before connections ...
App & del(const std::string &path, std::vector< routing::Middleware > mws, routing::RouteHandler handler)
Registers a DELETE route with middleware.
std::atomic< bool > started_
Definition App.hpp:422
std::atomic< size_t > open_connections_
Definition App.hpp:411
void hot_reload()
Triggers a hot reload of the server configuration and routes.
routing::Router router_
Definition App.hpp:398
App & enable_openapi(const std::string &title="Orbit Framework API", const std::string &version="1.0.0", const std::string &docs_path="/docs", const std::string &json_path="/swagger.json", const std::string &assets_url="https://unpkg.com/swagger-ui-dist@5.11.0")
Enables OpenAPI documentation and Swagger UI.
openapi::OpenApiRegistry & openapi()
This app's OpenAPI registry: its routes, plus schemas added with openapi().register_schema()....
Definition App.hpp:256
routing::Router::RouteBuilder route(const std::string &path, http::HttpMethod method=http::HttpMethod::GET)
Initiates a route builder for a specific path and method.
Definition App.hpp:91
App & on_start(std::function< void(App &)> hook)
Runs hook once the server is up: listeners bound, worker pool and timers running, just before the eve...
concurrency::ThreadPool & get_thread_pool()
Definition App.hpp:245
bool reload_tls(std::string *error=nullptr)
Re-reads the TLS certificate and key files (ssl_cert, ssl_key and sni_certificates)....
A timer from App::run_every() or App::run_after().
Definition Timer.hpp:15
Definition Config.hpp:8
HttpMethod
Represents standard HTTP methods.
Definition HttpRequest.hpp:28
std::function< void(http::websocket::WebSocketConnection &)> WsHandler
Definition Router.hpp:20
std::function< bool(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> Middleware
Definition Router.hpp:19
std::function< void(http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> RouteHandler
Definition Router.hpp:18
std::function< void(const std::exception &, http::HttpRequest &, std::shared_ptr< http::ResponseWriter >)> ErrorHandler
Definition Router.hpp:21
Definition Http2Session.hpp:18
Definition Config.hpp:30