Files
vdm/daemon/tests/uds_roundtrip_test.cpp
T
samiandClaude Sonnet 5 e60d6669d8 daemon: rpc/ — Unix-socket transport + generated dispatch wiring (build step 1)
First real code in daemon/. veloxd now listens on
$XDG_RUNTIME_DIR/velox/velox.sock (0600, SO_PEERCRED same-UID check),
frames NDJSON, and routes every method through the generated
velox::proto::dispatch(). The CLI and GUI have a server to talk to.

Modules:
- rpc/ndjson.hpp    — newline-delimited framing, 8 MiB frame cap, CRLF-
                       tolerant, partial-tail buffering. Header-only, tested.
- rpc/event_loop    — single-threaded poll(2) reactor; never blocks the
                       loop. stop()/wake() are async-signal-safe (eventfd).
- rpc/runtime_dir   — $XDG_RUNTIME_DIR/velox resolution, 0700, owner-checked;
                       refuses an insecure fallback rather than using /tmp.
- rpc/uds_server    — listener + non-blocking per-conn read/write with
                       backpressure; handles session.hello (protocol-major
                       check -> -32001, sessionId, transport=uds) and
                       session.subscribe in the server layer; routes the
                       rest through dispatch().
- rpc/dispatcher    — VeloxDispatcher : proto::Dispatcher, all 39 methods.
                       download.list answers an empty table; the rest return
                       "not implemented" (-> -32603) until the store lands.
- main.cpp          — abstract-namespace single-instance lock, signal ->
                       clean shutdown, socket unlinked on exit.

Tests (ASan+UBSan and TSan clean):
- veloxd.ndjson         — framing edge cases
- veloxd.uds_roundtrip  — real socket: hello ok / version mismatch / empty
                          list / -32601 / -32700 / pipelined requests, and a
                          guard on the -32603 collapse documented in P1.

Known gap, filed not worked around: daemon/docs/proto-requests-m1.md P1 —
the generated Dispatcher has no error channel below -32603, so handlers
cannot yet return -32010/-32011/-32013 with their data payloads. The
server layer handles -32001/-32002/-32003 around dispatch(); genuine
in-handler errors collapse to -32603 until PROTO gives handlers a real
error return. Three error fixtures are non-conformant until then.

Not in this drop: rpc/ws_server (next; needs the store for hashed pairing
tokens), store/, sched/, cli/. WS reuses this event loop.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Upd9WhG9oppieig5nRDLig
2026-09-10 15:27:20 +04:00

196 lines
7.3 KiB
C++

