|
Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
|
The PostgreSQL and MySQL/MariaDB clients are asynchronous: queries run on the event loop (io_uring/epoll/kqueue/IOCP) and are awaited from C++20 coroutines (Task handlers and Awaitable<T> helpers), so a waiting handler holds no thread. The other two are not: MongoClient runs the (blocking) MongoDB driver on the thread pool, and RedisClient is synchronous, so use it from handlers that may block (they run on the pool) and keep calls short. See #196.
Include the necessary headers:
Define a handler that returns orbit::concurrency::Task instead of void. You can then use the co_await keyword for database operations.
ORBIT_REGISTER_MODEL(Type, "table") gives a query builder for a JSON-serialisable struct:
update_async() and remove_async() refuse to run (std::logic_error) without a where() condition, so a forgotten filter cannot rewrite or empty a table; call .all() to really affect every row. Table and column names must be plain identifiers; SQL reserved words among them (user, order, group, ...) are quoted for the database ("user" on PostgreSQL, `user` on MySQL), while other names stay unquoted so PostgreSQL's usual lower-case folding still applies. select_statement(), count_statement(), insert_statement(), update_statement() and delete_statement() return the generated SQL and parameters without running it.
A model's primary key is the id field unless it says otherwise. When the key is unset — 0, "" or null — insert_async() leaves it out so the database generates it, and update_async(model) never rewrites it:
create_async() uses RETURNING, which PostgreSQL and MariaDB 10.5+ support; MySQL Server does not and reports an error.
A query that fails throws orbit::orm::DatabaseError from the co_await (get_async, count_async, insert_async, create_async, update_async, remove_async), with the database's message. It no longer looks like "0 rows" or an empty result. In a coroutine handler an uncaught DatabaseError reaches the router's error handling (on_error, else a 500); catch it where a failure has a meaning of its own, such as a duplicate key.
Rows are read by the model's field types: a std::string field receives the column's text even when it looks like a number ("42", "007"), integers and floats are parsed exactly, booleans accept t/f, true/false and 1/0, and JSON object or array fields parse JSON text. Columns the model does not declare are ignored, and a field with no column in the result keeps the value of a default-constructed model. A value that does not fit — NULL in a non-optional field, "abc" in an int — throws DatabaseError.
Never build SQL by concatenating request data. Bind values instead:
The ORM does this for you. orbit::orm::Col("name") == value, where(field, op, value) and insert_async(model) bind every value (as $n parameters on PostgreSQL, or as literals escaped with mysql_real_escape_string on MariaDB/MySQL). Column and table names cannot be bound, so they must be plain identifiers (name, users.created_at) and where() only accepts the operators =, !=, <>, <, <=, >, >=, [NOT] LIKE and [NOT] ILIKE; anything else throws std::invalid_argument.
Every column arrives as text. Row::get_as<T> converts it to bool, an integer type, a floating-point type or std::string, and gives std::nullopt for NULL, a missing column, or text that does not convert exactly ("12abc" is not 12; a value out of range for T is refused):
execute() / execute_async() prepare a statement the first time its SQL is seen on a connection and reuse the plan afterwards, which saves parsing and planning for statements run often:
Up to 256 statements are cached per connection (set_max_prepared_statements()); beyond that they run unprepared. The cache is per server session, so it starts empty after a reconnect.
After a failed statement, PostgreSQL rolls the whole transaction back on COMMIT; commit() then reports a failure ("transaction was rolled back after an earlier error") rather than success. in_transaction() tells whether a transaction block is open.
set_statement_timeout() (before connect()) limits how long each statement may run on the server; a longer one fails with "canceling statement due to statement timeout". To detect an unreachable server, add libpq's connect_timeout, keepalives_idle or tcp_user_timeout to the connection string.
is_healthy() reports whether the connection is usable. After the server drops it (a restart, a failover, pg_terminate_backend), queries fail, is_healthy() turns false, and connect() / reconnect() (or co_await connect_async(db)) establish a new session, with the statement timeout applied again.
orbit::orm::MigrationRunner (<orbit/orm/MigrationRunner.hpp>, PostgreSQL) applies the .sql files in a directory in name order (001_users.sql, 002_index.sql, ...) and records each in an orbit_migrations table, so every file runs once. Each file runs in a transaction together with its tracking row: a failing file leaves nothing behind and stops the run. An advisory lock keeps several instances starting at once from applying the same file twice. Statements that cannot run in a transaction (such as CREATE INDEX CONCURRENTLY) are not supported.
At start-up, before serving, migrate_sync connects, migrates and returns, using its own short-lived event loop:
From a coroutine, with a connected client, co_await MigrationRunner<PostgresClient>::run(db, "migrations") gives the same MigrationResult (applied files, error, summary()). run_migrations(db, dir, writer) answers it over HTTP (200 with the summary, or a 500 whose details go only to the log), for an admin endpoint.
A coroutine handler can use its HttpRequest& (headers, body, params, req.json()) for as long as it runs: across every co_await, on whichever thread it resumes, and even after it has sent the response. On HTTP/1.1 the connection then parses the next request into fresh storage while the handler still holds the old one. No copying is needed.
This holds for the request the coroutine takes as a parameter. A coroutine started from a plain handler gets the same guarantee when the request is passed on as a parameter too:
A request captured by reference in a lambda coroutine ([&req]() -> Task) is not covered: the coroutine cannot see it.
orbit::concurrency::Awaitable<T> is a coroutine a handler can co_await for a result, so database access can live in small helpers:
An Awaitable starts only when awaited and resumes its caller when it finishes. An exception thrown inside it is rethrown at the co_await; uncaught there, it is handled like any handler exception (on_error, else a 500). Handlers themselves keep returning Task.
Simply pass your Coroutine handler to the standard app.get() router:
An exception that escapes a coroutine handler — before or after a co_await, on whichever thread resumed it — is handled like one from a synchronous handler: the router's on_error handler runs, or else the client gets 500 Internal Server Error. The exception text goes to the log, never to the client. This works for any Task coroutine that takes the request's std::shared_ptr<ResponseWriter> as a parameter (that is how the error is routed back to its request).
Two cases are only logged:
ResponseWriter parameter, e.g. a background helper.A coroutine exception never terminates the server.
Pass the writer to the coroutine as a parameter, not a lambda capture: the coroutine finds its request through its parameters.
orbit::database::ConnectionPool hands out connected clients and takes them back. Given a health check, it also drops clients that have stopped working (a database restart, a failover, an idle connection cut by a firewall) and connects replacements in the background, retrying failed attempts with exponential backoff:
A client is checked when it is acquired and when it is released; a dead one is never handed out. Replacements go to waiting acquire() calls first. Retries wait on a detached thread by default; set opts.schedule to run them on your own timers. idle_count(), waiting_count() and reconnecting_count() expose the pool's state, for example for a readiness check.