Study · C11 + C++20 · CoAkkaHttpHost 2.3.0 · ABI 10
Học CoAkka HTTP Runtime qua public C ABI
Bắt đầu bằng C để thấy rõ owner, event lease và terminal. Sau đó dùng C++ RAII trên đúng ABI đó; không tạo thêm transport, policy hay lifecycle ở wrapper.
Beginner · 01 / 04
Cài SDK trước, cấu hình service sau
Kiểm tra compiler và CMake. SDK phải đúng OS/CPU và giữ nguyên header, library, CMake metadata của cùng artifact 2.3.0.
cmake --version
cc --version
c++ --versionTải archive coakka-http-runtime-native-2.3.0-<target>.tar.gz
và ledger checksum chính thức, kiểm SHA-256 rồi đặt đường dẫn tuyệt
đối tới prefix đã giải nén:
export COAKKA_HTTP_SDK=/absolute/path/to/coakka-http-runtime-native-2.3.0
CoAkkaHttpHost 2.3.0- Package identity dùng cho app-host/event API; đây cũng là package phục vụ Portal.
COAKKA_HTTP_HOST_ABI_VERSION- Public C ABI là
10. Version package, Core generation và ABI là các identity riêng. <coakka/http/host.h>- Header duy nhất của Study này; không trộn callback SDK lịch sử hoặc header từ archive khác.
CoAkkaHttp::host- Imported CMake target mang include path, library và loader contract.
Compiler, SDK và loader chuẩn bị binary. Bind address, route, protocol và limits chỉ được khai báo khi tạo service.
Beginner · 02 / 04
Build và chạy C service đầu tiên
Tạo ba file từ các khối này. CMake khóa package 2.3.0 và bật warnings-as-errors cho source Study.
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-cChương trình in URL effective. Trong terminal khác:
curl -i http://127.0.0.1:49321/hello
HTTP/1.1 200 OK
...
hello native
configuration_init- Đặt
struct_sizevà bounded defaults. Luôn gọi initializer trước khi gán field. port = 0- Mặc định yêu cầu OS chọn port trống; đọc effective port sau start.
route_id- Stable route identity của Core; không phải handler pointer.
handler_binding_id- Connector/app-host dispatch identity. Request đã admit giữ binding revision của nó.
Beginner · 03 / 04
Một reader, một lease, rồi mới response
take_requesttrả một native-owned event lease.request_viewchiếu scalar/count và byte span mượn cùng lease.- Copy mọi byte cần giữ, lưu exact
exchange, rồirelease_request. respondcopy response synchronously; terminal event khép outcome và cũng phải release.
| Giá trị | Owner/lifetime | Sai lầm cần tránh |
|---|---|---|
request_view_t | Không own byte; hết hạn khi release event. | Giữ pointer sang worker khác. |
exchange | Value identity slot + generation. | Match chỉ bằng slot hoặc tự đoán request còn sống. |
| Response body | Borrowed đến hết lời gọi; Core copy khi submit thành công. | Đọc success thành peer đã consume hết byte. |
| Terminal event | Một lease khác; phải release. | Bỏ qua và làm retained state ngăn destroy. |
Beginner · 04 / 04
C++ chỉ bọc owner bằng RAII
Lưu source dưới thành server.cpp. Route, lease và
status vẫn là C ABI; class chỉ cấm copy, giữ pointer owner và buộc
close được kiểm tra.
#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
- Một wrapper không được tạo hai owner cho cùng service.
- Explicit
close() - Main có nơi nhận failure; destructor là last-resort invariant guard.
- Retained owner
destroyfailure giữ pointer non-null để release lease rồi retry; wrapper không được set null giả.- No restart
- Stopped instance không quay lại Started; tạo instance mới.
Advanced · 05
Học từng capability trước khi kết hợp
Native làm ownership tường minh hơn, vì vậy càng cần tách bài. Mỗi file đầu tiên chỉ giữ lane và lifecycle cần cho một capability; bài tích hợp mới ghép chúng lại.
01 · File deliveryAuthority, relative path và limit; CoAkka HTTP Runtime tự chọn sendfile khi đủ điều kiện.
#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, hai event và 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 · WebSocketMột request reader, một WebSocket reader và 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 · Kết hợp trong một serviceBài tích hợp tùy chọn sau khi ba ownership contract đã rõ.
#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-advancedChi tiết transport vẫn thuộc CoAkka HTTP Runtime; sample chỉ chiếu public ownership contract mà application phải giữ.
| 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 |
Mỗi successful take tạo lease phải release. Mỗi lane có đúng một reader; application worker không được gọi take đồng thời để “tăng tốc”.
Chạy HTTP/1.1, HTTP/2 và HTTP/3 cùng cổng bằng C/C++ →
Tra cứu toàn bộ tính năng · Thử gzip · Chạy bài upload · Tiếp tục tải tệp lớn lên
Advanced · 06
Outbound và live control giữ exact identity
| Việc | C ABI 10 | Invariant |
|---|---|---|
| Gửi outbound | submit_outbound | Logical target đã khai báo; nhận exact call identity. |
| Đọc terminal | take_outbound + release_outbound | HTTP status khác transport reason/phase/certainty. |
| Rebind handler | route_snapshot + rebind | Expected generation/revision; admitted request giữ cut cũ. |
| Publish structure | publish_routes | Complete generation; không patch local rồi đoán effective state. |
Advanced · 07
Đọc effective state; Monitor là opt-in
service_info- Listener/protocol/capability facts đã được Core chấp nhận.
service_limits- Resolved bounded limits, không echo zero/default input.
service_health- Direct health; không cần bật Monitor.
probe_liveness- Fresh bounded probe; timeout giữ ý nghĩa riêng.
- Monitor APIs
- Reserve trước start, apply policy theo generation, snapshot/page giữ loss/cursor facts; một waiter.
Output bị từ chối phải được coi là unchanged, không phải fresh. Serialize mọi query với destruction; exporter queue/network/retry vẫn do application sở hữu.
Advanced · 08
Failure, shutdown và C/C++ quick reference
| Status/fact | Ý nghĩa | Hành động |
|---|---|---|
TIMEOUT | Wait/budget kết thúc; effect có thể đã xảy ra. | Đọc stage, terminal và idempotency trước retry. |
STALE_EXCHANGE | Captured generation không còn nhận completion. | Không gửi response lần hai. |
CONTROL_UNRESOLVED | Control observation chưa có fresh truth. | Retry cùng activation hoặc destroy; không dùng cache giả current. |
Drain PENDING | Caller wait kết thúc; Core chưa stop. | Giữ readers/handlers chạy và theo outer deadline. |
| Destroy failure | Borrowed lease hoặc lifecycle work còn giữ owner. | Release, giữ pointer, retry; không free/drop. |
- Mọi public struct đi qua initializer.
- Mọi successful take đi qua matching release.
- Mỗi request/outbound/WebSocket/Monitor lane có một reader.
- Mọi status được branch bằng typed value, không parse message.
- Stop không free; destroy failure không consume owner.