// Integration: a real UdsServer on a temp socket, a real client socket, NDJSON round trips.
// Proves the transport, the generated dispatch() wiring, and the session-layer handling.
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <thread>
#include <nlohmann/json.hpp>
#include "check.hpp"
#include "rpc/dispatcher.hpp"
#include "rpc/event_loop.hpp"
#include "rpc/ndjson.hpp"
#include "rpc/uds_server.hpp"
#include "velox_proto.hpp"
using nlohmann::json;
namespace rpc = velox::daemon::rpc;
namespace {
std::string make_temp_socket_path() {
char tmpl[] = "/tmp/veloxd-test-XXXXXX";
const char* dir = ::mkdtemp(tmpl);
return std::string(dir ? dir : "/tmp") + "/velox.sock";
}
int connect_client(const std::string& path) {
const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
std::memcpy(addr.sun_path, path.c_str(), path.size());
if (::connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
::close(fd);
return -1;
}
return fd;
}
// Send one framed request, read one framed reply (blocking client; the server is async).
json call(int fd, const json& request) {
const std::string out = rpc::frame(request.dump());
if (::write(fd, out.data(), out.size()) != static_cast<ssize_t>(out.size())) return {};
std::string buf;
char chunk[4096];
for (;;) {
const ssize_t n = ::read(fd, chunk, sizeof(chunk));
if (n <= 0) return {};
buf.append(chunk, static_cast<std::size_t>(n));
if (const auto nl = buf.find('\n'); nl != std::string::npos)
return json::parse(buf.substr(0, nl), nullptr, false);
}
}
} // namespace
void run() {
const std::string sock = make_temp_socket_path();
rpc::EventLoop loop;
rpc::VeloxDispatcher dispatcher;
rpc::UdsServer server(loop, dispatcher, sock);
const auto ec = server.start();
CHECK(!ec);
if (ec) return;
std::thread loop_thread([&loop] { loop.run(); });
// --- session.hello, matching major -> a real SessionHelloResult -------------------
{
const int c = connect_client(sock);
CHECK(c >= 0);
const json reply = call(c, {{"jsonrpc", "2.0"},
{"id", 1},
{"method", "session.hello"},
{"params",
{{"clientType", "test"},
{"clientName", "roundtrip"},
{"protocolVersion", std::string(velox::proto::kProtocolVersion)}}}});
CHECK(reply.contains("result"));
CHECK_EQ(reply["id"].get<int>(), 1);
CHECK_EQ(reply["result"]["protocolVersion"].get<std::string>(),
std::string(velox::proto::kProtocolVersion));
CHECK_EQ(reply["result"]["transport"].get<std::string>(), std::string("uds"));
CHECK(!reply["result"]["sessionId"].get<std::string>().empty());
::close(c);
}
// --- session.hello, wrong major -> -32001, connection closed after the reply ------
{
const int c = connect_client(sock);
const json reply = call(c, {{"jsonrpc", "2.0"},
{"id", 2},
{"method", "session.hello"},
{"params",
{{"clientType", "gui"},
{"clientName", "from the future"},
{"protocolVersion", "2.0.0"}}}});
CHECK(reply.contains("error"));
CHECK_EQ(reply["error"]["code"].get<int>(), -32001);
CHECK_EQ(reply["error"]["data"]["actual"].get<std::string>(), std::string("2.0.0"));
::close(c);
}
// --- download.list -> an empty table (dispatcher answers this one for real) -------
{
const int c = connect_client(sock);
const json reply =
call(c, {{"jsonrpc", "2.0"}, {"id", 3}, {"method", "download.list"}, {"params", json::object()}});
CHECK(reply.contains("result"));
CHECK_EQ(reply["result"]["total"].get<int>(), 0);
CHECK(reply["result"]["items"].is_array());
CHECK_EQ(reply["result"]["items"].size(), 0u);
::close(c);
}
// --- an unknown method -> -32601 ------------------------------------------------
{
const int c = connect_client(sock);
const json reply =
call(c, {{"jsonrpc", "2.0"}, {"id", 4}, {"method", "no.such.method"}, {"params", json::object()}});
CHECK(reply.contains("error"));
CHECK_EQ(reply["error"]["code"].get<int>(), -32601);
::close(c);
}
// --- malformed JSON -> -32700, id null ----------------------------------------
{
const int c = connect_client(sock);
const std::string bad = "{ this is not json )\n";
CHECK(::write(c, bad.data(), bad.size()) == static_cast<ssize_t>(bad.size()));
std::string buf;
char chunk[1024];
const ssize_t n = ::read(c, chunk, sizeof(chunk));
CHECK(n > 0);
if (n > 0) {
buf.assign(chunk, static_cast<std::size_t>(n));
const json reply = json::parse(buf.substr(0, buf.find('\n')), nullptr, false);
CHECK_EQ(reply["error"]["code"].get<int>(), -32700);
CHECK(reply["id"].is_null());
}
::close(c);
}
// --- download.get -> -32603 for now: documents the P1 codegen gap ---------------
// (proto-requests-m1.md P1: handlers cannot yet return -32010. When P1 lands this
// check flips to -32010 and is the regression guard for it.)
{
const int c = connect_client(sock);
const json reply = call(c, {{"jsonrpc", "2.0"},
{"id", 6},
{"method", "download.get"},
{"params", {{"taskId", "00000000-0000-4000-8000-000000000000"}}}});
CHECK(reply.contains("error"));
CHECK_EQ(reply["error"]["code"].get<int>(), -32603);
::close(c);
}
// --- two requests in one write, pipelined on one connection --------------------
{
const int c = connect_client(sock);
std::string out = rpc::frame(json({{"jsonrpc", "2.0"}, {"id", 7}, {"method", "download.list"}, {"params", json::object()}}).dump());
out += rpc::frame(json({{"jsonrpc", "2.0"}, {"id", 8}, {"method", "download.list"}, {"params", json::object()}}).dump());
CHECK(::write(c, out.data(), out.size()) == static_cast<ssize_t>(out.size()));
std::string buf;
char chunk[4096];
int seen = 0;
while (seen < 2) {
const ssize_t n = ::read(c, chunk, sizeof(chunk));
if (n <= 0) break;
buf.append(chunk, static_cast<std::size_t>(n));
std::size_t nl;
while ((nl = buf.find('\n')) != std::string::npos) {
const json reply = json::parse(buf.substr(0, nl), nullptr, false);
CHECK(reply.contains("result"));
++seen;
buf.erase(0, nl + 1);
}
}
CHECK_EQ(seen, 2);
::close(c);
}
loop.stop();
loop_thread.join();
::unlink(sock.c_str());
}
TEST_MAIN()