Study · C11 + C++20 · CoAkkaHttpHost 2.3.0 · ABI 10
Learn CoAkka HTTP Runtime through its public C ABI
Start in C so ownership, event leases and terminals are visible. Then use C++ RAII over that same ABI without creating a second transport, policy or lifecycle in the wrapper.
Beginner · 01 / 04
Install the SDK first; configure a service later
Check the compiler and CMake. The SDK must match the OS/CPU and keep the header, library and CMake metadata from one 2.3.0 artifact.
cmake --version
cc --version
c++ --versionDownload coakka-http-runtime-native-2.3.0-<target>.tar.gz
and its official checksum ledger, verify SHA-256, then set an
absolute path to the extracted prefix:
export COAKKA_HTTP_SDK=/absolute/path/to/coakka-http-runtime-native-2.3.0
CoAkkaHttpHost 2.3.0- The app-host/event API package identity; it is also the package serving this Portal.
COAKKA_HTTP_HOST_ABI_VERSION- The public C ABI is
10. Package version, Core generation and ABI are separate identities. <coakka/http/host.h>- The only header in this Study; never mix it with a historical callback SDK or another archive.
CoAkkaHttp::host- The imported CMake target carrying include, library and loader contracts.
The compiler, SDK and loader prepare a binary. Bind address, route, protocol and limits are declared only when the service is created.
Beginner · 02 / 04
Build and run the first C service
Create the three files from these blocks. CMake pins package 2.3.0 and enables warnings-as-errors for the Study source.
cmake_minimum_required(VERSION 3.24)
project(coakka_http_native_study LANGUAGES C CXX)
find_package(CoAkkaHttpHost 2.3.0 EXACT CONFIG REQUIRED)
find_package(Threads REQUIRED)
add_executable(http-study-c server.c)
target_link_libraries(http-study-c PRIVATE CoAkkaHttp::host)
set_target_properties(http-study-c PROPERTIES
C_STANDARD 11
C_STANDARD_REQUIRED YES
C_EXTENSIONS NO
)
target_compile_options(http-study-c PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_executable(http-study-cpp server.cpp)
target_link_libraries(http-study-cpp PRIVATE CoAkkaHttp::host)
set_target_properties(http-study-cpp PROPERTIES
CXX_STANDARD 20
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS NO
)
target_compile_options(http-study-cpp PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_executable(http-study-advanced advanced.cpp)
target_link_libraries(http-study-advanced PRIVATE CoAkkaHttp::host Threads::Threads)
set_target_properties(http-study-advanced PROPERTIES
CXX_STANDARD 20
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS NO
)
target_compile_options(http-study-advanced PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_executable(http-study-file file.cpp)
target_link_libraries(http-study-file PRIVATE CoAkkaHttp::host)
set_target_properties(http-study-file PROPERTIES
CXX_STANDARD 20
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS NO
)
target_compile_options(http-study-file PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_executable(http-study-sse sse.cpp)
target_link_libraries(http-study-sse PRIVATE CoAkkaHttp::host)
set_target_properties(http-study-sse PROPERTIES
CXX_STANDARD 20
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS NO
)
target_compile_options(http-study-sse PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_executable(http-study-websocket websocket.cpp)
target_link_libraries(http-study-websocket PRIVATE CoAkkaHttp::host Threads::Threads)
set_target_properties(http-study-websocket PROPERTIES
CXX_STANDARD 20
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS NO
)
target_compile_options(http-study-websocket PRIVATE -Wall -Wextra -Wpedantic -Werror)
#include <coakka/http/host.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static coakka_http_host_bytes_t bytes(const char *text) {
const coakka_http_host_bytes_t value = {
.data = (const uint8_t *)text,
.size = strlen(text),
};
return value;
}
static int check(coakka_http_host_status_t status, const char *operation) {
if (status == COAKKA_HTTP_HOST_OK) return 1;
fprintf(stderr, "%s: %s\n", operation,
coakka_http_host_status_name(status));
return 0;
}
static int close_service(coakka_http_host_service_t **service) {
if (*service == NULL) return 1;
const int stopped =
check(coakka_http_host_service_stop(*service), "stop service");
const int destroyed =
check(coakka_http_host_service_destroy(service), "destroy service");
return stopped && destroyed;
}
static int serve_one(coakka_http_host_service_t *service) {
coakka_http_host_request_event_t request;
coakka_http_host_request_event_init(&request);
if (!check(coakka_http_host_take_request(service, 30000U, &request),
"take request")) {
return 0;
}
const coakka_http_host_exchange_t exchange = request.exchange;
coakka_http_host_request_view_t view;
coakka_http_host_request_view_init(&view);
const int is_request = request.kind == COAKKA_HTTP_HOST_REQUEST;
const int projected =
is_request && check(coakka_http_host_request_view(&request, &view),
"project request");
if (projected) {
printf("request=%.*s %.*s\n", (int)view.method.size, view.method.data,
(int)view.target.size, view.target.data);
}
/* view borrows request storage. Copy anything retained before release. */
const int released = check(coakka_http_host_release_request(service, &request),
"release request");
if (!projected || !released) return 0;
coakka_http_host_response_t response;
coakka_http_host_response_init(&response);
response.status_code = 200U;
response.body = bytes("hello native\n");
if (!check(coakka_http_host_respond(service, exchange, &response),
"respond")) {
return 0;
}
coakka_http_host_request_event_t terminal;
coakka_http_host_request_event_init(&terminal);
if (!check(coakka_http_host_take_request(service, 5000U, &terminal),
"take terminal")) {
return 0;
}
const int matched = terminal.kind == COAKKA_HTTP_HOST_REQUEST_TERMINAL &&
terminal.exchange.slot == exchange.slot &&
terminal.exchange.generation == exchange.generation;
const int terminal_released = check(
coakka_http_host_release_request(service, &terminal), "release terminal");
return matched && terminal_released;
}
int main(void) {
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
coakka_http_host_route_t route;
coakka_http_host_route_init(&route);
route.route_id = 1U;
route.handler_binding_id = 1U;
route.method = bytes("GET");
route.encoded_path_pattern = bytes("/hello");
coakka_http_host_service_t *service = NULL;
uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
if (!check(coakka_http_host_service_create(
&configuration, &route, 1U, &service, &failed_route),
"create service")) {
return EXIT_FAILURE;
}
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
if (!check(coakka_http_host_service_start(service, &issue), "start service")) {
close_service(&service);
return EXIT_FAILURE;
}
uint16_t port = 0U;
if (!check(coakka_http_host_service_port(service, &port), "read port")) {
close_service(&service);
return EXIT_FAILURE;
}
printf("http://127.0.0.1:%u/hello\n", (unsigned)port);
fflush(stdout);
const int served = serve_one(service);
const int closed = close_service(&service);
return served && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}
cmake -S . -B build \
-DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK" \
-DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release
./build/http-study-cThe program prints its effective URL. In a second terminal:
curl -i http://127.0.0.1:49321/hello
HTTP/1.1 200 OK
...
hello native
configuration_init- Sets
struct_sizeand bounded defaults. Always initialize before assigning fields. port = 0- The default asks the OS for a free port; read the effective port after start.
route_id- Core's stable route identity, not a handler pointer.
handler_binding_id- The connector/app-host dispatch identity. An admitted request retains its binding revision.
Beginner · 03 / 04
One reader, one lease, then a response
take_requestreturns a native-owned event lease.request_viewprojects scalars/counts and byte spans borrowing that lease.- Copy every retained byte, save the exact
exchange, thenrelease_request. respondcopies the response synchronously; the terminal closes the outcome and must also be released.
| Value | Owner/lifetime | Avoid |
|---|---|---|
request_view_t | Owns no bytes; expires when the event is released. | Passing its pointer to another worker. |
exchange | Value identity: slot + generation. | Matching by slot alone or guessing liveness. |
| Response body | Borrowed through the call; Core copies on successful submit. | Reading success as proof that the peer consumed every byte. |
| Terminal event | A separate lease that must be released. | Ignoring retained state that can prevent destroy. |
Beginner · 04 / 04
C++ only wraps the owner with RAII
Save this source as server.cpp. Routes, leases and
statuses still use the C ABI; the class only prevents copies,
retains the owner pointer and requires a checked close.
#include <coakka/http/host.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <string>
namespace {
coakka_http_host_bytes_t bytes(const char *text) {
return {reinterpret_cast<const std::uint8_t *>(text), std::strlen(text)};
}
bool check(coakka_http_host_status_t status, const char *operation) {
if (status == COAKKA_HTTP_HOST_OK) return true;
std::fprintf(stderr, "%s: %s\n", operation,
coakka_http_host_status_name(status));
return false;
}
class Service final {
public:
Service() = default;
Service(const Service &) = delete;
Service &operator=(const Service &) = delete;
~Service() noexcept {
if (value_ != nullptr && !close()) std::terminate();
}
bool open() {
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
coakka_http_host_route_t route;
coakka_http_host_route_init(&route);
route.route_id = 1U;
route.handler_binding_id = 1U;
route.method = bytes("GET");
route.encoded_path_pattern = bytes("/hello");
std::uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
if (!check(coakka_http_host_service_create(
&configuration, &route, 1U, &value_, &failed_route),
"create service")) {
return false;
}
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
if (!check(coakka_http_host_service_start(value_, &issue),
"start service")) {
return false;
}
return check(coakka_http_host_service_port(value_, &port_), "read port");
}
bool serve_one() {
coakka_http_host_request_event_t request;
coakka_http_host_request_event_init(&request);
if (!check(coakka_http_host_take_request(value_, 30000U, &request),
"take request")) {
return false;
}
const auto exchange = request.exchange;
coakka_http_host_request_view_t view;
coakka_http_host_request_view_init(&view);
const bool projected = request.kind == COAKKA_HTTP_HOST_REQUEST &&
check(coakka_http_host_request_view(&request, &view),
"project request");
const std::string method = projected
? std::string(reinterpret_cast<const char *>(
view.method.data),
view.method.size)
: std::string{};
const std::string target = projected
? std::string(reinterpret_cast<const char *>(
view.target.data),
view.target.size)
: std::string{};
const bool released = check(
coakka_http_host_release_request(value_, &request), "release request");
if (!projected || !released) return false;
std::printf("request=%s %s\n", method.c_str(), target.c_str());
coakka_http_host_response_t response;
coakka_http_host_response_init(&response);
response.status_code = 200U;
response.body = bytes("hello native\n");
if (!check(coakka_http_host_respond(value_, exchange, &response),
"respond")) {
return false;
}
coakka_http_host_request_event_t terminal;
coakka_http_host_request_event_init(&terminal);
if (!check(coakka_http_host_take_request(value_, 5000U, &terminal),
"take terminal")) {
return false;
}
const bool matched = terminal.kind == COAKKA_HTTP_HOST_REQUEST_TERMINAL &&
terminal.exchange.slot == exchange.slot &&
terminal.exchange.generation == exchange.generation;
const bool terminal_released = check(
coakka_http_host_release_request(value_, &terminal), "release terminal");
return matched && terminal_released;
}
bool close() noexcept {
if (value_ == nullptr) return true;
const bool stopped =
check(coakka_http_host_service_stop(value_), "stop service");
const bool destroyed =
check(coakka_http_host_service_destroy(&value_), "destroy service");
return stopped && destroyed;
}
[[nodiscard]] std::uint16_t port() const noexcept { return port_; }
private:
coakka_http_host_service_t *value_ = nullptr;
std::uint16_t port_ = 0U;
};
} // namespace
int main() {
Service service;
if (!service.open()) return EXIT_FAILURE;
std::printf("http://127.0.0.1:%u/hello\n",
static_cast<unsigned>(service.port()));
std::fflush(stdout);
const bool served = service.serve_one();
return service.close() && served ? EXIT_SUCCESS : EXIT_FAILURE;
}
cmake --build build --config Release
./build/http-study-cpp- Deleted copy
- A wrapper cannot create two owners for one service.
- Explicit
close() - Main has somewhere to receive failure; the destructor is a last-resort invariant guard.
- Retained owner
- A destroy failure keeps the pointer non-null so leases can be released and destroy retried.
- No restart
- A stopped instance never returns to Started; create a new instance.
Advanced · 05
Learn one capability at a time, then combine them
Native makes ownership more explicit, so the lesson benefits even more from separation. Each first file retains only the lane and lifecycle needed by one capability; the integration exercise combines them later.
01 · File deliveryAuthority, relative path and limits; CoAkka HTTP Runtime selects sendfile when eligible.
#include <coakka/http/host.h>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <string>
namespace {
volatile std::sig_atomic_t stop_requested = 0;
coakka_http_host_bytes_t bytes(const char *text) {
return {reinterpret_cast<const std::uint8_t *>(text), std::strlen(text)};
}
coakka_http_host_bytes_t bytes(const std::string &text) {
return {reinterpret_cast<const std::uint8_t *>(text.data()), text.size()};
}
bool check(coakka_http_host_status_t status, const char *operation) {
if (status == COAKKA_HTTP_HOST_OK) {
return true;
}
std::fprintf(stderr, "%s: %s\n", operation,
coakka_http_host_status_name(status));
return false;
}
void request_stop(int) { stop_requested = 1; }
} // namespace
int main() {
std::signal(SIGINT, request_stop);
const auto root =
std::filesystem::temp_directory_path() /
("coakka-http-file-" +
std::to_string(
std::chrono::steady_clock::now().time_since_epoch().count()));
std::filesystem::create_directory(root);
std::ofstream(root / "manual.txt", std::ios::binary)
<< "CoAkka file delivery\n";
const auto root_text = root.string();
coakka_http_host_file_authority_t authority;
coakka_http_host_file_authority_init(&authority);
authority.authority_id = 1U;
authority.root_path = bytes(root_text);
authority.max_active_files = 4U;
authority.max_file_bytes = 1024U;
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
configuration.file_authorities = &authority;
configuration.file_authority_count = 1U;
coakka_http_host_route_t route;
coakka_http_host_route_init(&route);
route.route_id = 1U;
route.handler_binding_id = 1U;
route.method = bytes("GET");
route.encoded_path_pattern = bytes("/download");
coakka_http_host_service_t *service = nullptr;
std::uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
bool ok = check(coakka_http_host_service_create(&configuration, &route, 1U,
&service, &failed_route),
"create service");
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
ok = ok &&
check(coakka_http_host_service_start(service, &issue), "start service");
std::uint16_t port = 0U;
ok = ok && check(coakka_http_host_service_port(service, &port), "read port");
if (ok) {
std::printf("curl http://127.0.0.1:%u/download\n", port);
std::printf("Press Ctrl+C to close\n");
std::fflush(stdout);
}
while (ok && stop_requested == 0) {
coakka_http_host_request_event_t event;
coakka_http_host_request_event_init(&event);
const auto status = coakka_http_host_take_request(service, 100U, &event);
if (status == COAKKA_HTTP_HOST_TIMEOUT) {
continue;
}
if (status == COAKKA_HTTP_HOST_CLOSED) {
break;
}
ok = check(status, "take request");
if (!ok) {
break;
}
if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
coakka_http_host_file_response_t response;
coakka_http_host_file_response_init(&response);
response.head.status_code = 200U;
response.authority_id = 1U;
response.encoded_path = bytes("/manual.txt");
ok = check(
coakka_http_host_respond_file(service, event.exchange, &response),
"respond with file");
}
ok = check(coakka_http_host_release_request(service, &event),
"release request") &&
ok;
}
if (service != nullptr) {
ok = check(coakka_http_host_service_stop(service), "stop service") && ok;
ok = check(coakka_http_host_service_destroy(&service), "destroy service") &&
ok;
}
std::filesystem::remove_all(root);
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
cmake --build build --config Release
./build/http-study-file02 · Server-Sent EventsRequest, writable signal, two events and a stream terminal.
#include <coakka/http/host.h>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace {
volatile std::sig_atomic_t stop_requested = 0;
coakka_http_host_bytes_t bytes(const char *text) {
return {reinterpret_cast<const std::uint8_t *>(text), std::strlen(text)};
}
bool check(coakka_http_host_status_t status, const char *operation) {
if (status == COAKKA_HTTP_HOST_OK) {
return true;
}
std::fprintf(stderr, "%s: %s\n", operation,
coakka_http_host_status_name(status));
return false;
}
bool write_events(coakka_http_host_service_t *service,
coakka_http_host_exchange_t exchange) {
coakka_http_host_sse_event_t event;
coakka_http_host_sse_event_init(&event);
event.data = bytes("ready");
event.event_type = bytes("state");
event.id = bytes("1");
event.retry_ms = 1000U;
event.has_event_type = 1U;
event.has_id = 1U;
event.has_retry = 1U;
if (!check(coakka_http_host_write_sse(service, exchange, &event),
"write SSE event")) {
return false;
}
coakka_http_host_sse_event_init(&event);
event.data = bytes("done");
return check(coakka_http_host_write_sse(service, exchange, &event),
"write SSE event") &&
check(coakka_http_host_finish_response_stream(service, exchange,
nullptr, 0U),
"finish SSE");
}
void request_stop(int) { stop_requested = 1; }
} // namespace
int main() {
std::signal(SIGINT, request_stop);
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
coakka_http_host_route_t route;
coakka_http_host_route_init(&route);
route.route_id = 1U;
route.handler_binding_id = 1U;
route.method = bytes("GET");
route.encoded_path_pattern = bytes("/events");
coakka_http_host_service_t *service = nullptr;
std::uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
bool ok = check(coakka_http_host_service_create(&configuration, &route, 1U,
&service, &failed_route),
"create service");
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
ok = ok &&
check(coakka_http_host_service_start(service, &issue), "start service");
std::uint16_t port = 0U;
ok = ok && check(coakka_http_host_service_port(service, &port), "read port");
if (ok) {
std::printf("curl -N http://127.0.0.1:%u/events\n", port);
std::printf("Press Ctrl+C to close\n");
std::fflush(stdout);
}
while (ok && stop_requested == 0) {
coakka_http_host_request_event_t event;
coakka_http_host_request_event_init(&event);
const auto status = coakka_http_host_take_request(service, 100U, &event);
if (status == COAKKA_HTTP_HOST_TIMEOUT) {
continue;
}
if (status == COAKKA_HTTP_HOST_CLOSED) {
break;
}
ok = check(status, "take request");
if (!ok) {
break;
}
const auto exchange = event.exchange;
const bool writable = event.kind == COAKKA_HTTP_HOST_RESPONSE_WRITABLE;
if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
ok = check(coakka_http_host_start_sse(service, exchange, nullptr, 0U),
"start SSE");
}
ok = check(coakka_http_host_release_request(service, &event),
"release request") &&
ok;
if (ok && writable) {
ok = write_events(service, exchange);
}
}
if (service != nullptr) {
ok = check(coakka_http_host_service_stop(service), "stop service") && ok;
ok = check(coakka_http_host_service_destroy(&service), "destroy service") &&
ok;
}
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
cmake --build build --config Release
./build/http-study-sse03 · WebSocketOne request reader, one WebSocket reader and explicit event release.
#include <coakka/http/host.h>
#include <atomic>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <thread>
namespace {
volatile std::sig_atomic_t stop_requested = 0;
coakka_http_host_bytes_t bytes(const char *text) {
return {reinterpret_cast<const std::uint8_t *>(text), std::strlen(text)};
}
coakka_http_host_bytes_t bytes(const std::string &text) {
return {reinterpret_cast<const std::uint8_t *>(text.data()), text.size()};
}
bool check(coakka_http_host_status_t status, const char *operation) {
if (status == COAKKA_HTTP_HOST_OK) {
return true;
}
std::fprintf(stderr, "%s: %s\n", operation,
coakka_http_host_status_name(status));
return false;
}
void read_websockets(coakka_http_host_service_t *service,
const std::atomic<bool> &stopping) {
while (!stopping.load()) {
coakka_http_host_websocket_event_t event;
coakka_http_host_websocket_event_init(&event);
const auto status = coakka_http_host_take_websocket(service, 100U, &event);
if (status == COAKKA_HTTP_HOST_TIMEOUT) {
continue;
}
if (status == COAKKA_HTTP_HOST_CLOSED) {
return;
}
if (!check(status, "take WebSocket event")) {
return;
}
const auto session = event.session;
const bool send_greeting = event.kind == COAKKA_HTTP_HOST_WEBSOCKET_OPEN;
std::string reply;
if (event.kind == COAKKA_HTTP_HOST_WEBSOCKET_TEXT) {
reply = "echo: ";
reply.append(reinterpret_cast<const char *>(event.data.data),
event.data.size);
}
if (!check(coakka_http_host_release_websocket(service, &event),
"release WebSocket event")) {
return;
}
if (send_greeting) {
(void)check(coakka_http_host_send_websocket(
service, session, COAKKA_HTTP_HOST_WEBSOCKET_TEXT,
bytes("ready")),
"send WebSocket greeting");
} else if (!reply.empty()) {
(void)check(
coakka_http_host_send_websocket(
service, session, COAKKA_HTTP_HOST_WEBSOCKET_TEXT, bytes(reply)),
"send WebSocket echo");
}
}
}
void request_stop(int) { stop_requested = 1; }
} // namespace
int main() {
std::signal(SIGINT, request_stop);
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
coakka_http_host_route_t route;
coakka_http_host_route_init(&route);
route.route_id = 1U;
route.handler_binding_id = 1U;
route.method = bytes("GET");
route.encoded_path_pattern = bytes("/socket");
route.flags = COAKKA_HTTP_HOST_ROUTE_WEBSOCKET;
coakka_http_host_service_t *service = nullptr;
std::uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
bool ok = check(coakka_http_host_service_create(&configuration, &route, 1U,
&service, &failed_route),
"create service");
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
ok = ok &&
check(coakka_http_host_service_start(service, &issue), "start service");
std::uint16_t port = 0U;
ok = ok && check(coakka_http_host_service_port(service, &port), "read port");
if (ok) {
std::printf("new WebSocket('ws://127.0.0.1:%u/socket', 'coakka.demo')\n",
port);
std::printf("Press Ctrl+C to close\n");
std::fflush(stdout);
}
std::atomic<bool> stopping{false};
std::thread websocket_reader;
if (ok) {
websocket_reader = std::thread(
[service, &stopping] { read_websockets(service, stopping); });
}
while (ok && stop_requested == 0) {
coakka_http_host_request_event_t event;
coakka_http_host_request_event_init(&event);
const auto status = coakka_http_host_take_request(service, 100U, &event);
if (status == COAKKA_HTTP_HOST_TIMEOUT) {
continue;
}
if (status == COAKKA_HTTP_HOST_CLOSED) {
break;
}
ok = check(status, "take request");
if (!ok) {
break;
}
if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
ok = check(coakka_http_host_accept_websocket(service, event.exchange,
bytes("coakka.demo")),
"accept WebSocket");
}
ok = check(coakka_http_host_release_request(service, &event),
"release request") &&
ok;
}
stopping.store(true);
if (service != nullptr) {
ok = check(coakka_http_host_service_stop(service), "stop service") && ok;
}
if (websocket_reader.joinable()) {
websocket_reader.join();
}
if (service != nullptr) {
ok = check(coakka_http_host_service_destroy(&service), "destroy service") &&
ok;
}
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
cmake --build build --config Release
./build/http-study-websocket04 · Combine them in one serviceAn optional integration exercise after all three ownership contracts are clear.
#include <coakka/http/host.h>
#include <array>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <string>
#include <thread>
namespace {
volatile std::sig_atomic_t stop_requested = 0;
coakka_http_host_bytes_t bytes(const char *text) {
return {reinterpret_cast<const std::uint8_t *>(text), std::strlen(text)};
}
coakka_http_host_bytes_t bytes(const std::string &text) {
return {reinterpret_cast<const std::uint8_t *>(text.data()), text.size()};
}
bool check(coakka_http_host_status_t status, const char *operation) {
if (status == COAKKA_HTTP_HOST_OK)
return true;
std::fprintf(stderr, "%s: %s\n", operation,
coakka_http_host_status_name(status));
return false;
}
class AdvancedService final {
public:
AdvancedService() = default;
AdvancedService(const AdvancedService &) = delete;
AdvancedService &operator=(const AdvancedService &) = delete;
~AdvancedService() noexcept { close(); }
bool open(const std::filesystem::path &root) {
root_ = root.string();
coakka_http_host_file_authority_t authority;
coakka_http_host_file_authority_init(&authority);
authority.authority_id = 1U;
authority.root_path = bytes(root_);
authority.max_active_files = 4U;
authority.max_file_bytes = 1024U;
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
configuration.file_authorities = &authority;
configuration.file_authority_count = 1U;
std::array<coakka_http_host_route_t, 3> routes{};
const std::array<const char *, 3> paths = {"/download", "/events",
"/socket"};
for (std::size_t index = 0; index < routes.size(); ++index) {
coakka_http_host_route_init(&routes[index]);
routes[index].route_id = index + 1U;
routes[index].handler_binding_id = index + 1U;
routes[index].method = bytes("GET");
routes[index].encoded_path_pattern = bytes(paths[index]);
}
routes[2].flags = COAKKA_HTTP_HOST_ROUTE_WEBSOCKET;
std::uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
if (!check(coakka_http_host_service_create(&configuration, routes.data(),
routes.size(), &service_,
&failed_route),
"create service")) {
return false;
}
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
if (!check(coakka_http_host_service_start(service_, &issue),
"start service") ||
!check(coakka_http_host_service_port(service_, &port_), "read port")) {
return false;
}
websocket_reader_ = std::thread([this] { read_websockets(); });
return true;
}
bool serve_until_signal() {
while (stop_requested == 0) {
coakka_http_host_request_event_t event;
coakka_http_host_request_event_init(&event);
const auto status = coakka_http_host_take_request(service_, 100U, &event);
if (status == COAKKA_HTTP_HOST_TIMEOUT)
continue;
if (status == COAKKA_HTTP_HOST_CLOSED)
break;
if (!check(status, "take request"))
return false;
bool handled = true;
const bool sse_writable =
event.kind == COAKKA_HTTP_HOST_RESPONSE_WRITABLE;
const auto exchange = event.exchange;
if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
if (event.handler_binding_id == 1U) {
handled = serve_file(exchange);
} else if (event.handler_binding_id == 2U) {
handled = start_events(exchange);
} else if (event.handler_binding_id == 3U) {
handled = check(coakka_http_host_accept_websocket(
service_, exchange, bytes("coakka.demo")),
"accept WebSocket");
}
}
const bool released =
check(coakka_http_host_release_request(service_, &event),
"release request");
if (!handled || !released)
return false;
if (sse_writable && !write_events(exchange))
return false;
}
return true;
}
void print_instructions() const {
std::printf("file: curl http://127.0.0.1:%u/download\n", port_);
std::printf("SSE: curl -N http://127.0.0.1:%u/events\n", port_);
std::printf(
"WS: new WebSocket('ws://127.0.0.1:%u/socket', 'coakka.demo')\n",
port_);
std::printf("Press Ctrl+C to close\n");
std::fflush(stdout);
}
bool close() noexcept {
if (service_ == nullptr)
return true;
stopping_.store(true);
const bool stopped =
check(coakka_http_host_service_stop(service_), "stop service");
if (websocket_reader_.joinable())
websocket_reader_.join();
const bool destroyed =
check(coakka_http_host_service_destroy(&service_), "destroy service");
return stopped && destroyed;
}
private:
bool serve_file(coakka_http_host_exchange_t exchange) {
coakka_http_host_file_response_t response;
coakka_http_host_file_response_init(&response);
response.head.status_code = 200U;
response.authority_id = 1U;
response.encoded_path = bytes("/manual.txt");
return check(coakka_http_host_respond_file(service_, exchange, &response),
"respond with file");
}
bool start_events(coakka_http_host_exchange_t exchange) {
return check(coakka_http_host_start_sse(service_, exchange, nullptr, 0U),
"start SSE");
}
bool write_events(coakka_http_host_exchange_t exchange) {
coakka_http_host_sse_event_t event;
coakka_http_host_sse_event_init(&event);
event.data = bytes("ready");
event.event_type = bytes("state");
event.id = bytes("1");
event.retry_ms = 1000U;
event.has_event_type = 1U;
event.has_id = 1U;
event.has_retry = 1U;
if (!check(coakka_http_host_write_sse(service_, exchange, &event),
"write SSE event")) {
return false;
}
coakka_http_host_sse_event_init(&event);
event.data = bytes("done");
return check(coakka_http_host_write_sse(service_, exchange, &event),
"write SSE event") &&
check(coakka_http_host_finish_response_stream(service_, exchange,
nullptr, 0U),
"finish SSE");
}
void read_websockets() noexcept {
while (!stopping_.load()) {
coakka_http_host_websocket_event_t event;
coakka_http_host_websocket_event_init(&event);
const auto status =
coakka_http_host_take_websocket(service_, 100U, &event);
if (status == COAKKA_HTTP_HOST_TIMEOUT)
continue;
if (status == COAKKA_HTTP_HOST_CLOSED)
return;
if (!check(status, "take WebSocket event"))
return;
const auto session = event.session;
const bool send_greeting = event.kind == COAKKA_HTTP_HOST_WEBSOCKET_OPEN;
std::string reply;
if (event.kind == COAKKA_HTTP_HOST_WEBSOCKET_TEXT) {
reply = "echo: ";
reply.append(reinterpret_cast<const char *>(event.data.data),
event.data.size);
}
if (!check(coakka_http_host_release_websocket(service_, &event),
"release WebSocket event")) {
return;
}
if (send_greeting) {
(void)check(coakka_http_host_send_websocket(
service_, session, COAKKA_HTTP_HOST_WEBSOCKET_TEXT,
bytes("ready")),
"send WebSocket greeting");
} else if (!reply.empty()) {
(void)check(coakka_http_host_send_websocket(
service_, session, COAKKA_HTTP_HOST_WEBSOCKET_TEXT,
bytes(reply)),
"send WebSocket echo");
}
}
}
coakka_http_host_service_t *service_ = nullptr;
std::uint16_t port_ = 0U;
std::string root_;
std::atomic<bool> stopping_{false};
std::thread websocket_reader_;
};
void request_stop(int) { stop_requested = 1; }
} // namespace
int main() {
std::signal(SIGINT, request_stop);
const auto root =
std::filesystem::temp_directory_path() /
("coakka-http-advanced-" +
std::to_string(
std::chrono::steady_clock::now().time_since_epoch().count()));
std::filesystem::create_directory(root);
std::ofstream(root / "manual.txt", std::ios::binary)
<< "CoAkka file delivery\n";
AdvancedService service;
const bool opened = service.open(root);
if (opened)
service.print_instructions();
const bool served = opened && service.serve_until_signal();
const bool closed = service.close();
std::filesystem::remove_all(root);
return served && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}
cmake --build build --config Release
./build/http-study-advancedTransport details remain owned by CoAkka HTTP Runtime; the samples project only the public ownership contract the application must preserve.
| Task | C ABI 10 | Contract |
|---|---|---|
| Request stream | REQUEST_DATA/TRAILERS/END/CANCELLED | Event order + one reader |
| Response stream | start/write/finish_response_stream | Writability + pressure |
| File | file_authority_t + respond_file | Confined authority |
| SSE | start_sse + write_sse | Finite session |
| WebSocket | accept/take/release/send/close_websocket | Separate reader + frame bounds |
Every successful take creates a lease that must be released. Each lane has exactly one reader; application workers must not call take concurrently as a supposed throughput optimization.
Run HTTP/1.1, HTTP/2 and HTTP/3 on one port in C/C++ →
Find all feature guides · Try gzip · Run the upload labs · Resume a large upload
Advanced · 06
Outbound and live control preserve exact identity
| Task | C ABI 10 | Invariant |
|---|---|---|
| Submit outbound | submit_outbound | A declared logical target produces an exact call identity. |
| Read terminal | take_outbound + release_outbound | HTTP status differs from transport reason/phase/certainty. |
| Rebind handler | route_snapshot + rebind | Expected generation/revision; admitted requests retain the old cut. |
| Publish structure | publish_routes | A complete generation, never a local patch guessed as effective state. |
Advanced · 07
Read effective state; Monitor is opt-in
service_info- Core-accepted listener, protocol and capability facts.
service_limits- Resolved bounded limits, not an echo of zero/default input.
service_health- Direct health without enabling Monitor.
probe_liveness- A fresh bounded probe whose timeout remains distinct.
- Monitor APIs
- Reserve before start, apply by generation, preserve snapshot/page loss and cursor facts; one waiter.
A rejected output is unchanged, not fresh. Serialize every query with destruction; exporter queues, network I/O and retries remain application-owned.
Advanced · 08
Failure, shutdown and C/C++ quick reference
| Status/fact | Meaning | Action |
|---|---|---|
TIMEOUT | A wait/budget ended; the effect may have happened. | Read stage, terminal and idempotency before retry. |
STALE_EXCHANGE | The captured generation no longer accepts completion. | Do not submit a second response. |
CONTROL_UNRESOLVED | No fresh control truth is available yet. | Retry the same activation or destroy; never call a cached cut current. |
Drain PENDING | The caller wait ended; Core has not stopped. | Keep readers/handlers progressing under the outer deadline. |
| Destroy failure | A borrowed lease or lifecycle work retains the owner. | Release, retain the pointer and retry; never free/drop it. |
- Run every public struct through its initializer.
- Match every successful take with its release.
- Use one reader per request/outbound/WebSocket/Monitor lane.
- Branch on typed statuses, never parsed message text.
- Stop does not free; destroy failure does not consume the owner.