http_listener.cpp

src/facade/http_listener.cpp

@file http_listener.cpp @brief Streamable-HTTP front end for the external bridge (gh#204).

Owners: @tvanfossen

await_running

std::string entropic::http::HttpListener::await_running()

Return only once the server is accepting, or say why not.

src/facade/http_listener.cpp:531

Show on the map →

Called by start

Calls none

Source · 8 lines
std::string HttpListener::await_running() {
    for (int i = 0; i < 5000; ++i) {
        if (impl_->server.is_running() || impl_->listen_returned) { break; }
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    return impl_->server.is_running() ? std::string{}
                                      : std::string("listener did not start");
}
Activity · 5 steps
lines 532–532◇ for (int i = 0; i < 5000; ++i)lines 533–533◇ if (impl_->server.is_running() || impl_->listen_returned)lines 533–533break;lines 534–534std::this_thread::sleep_for(std::chrono::milliseconds(1));lines 536–537return impl_->server.is_running() ? std::string{} : std::string("listener did not start");

Requirements

REQ-BRIDGE-001

bind_loopback

static int entropic::http::bind_loopback(httplib::Server &server, int port)

Bind 127.0.0.1 on port , or on any free port when it is 0.

src/facade/http_listener.cpp:456

Show on the map →

Called by start

Calls none

Source · 8 lines
static int bind_loopback(httplib::Server& server, int port) {
    server.set_socket_options([](socket_t sock) {
        int one = 1;
        ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    });
    return port == 0 ? server.bind_to_any_port("127.0.0.1")
                     : (server.bind_to_port("127.0.0.1", port) ? port : -1);
}
Activity · 2 steps
lines 457–460server.set_socket_options([](socket_t sock) { int one = 1; ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); });lines 461–462return port == 0 ? server.bind_to_any_port("127.0.0.1") : (server.bind_to_port("127.0.0.1", port) ? port : -1);

Requirements

REQ-BRIDGE-001

blocked

bool entropic::http::AuthThrottle::blocked(Clock::time_point now) const

Whether requests are refused at now .

src/facade/http_listener.cpp:197

Show on the map →

Called by SCENARIO, refusal_status

Calls none

Source · 4 lines
bool AuthThrottle::blocked(Clock::time_point now) const {
    std::lock_guard<std::mutex> lock(mu_);
    return now < blocked_until_;
}
Activity · 2 steps
lines 198–198std::lock_guard<std::mutex> lock(mu_);lines 199–199return now < blocked_until_;

Requirements

REQ-BRIDGE-001

configure_server

static void entropic::http::configure_server(HttpListener::Impl &impl, ExternalBridge *bridge, const std::atomic< int > &port)

Install routes, limits and the worker pool on the server.

src/facade/http_listener.cpp:417

Show on the map →

Called by start

Calls error_body, handle_post, refusal_status

Source · 23 lines
static void configure_server(HttpListener::Impl& impl, ExternalBridge* bridge,
                             const std::atomic<int>& port) {
    auto& s = impl.server;
    s.set_payload_max_length(kMaxBodyBytes);
    s.set_read_timeout(30, 0);
    s.set_write_timeout(30, 0);
    s.new_task_queue = [] { return new httplib::ThreadPool(32); };
    s.Post("/mcp", [&impl, bridge, &port](const httplib::Request& req,
                                          httplib::Response& res) {
        const int refuse = refusal_status(req, port.load(), impl);
        if (refuse != 0) {
            res.status = refuse;
            res.set_content(error_body("refused"), "application/json");
            return;
        }
        handle_post(bridge, req, res);
    });
    auto not_allowed = [](const httplib::Request&, httplib::Response& res) {
        res.status = 405;  // no server-initiated stream, no transport session
    };
    s.Get("/mcp", not_allowed);
    s.Delete("/mcp", not_allowed);
}
Activity · 9 steps
lines 419–419auto& s = impl.server;lines 420–420s.set_payload_max_length(kMaxBodyBytes);lines 421–421s.set_read_timeout(30, 0);lines 422–422s.set_write_timeout(30, 0);lines 423–423s.new_task_queue = [] { return new httplib::ThreadPool(32); };lines 424–433s.Post("/mcp", [&impl, bridge, &port](const httplib::Request& req, httplib::Response& res) { const int refuse = refusal_status(req, port.load(), impl); if (refuse != 0) { res.status = refuse; res.set_content(error_body("refused"), "application/json"); return; } handle_post(bridge, req, res); });lines 434–436auto not_allowed = [](const httplib::Request&, httplib::Response& res) { res.status = 405; // no server-initiated stream, no transport session };lines 437–437s.Get("/mcp", not_allowed);lines 438–438s.Delete("/mcp", not_allowed);

Requirements

REQ-BRIDGE-001

publish_token

std::string entropic::http::HttpListener::publish_token(int bound)

Generate this run's token and write it where clients read it.

src/facade/http_listener.cpp:472

Show on the map →

Called by start

Calls generate_token, prepare_private_dir, token_path_for, write_token_file

Source · 13 lines
std::string HttpListener::publish_token(int bound) {
    std::string err;
    impl_->token = generate_token();
    if (impl_->token.empty()) {
        err = "no entropy for the bearer token";
    } else {
        token_file_ = token_path_for(bound);
        if (prepare_private_dir(token_file_.parent_path(), err)) {
            write_token_file(token_file_, impl_->token, err);
        }
    }
    return err;
}
Activity · 9 steps
lines 473–473std::string err;lines 474–474impl_->token = generate_token();lines 475–475◇ if (impl_->token.empty())lines 476–476err = "no entropy for the bearer token";lines 477–477elselines 478–478token_file_ = token_path_for(bound);lines 479–479◇ if (prepare_private_dir(token_file_.parent_path(), err))lines 480–480write_token_file(token_file_, impl_->token, err);lines 483–483return err;

Requirements

REQ-BRIDGE-001

record_failure

void entropic::http::AuthThrottle::record_failure(Clock::time_point now)

Record one failed authentication at now .

src/facade/http_listener.cpp:208

Show on the map →

Called by SCENARIO, refusal_status

Calls none

Source · 11 lines
void AuthThrottle::record_failure(Clock::time_point now) {
    std::lock_guard<std::mutex> lock(mu_);
    if (now - window_start_ > kThrottleWindow) {
        window_start_ = now;
        failures_ = 0;
    }
    if (++failures_ >= kThrottleFailures) {
        blocked_until_ = now + kThrottleBlock;
        failures_ = 0;
    }
}
Activity · 7 steps
lines 209–209std::lock_guard<std::mutex> lock(mu_);lines 210–210◇ if (now - window_start_ > kThrottleWindow)lines 211–211window_start_ = now;lines 212–212failures_ = 0;lines 214–214◇ if (++failures_ >= kThrottleFailures)lines 215–215blocked_until_ = now + kThrottleBlock;lines 216–216failures_ = 0;

Requirements

REQ-BRIDGE-001

start

bool entropic::http::HttpListener::start(std::string &err)

Write the token, bind, and start serving.

src/facade/http_listener.cpp:493

Source · 22 lines
bool HttpListener::start(std::string& err) {
    configure_server(*impl_, bridge_, port_);
    const int bound = bind_loopback(impl_->server, port_.load());
    if (bound <= 0) {
        err = "cannot bind 127.0.0.1:" + std::to_string(port_.load());
    } else {
        port_ = bound;
        err = publish_token(bound);
    }
    if (err.empty()) {
        thread_ = std::thread([this] {
            impl_->server.listen_after_bind();
            impl_->listen_returned = true;
        });
        err = await_running();
    }
    if (err.empty()) {
        logger->info("[http] serving MCP at http://127.0.0.1:{}/mcp "
                     "(token: {})", bound, token_file_.string());
    }
    return err.empty();
}
Activity · 13 steps
lines 494–494configure_server(*impl_, bridge_, port_);lines 495–495const int bound = bind_loopback(impl_->server, port_.load());lines 496–496◇ if (bound <= 0)lines 497–497err = "cannot bind 127.0.0.1:" + std::to_string(port_.load());lines 498–498elselines 499–499port_ = bound;lines 500–500err = publish_token(bound);lines 502–502◇ if (err.empty())lines 503–506thread_ = std::thread([this] { impl_->server.listen_after_bind(); impl_->listen_returned = true; });lines 507–507err = await_running();lines 509–509◇ if (err.empty())lines 510–511logger->info("[http] serving MCP at http://127.0.0.1:{}/mcp " "(token: {})", bound, token_file_.string());lines 513–513return err.empty();

Requirements

REQ-BRIDGE-001

stop

void entropic::http::HttpListener::stop()

Stop serving and remove the token file.

src/facade/http_listener.cpp:545

Show on the map →

Called by SCENARIO, TEST_CASE, ~HttpListener

Calls none

Source · 9 lines
void HttpListener::stop() {
    impl_->server.stop();
    if (thread_.joinable()) { thread_.join(); }
    if (!token_file_.empty()) {
        std::error_code ec;
        std::filesystem::remove(token_file_, ec);
        token_file_.clear();
    }
}
Activity · 7 steps
lines 546–546impl_->server.stop();lines 547–547◇ if (thread_.joinable())lines 547–547thread_.join();lines 548–548◇ if (!token_file_.empty())lines 549–549std::error_code ec;lines 550–550std::filesystem::remove(token_file_, ec);lines 551–551token_file_.clear();

Requirements

REQ-BRIDGE-001

~HttpListener

entropic::http::HttpListener::~HttpListener()

Stops the server and removes the token file.

src/facade/http_listener.cpp:407

Show on the map →

Called by none

Calls stop

The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.

Requirements

REQ-BRIDGE-001

~SseJob

entropic::http::anonymous_namespace{http_listener.cpp}::SseJob::~SseJob()

Join the dispatching thread, then close our end of the pipe.

src/facade/http_listener.cpp:252

Show on the map →

Called by none

Calls none

The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.

Requirements

REQ-BRIDGE-001