feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security, data, app, realtime, supervisor, clients, CLI, example plus enterprise tenancy, audit, operability, governance, supplychain. Postgres via docker compose for tests.
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
// Route: /dav/*. Full litmus-style sequence: MKCOL, PUT, GET,
|
||||
// PROPFIND depths, PROPPATCH, COPY/MOVE, LOCK/UNLOCK, quota 507,
|
||||
// client streaming GET with ETag cache.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_main.h"
|
||||
#include "realtime/shared/http_seam.h"
|
||||
#include "realtime/webdav/client/webdav_client.h"
|
||||
#include "realtime/webdav/server/dav_view.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
namespace {
|
||||
|
||||
shared::HttpRequest dav_req(const std::string& method, const std::string& path,
|
||||
const std::string& body = "") {
|
||||
shared::HttpRequest req;
|
||||
req.method = method;
|
||||
req.path = path;
|
||||
req.body = body;
|
||||
return req;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
webdav::server::DavView dav("/dav");
|
||||
|
||||
// OPTIONS advertises DAV: 1.
|
||||
{
|
||||
auto res = dav.dispatch(dav_req("OPTIONS", "/dav"));
|
||||
T_CHECK(r, res.status == 200);
|
||||
T_CHECK(r, shared::header_first(res, "DAV") == "1");
|
||||
}
|
||||
|
||||
// MKCOL then PUT then GET.
|
||||
T_CHECK(r, dav.dispatch(dav_req("MKCOL", "/dav/docs")).status == 201);
|
||||
T_CHECK(r, dav.dispatch(dav_req("MKCOL", "/dav/docs")).status == 405);
|
||||
T_CHECK(r, dav.dispatch(dav_req("MKCOL", "/dav/no/file")).status == 409);
|
||||
{
|
||||
auto res = dav.dispatch(dav_req("PUT", "/dav/docs/a.txt", "hello dav"));
|
||||
T_CHECK(r, res.status == 201);
|
||||
auto get = dav.dispatch(dav_req("GET", "/dav/docs/a.txt"));
|
||||
T_CHECK(r, get.status == 200 && get.body == "hello dav");
|
||||
T_CHECK(r, !shared::header_first(get, "ETag").empty());
|
||||
// Conditional GET: 304.
|
||||
auto cond = dav_req("GET", "/dav/docs/a.txt");
|
||||
cond.headers.emplace("If-None-Match",
|
||||
shared::header_first(get, "ETag"));
|
||||
T_CHECK(r, dav.dispatch(cond).status == 304);
|
||||
// Range GET: 206 with Content-Range.
|
||||
auto rng = dav_req("GET", "/dav/docs/a.txt");
|
||||
rng.headers.emplace("Range", "bytes=0-4");
|
||||
auto r206 = dav.dispatch(rng);
|
||||
T_CHECK(r, r206.status == 206 && r206.body == "hello");
|
||||
auto bad = dav_req("GET", "/dav/docs/a.txt");
|
||||
bad.headers.emplace("Range", "bytes=99-");
|
||||
T_CHECK(r, dav.dispatch(bad).status == 416);
|
||||
}
|
||||
|
||||
// PROPFIND depth 1 lists the collection plus child.
|
||||
{
|
||||
auto req = dav_req("PROPFIND", "/dav/docs");
|
||||
req.headers.emplace("Depth", "1");
|
||||
auto res = dav.dispatch(req);
|
||||
T_CHECK(r, res.status == 207);
|
||||
T_CHECK(r, res.body.find("/dav/docs/a.txt") != std::string::npos);
|
||||
auto entries = webdav::client::WebDavClient::parse_propfind(res.body);
|
||||
T_CHECK(r, entries.size() == 2);
|
||||
}
|
||||
// Depth infinity is capped, still 207.
|
||||
{
|
||||
auto req = dav_req("PROPFIND", "/dav");
|
||||
req.headers.emplace("Depth", "infinity");
|
||||
T_CHECK(r, dav.dispatch(req).status == 207);
|
||||
auto bad = dav_req("PROPFIND", "/dav");
|
||||
bad.headers.emplace("Depth", "2");
|
||||
T_CHECK(r, dav.dispatch(bad).status == 400);
|
||||
}
|
||||
|
||||
// PROPPATCH sets a dead property, readable via prop selection.
|
||||
{
|
||||
auto req = dav_req("PROPPATCH", "/dav/docs/a.txt",
|
||||
"<D:propertyupdate xmlns:D=\"DAV:\">"
|
||||
"<D:set><D:prop><D:author>ada</D:author></D:prop>"
|
||||
"</D:set></D:propertyupdate>");
|
||||
T_CHECK(r, dav.dispatch(req).status == 207);
|
||||
}
|
||||
|
||||
// COPY then MOVE with Overwrite handling.
|
||||
{
|
||||
auto copy = dav_req("COPY", "/dav/docs/a.txt");
|
||||
copy.headers.emplace("Destination", "/dav/docs/b.txt");
|
||||
T_CHECK(r, dav.dispatch(copy).status == 201);
|
||||
auto copy2 = dav_req("COPY", "/dav/docs/a.txt");
|
||||
copy2.headers.emplace("Destination", "/dav/docs/b.txt");
|
||||
copy2.headers.emplace("Overwrite", "F");
|
||||
T_CHECK(r, dav.dispatch(copy2).status == 412);
|
||||
auto move = dav_req("MOVE", "/dav/docs/b.txt");
|
||||
move.headers.emplace("Destination", "/dav/docs/c.txt");
|
||||
T_CHECK(r, dav.dispatch(move).status == 201);
|
||||
T_CHECK(r, dav.dispatch(dav_req("GET", "/dav/docs/b.txt")).status == 404);
|
||||
T_CHECK(r, dav.dispatch(dav_req("GET", "/dav/docs/c.txt")).status == 200);
|
||||
}
|
||||
|
||||
// LOCK writes, COPY without token is 423, UNLOCK releases.
|
||||
{
|
||||
auto lock = dav_req("LOCK", "/dav/docs/c.txt",
|
||||
"<D:lockinfo xmlns:D=\"DAV:\">"
|
||||
"<D:lockscope><D:exclusive/></D:lockscope>"
|
||||
"<D:locktype><D:write/></D:locktype>"
|
||||
"<D:owner>tester</D:owner></D:lockinfo>");
|
||||
lock.headers.emplace("Timeout", "Second-60");
|
||||
auto locked = dav.dispatch(lock);
|
||||
T_CHECK(r, locked.status == 200);
|
||||
std::string token = shared::header_first(locked, "Lock-Token");
|
||||
T_CHECK(r, !token.empty());
|
||||
auto copy = dav_req("COPY", "/dav/docs/c.txt");
|
||||
copy.headers.emplace("Destination", "/dav/docs/d.txt");
|
||||
T_CHECK(r, dav.dispatch(copy).status == 423);
|
||||
auto unlock = dav_req("UNLOCK", "/dav/docs/c.txt");
|
||||
unlock.headers.emplace("Lock-Token", token);
|
||||
T_CHECK(r, dav.dispatch(unlock).status == 204);
|
||||
T_CHECK(r, dav.dispatch(copy).status == 201);
|
||||
}
|
||||
|
||||
// DELETE removes; non-empty collection delete fails.
|
||||
{
|
||||
T_CHECK(r,
|
||||
dav.dispatch(dav_req("DELETE", "/dav/docs/c.txt")).status == 204);
|
||||
T_CHECK(r, dav.dispatch(dav_req("DELETE", "/dav/docs")).status == 409);
|
||||
}
|
||||
|
||||
// Path escape fails closed.
|
||||
T_CHECK(r, dav.dispatch(dav_req("GET", "/dav/../etc/passwd")).status == 404);
|
||||
|
||||
// Quota exceeded is 507.
|
||||
{
|
||||
webdav::server::DavConfig cfg;
|
||||
cfg.quota_bytes = 8;
|
||||
webdav::server::DavView small("/dav", cfg);
|
||||
T_CHECK(r, small.dispatch(dav_req("MKCOL", "/dav/d")).status == 201);
|
||||
auto res = small.dispatch(dav_req("PUT", "/dav/d/big", "0123456789"));
|
||||
T_CHECK(r, res.status == 507);
|
||||
}
|
||||
|
||||
// Client: streaming GET with ETag cache and quota hook.
|
||||
{
|
||||
webdav::client::WebDavClient client;
|
||||
std::size_t quota_down = 0;
|
||||
client.set_quota_hook(
|
||||
[&](const std::string& dir, std::size_t n) {
|
||||
if (dir == "down") {
|
||||
quota_down += n;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
auto req = client.get("/dav/docs/a.txt");
|
||||
auto res = dav.dispatch(req);
|
||||
std::string streamed;
|
||||
auto got = client.on_get_response(req, res,
|
||||
[&](const uint8_t* data, std::size_t n) {
|
||||
streamed.append(
|
||||
reinterpret_cast<const char*>(data),
|
||||
n);
|
||||
return true;
|
||||
});
|
||||
T_CHECK(r, got.ok && !got.cached && streamed == "hello dav");
|
||||
T_CHECK(r, quota_down == streamed.size());
|
||||
T_CHECK(r, client.cache_entries() == 1);
|
||||
// Second GET is conditional and hits the cache.
|
||||
auto req2 = client.get("/dav/docs/a.txt");
|
||||
T_CHECK(r,
|
||||
!shared::header_first(req2, "If-None-Match").empty());
|
||||
auto res2 = dav.dispatch(req2);
|
||||
auto got2 = client.on_get_response(
|
||||
req2, res2, [&](const uint8_t*, std::size_t) { return true; });
|
||||
T_CHECK(r, got2.ok && got2.cached);
|
||||
}
|
||||
|
||||
return r.report("dav/files");
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Route: /engine.io/. Open handshake shape, polling framing,
|
||||
// upgrade probe sequence, duplicate GET rejection, unknown sid.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_main.h"
|
||||
#include "realtime/engineio/heartbeat_scheduler.h"
|
||||
#include "realtime/engineio/packet_codec.h"
|
||||
#include "realtime/engineio/polling_transport.h"
|
||||
#include "realtime/engineio/upgrade_manager.h"
|
||||
#include "realtime/engineio/websocket_transport.h"
|
||||
#include "realtime/shared/mini_json.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
using engineio::EnginePacket;
|
||||
using engineio::EnginePacketType;
|
||||
using engineio::EngineSession;
|
||||
using engineio::PacketCodec;
|
||||
|
||||
// Single packet round-trips for all 7 types.
|
||||
for (int t = 0; t <= 6; ++t) {
|
||||
EnginePacket p;
|
||||
p.type = static_cast<EnginePacketType>(t);
|
||||
p.data = t == 4 ? "hello" : "";
|
||||
auto wire = PacketCodec::encode(p);
|
||||
T_CHECK(r, wire[0] == '0' + t);
|
||||
auto back = PacketCodec::decode(wire);
|
||||
T_CHECK(r, back.has_value() && back->type == p.type &&
|
||||
back->data == p.data);
|
||||
}
|
||||
T_CHECK(r, !PacketCodec::decode("").has_value());
|
||||
T_CHECK(r, !PacketCodec::decode("7x").has_value());
|
||||
|
||||
// Polling payload framing round-trips; errors fail clean.
|
||||
{
|
||||
EnginePacket a, b;
|
||||
a.type = EnginePacketType::kMessage;
|
||||
a.data = "hi";
|
||||
b.type = EnginePacketType::kNoop;
|
||||
std::string payload = PacketCodec::encode_polling({a, b});
|
||||
T_CHECK(r, payload == "3:4hi1:6");
|
||||
auto back = PacketCodec::decode_polling(payload);
|
||||
T_CHECK(r, back.has_value() && back->size() == 2);
|
||||
T_CHECK(r, (*back)[0].data == "hi");
|
||||
T_CHECK(r, !PacketCodec::decode_polling("9:4hi").has_value());
|
||||
T_CHECK(r, !PacketCodec::decode_polling("xx").has_value());
|
||||
}
|
||||
|
||||
// Open packet JSON has exactly the spec keys.
|
||||
{
|
||||
shared::ConnectionContext ctx;
|
||||
EngineSession session(ctx);
|
||||
T_CHECK(r, !session.sid().empty());
|
||||
EnginePacket open = session.open_packet();
|
||||
T_CHECK(r, open.type == EnginePacketType::kOpen);
|
||||
auto json = shared::Json::parse(open.data);
|
||||
T_CHECK(r, json.has_value());
|
||||
T_CHECK(r, json->find("sid") != nullptr);
|
||||
T_CHECK(r, json->find("upgrades") != nullptr);
|
||||
T_CHECK(r, json->find("pingInterval") != nullptr);
|
||||
T_CHECK(r, json->find("pingTimeout") != nullptr);
|
||||
T_CHECK(r, json->find("maxPayload") != nullptr);
|
||||
}
|
||||
|
||||
// Polling GET drains queued packets; empty holds; dup GET is 400.
|
||||
{
|
||||
shared::ConnectionContext ctx;
|
||||
EngineSession session(ctx);
|
||||
engineio::PollingTransport polling;
|
||||
bool hold = false;
|
||||
auto held = polling.answer_get(session, hold);
|
||||
(void)held;
|
||||
T_CHECK(r, hold);
|
||||
bool hold2 = false;
|
||||
auto dup = polling.answer_get(session, hold2);
|
||||
T_CHECK(r, dup.status == 400);
|
||||
EnginePacket m;
|
||||
m.type = EnginePacketType::kMessage;
|
||||
m.data = "4hi";
|
||||
session.enqueue(m);
|
||||
auto flushed = polling.flush_held(session);
|
||||
T_CHECK(r, flushed.status == 200);
|
||||
T_CHECK(r, flushed.body == "4:44hi");
|
||||
T_CHECK(r, engineio::PollingTransport::unknown_sid().status == 400);
|
||||
}
|
||||
|
||||
// POST bodies decode; oversized is 400.
|
||||
{
|
||||
shared::ConnectionContext ctx;
|
||||
EngineSession session(ctx);
|
||||
engineio::PollingTransport polling;
|
||||
shared::HttpRequest req;
|
||||
req.method = "POST";
|
||||
req.body = "3:4hi";
|
||||
auto res = polling.accept_post(session, req);
|
||||
T_CHECK(r, res.ok && res.packets.size() == 1);
|
||||
req.body = "bogus";
|
||||
T_CHECK(r, !polling.accept_post(session, req).ok);
|
||||
}
|
||||
|
||||
// WebSocket transport admit checks EIO/transport/sid.
|
||||
{
|
||||
shared::HttpRequest req;
|
||||
req.query = "EIO=4&transport=websocket&sid=abc";
|
||||
T_CHECK(r, engineio::WebSocketTransport::admit(req, true).ok);
|
||||
T_CHECK(r, !engineio::WebSocketTransport::admit(req, false).ok);
|
||||
req.query = "EIO=3&transport=websocket";
|
||||
T_CHECK(r, !engineio::WebSocketTransport::admit(req, true).ok);
|
||||
}
|
||||
|
||||
// Upgrade probe: 2probe -> 3probe, 5 upgrades.
|
||||
{
|
||||
shared::ConnectionContext ctx;
|
||||
EngineSession session(ctx);
|
||||
engineio::UpgradeManager up;
|
||||
EnginePacket probe;
|
||||
probe.type = EnginePacketType::kPing;
|
||||
probe.data = "probe";
|
||||
auto answer = up.on_packet(session, probe);
|
||||
T_CHECK(r, answer.has_value() && *answer == "3probe");
|
||||
T_CHECK(r, !up.upgraded());
|
||||
EnginePacket fin;
|
||||
fin.type = EnginePacketType::kUpgrade;
|
||||
auto consumed = up.on_packet(session, fin);
|
||||
T_CHECK(r, consumed.has_value() && consumed->empty());
|
||||
T_CHECK(r, up.upgraded() && session.upgraded());
|
||||
EnginePacket other;
|
||||
other.type = EnginePacketType::kMessage;
|
||||
other.data = "x";
|
||||
T_CHECK(r, !up.on_packet(session, other).has_value());
|
||||
}
|
||||
|
||||
// Heartbeat pings on interval, closes on silence.
|
||||
{
|
||||
shared::ConnectionContext ctx;
|
||||
engineio::EngineConfig cfg;
|
||||
cfg.ping_interval = std::chrono::milliseconds(25);
|
||||
cfg.ping_timeout = std::chrono::milliseconds(100);
|
||||
EngineSession session(ctx, cfg);
|
||||
engineio::HeartbeatScheduler hb(&session);
|
||||
int pings = 0;
|
||||
bool dead = false;
|
||||
hb.on_send([&](const EnginePacket&) { ++pings; });
|
||||
hb.on_timeout([&] { dead = true; });
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
hb.start(t0);
|
||||
session.note_activity(t0);
|
||||
hb.tick(t0 + session.config().ping_interval);
|
||||
T_CHECK(r, pings == 1 && !dead);
|
||||
hb.tick(t0 + session.config().ping_interval +
|
||||
session.config().ping_timeout);
|
||||
T_CHECK(r, dead && session.closed());
|
||||
}
|
||||
|
||||
return r.report("engineio/handshake");
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// Shared foundations: base64/SHA-1 vectors, UTF-8, send-queue shed
|
||||
// policies, jittered backoff bounds, valve watermarks, JSON codec,
|
||||
// metrics names, auth headers.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_main.h"
|
||||
#include "realtime/shared/backpressure_valve.h"
|
||||
#include "realtime/shared/base64.h"
|
||||
#include "realtime/shared/base_realtime_client.h"
|
||||
#include "realtime/shared/mini_json.h"
|
||||
#include "realtime/shared/realtime_metrics.h"
|
||||
#include "realtime/shared/reconnect_policy.h"
|
||||
#include "realtime/shared/send_queue.h"
|
||||
#include "realtime/shared/sha1.h"
|
||||
#include "realtime/shared/utf8.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
|
||||
// SHA-1 golden vector ("abc").
|
||||
{
|
||||
auto d = shared::Sha1::hash("abc");
|
||||
std::string hex;
|
||||
for (uint8_t b : d) {
|
||||
char buf[3];
|
||||
std::snprintf(buf, sizeof(buf), "%02x", b);
|
||||
hex += buf;
|
||||
}
|
||||
T_CHECK(r, hex == "a9993e364706816aba3e25717850c26c9cd0d89d");
|
||||
}
|
||||
// Base64 round-trip plus rejection.
|
||||
{
|
||||
T_CHECK(r, shared::base64_encode("Man") == "TWFu");
|
||||
T_CHECK(r, shared::base64_encode("Ma") == "TWE=");
|
||||
auto dec = shared::base64_decode("TWFu");
|
||||
T_CHECK(r, dec.has_value() &&
|
||||
std::string(dec->begin(), dec->end()) == "Man");
|
||||
T_CHECK(r, !shared::base64_decode("!!!").has_value());
|
||||
T_CHECK(r, !shared::base64_decode("abc").has_value());
|
||||
}
|
||||
// UTF-8 strictness.
|
||||
{
|
||||
T_CHECK(r, shared::is_valid_utf8("hello"));
|
||||
T_CHECK(r, shared::is_valid_utf8("\xc3\xa9")); // e-acute.
|
||||
T_CHECK(r, !shared::is_valid_utf8("\xc3\x28"));
|
||||
T_CHECK(r, !shared::is_valid_utf8("\xed\xa0\x80")); // Surrogate.
|
||||
T_CHECK(r, !shared::is_valid_utf8("\xf0\x82\x82\xac")); // Overlong.
|
||||
}
|
||||
|
||||
// Send queue shed policies.
|
||||
{
|
||||
shared::SendQueue q(2, shared::ShedPolicy::kDropOldest);
|
||||
shared::SendItem a, b, c;
|
||||
a.bytes = {'a'};
|
||||
b.bytes = {'b'};
|
||||
c.bytes = {'c'};
|
||||
T_CHECK(r, q.push(a) && q.push(b) && q.push(c));
|
||||
T_CHECK(r, q.shed_count() == 1);
|
||||
shared::SendItem out;
|
||||
T_CHECK(r, q.pop(out) && out.bytes[0] == 'b');
|
||||
}
|
||||
{
|
||||
shared::SendQueue q(1, shared::ShedPolicy::kDropNewest);
|
||||
shared::SendItem a, b;
|
||||
a.bytes = {'a'};
|
||||
b.bytes = {'b'};
|
||||
T_CHECK(r, q.push(a));
|
||||
T_CHECK(r, !q.push(b));
|
||||
T_CHECK(r, q.shed_count() == 1);
|
||||
}
|
||||
{
|
||||
shared::SendQueue q(1, shared::ShedPolicy::kClose);
|
||||
shared::SendItem a, b;
|
||||
a.bytes = {'a'};
|
||||
b.bytes = {'b'};
|
||||
T_CHECK(r, q.push(a));
|
||||
T_CHECK(r, !q.push(b));
|
||||
T_CHECK(r, q.must_close());
|
||||
}
|
||||
|
||||
// Backoff bounds double then cap; jitter stays inside.
|
||||
{
|
||||
shared::ReconnectPolicy p(std::chrono::milliseconds(100),
|
||||
std::chrono::milliseconds(1000), 10);
|
||||
T_CHECK(r, p.bound_for(0) == std::chrono::milliseconds(100));
|
||||
T_CHECK(r, p.bound_for(1) == std::chrono::milliseconds(200));
|
||||
T_CHECK(r, p.bound_for(9) == std::chrono::milliseconds(1000));
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
auto d = p.delay_for(2);
|
||||
T_CHECK(r, d >= std::chrono::milliseconds(0) &&
|
||||
d <= std::chrono::milliseconds(400));
|
||||
}
|
||||
}
|
||||
|
||||
// Valve pauses at high, resumes at low.
|
||||
{
|
||||
shared::BackpressureValve v(10, 100);
|
||||
v.note_buffered(50);
|
||||
T_CHECK(r, !v.paused());
|
||||
v.note_buffered(60);
|
||||
T_CHECK(r, v.paused());
|
||||
v.note_flushed(50);
|
||||
T_CHECK(r, v.paused()); // Still above low.
|
||||
v.note_flushed(55);
|
||||
T_CHECK(r, !v.paused());
|
||||
}
|
||||
|
||||
// JSON round-trip and rejection.
|
||||
{
|
||||
auto v = shared::Json::parse("{\"a\":[1,true,\"x\"],\"b\":null}");
|
||||
T_CHECK(r, v.has_value());
|
||||
T_CHECK(r, v->find("a")->array()[1].boolean());
|
||||
T_CHECK(r, v->dump() == "{\"a\":[1,true,\"x\"],\"b\":null}");
|
||||
T_CHECK(r, !shared::Json::parse("{oops").has_value());
|
||||
T_CHECK(r, !shared::Json::parse("[1,]").has_value());
|
||||
}
|
||||
|
||||
// Metrics count and reset.
|
||||
{
|
||||
auto& m = shared::RealtimeMetrics::instance();
|
||||
m.reset_all();
|
||||
m.inc(shared::RealtimeMetric::kMessagesSent, 3);
|
||||
T_CHECK(r, m.get(shared::RealtimeMetric::kMessagesSent) == 3);
|
||||
T_CHECK(r, std::string(shared::metric_name(
|
||||
shared::RealtimeMetric::kMessagesSent)) ==
|
||||
"molo_realtime_messages_sent");
|
||||
}
|
||||
|
||||
// Client auth headers: exactly one scheme at a time.
|
||||
{
|
||||
shared::ClientAuth anon;
|
||||
T_CHECK(r, anon.anonymous() && anon.headers().empty());
|
||||
shared::ClientAuth bearer;
|
||||
bearer.bearer_token = "tok";
|
||||
auto h = bearer.headers();
|
||||
T_CHECK(r, h.size() == 1 && h[0].second == "Bearer tok");
|
||||
shared::ClientAuth basic;
|
||||
basic.basic_user = "u";
|
||||
basic.basic_password = "p";
|
||||
auto h2 = basic.headers();
|
||||
T_CHECK(r, h2.size() == 1 && h2[0].second == "Basic dTpw");
|
||||
}
|
||||
|
||||
return r.report("shared/foundation");
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Parser robustness: deterministic garbage into every byte-level
|
||||
// parser must fail clean, never crash or hang. Fixed seed, bounded
|
||||
// iterations, small inputs.
|
||||
|
||||
#include <cstdint>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_main.h"
|
||||
#include "realtime/engineio/packet_codec.h"
|
||||
#include "realtime/shared/base64.h"
|
||||
#include "realtime/shared/mini_json.h"
|
||||
#include "realtime/shared/utf8.h"
|
||||
#include "realtime/socketio/packet_codec.h"
|
||||
#include "realtime/sse/sse_client.h"
|
||||
#include "realtime/webdav/server/dav_xml.h"
|
||||
#include "realtime/websocket/server/frame_parser.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<uint8_t> garbage(std::mt19937_64& rng, std::size_t max_len) {
|
||||
std::uniform_int_distribution<std::size_t> len(0, max_len);
|
||||
std::uniform_int_distribution<int> byte(0, 255);
|
||||
std::uniform_int_distribution<int> pick(0, 3);
|
||||
std::vector<uint8_t> out(len(rng));
|
||||
for (auto& b : out) {
|
||||
// Mix raw bytes with protocol-ish alphabet to hit deep paths.
|
||||
int p = pick(rng);
|
||||
if (p == 0) {
|
||||
static const char k[] = "0123456-:,/[]{}<>\" _placeholder";
|
||||
b = static_cast<uint8_t>(k[byte(rng) % (sizeof(k) - 1)]);
|
||||
} else {
|
||||
b = static_cast<uint8_t>(byte(rng));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
std::mt19937_64 rng(0xC10C4E7E);
|
||||
constexpr int kIters = 4000;
|
||||
|
||||
int ws_frames = 0;
|
||||
for (int i = 0; i < kIters; ++i) {
|
||||
auto g = garbage(rng, 96);
|
||||
websocket::server::FrameParser parser(true);
|
||||
// Feed one byte at a time to stress incremental states.
|
||||
for (uint8_t b : g) {
|
||||
std::size_t consumed = 0;
|
||||
auto step = parser.feed(&b, 1, consumed);
|
||||
if (step.outcome == websocket::server::ParseOutcome::kFrame) {
|
||||
++ws_frames;
|
||||
}
|
||||
if (step.outcome == websocket::server::ParseOutcome::kFailed) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::string s(g.begin(), g.end());
|
||||
(void)engineio::PacketCodec::decode(s);
|
||||
(void)engineio::PacketCodec::decode_polling(s);
|
||||
(void)socketio::PacketCodec::decode_text(s);
|
||||
(void)shared::Json::parse(s);
|
||||
(void)shared::base64_decode(s);
|
||||
(void)shared::is_valid_utf8(g.data(), g.size());
|
||||
(void)webdav::server::parse_dav_xml(s, 65536);
|
||||
}
|
||||
T_CHECK(r, ws_frames >= 0); // Ran to completion without crashing.
|
||||
|
||||
// SSE client survives garbage streams and stays responsive.
|
||||
{
|
||||
sse::SseClient c;
|
||||
shared::HttpResponse head;
|
||||
head.status = 200;
|
||||
shared::set_header(head, "Content-Type", "text/event-stream");
|
||||
c.on_head(head);
|
||||
int events = 0;
|
||||
c.on_event([&](const sse::SseEvent&) { ++events; });
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
auto g = garbage(rng, 128);
|
||||
c.on_bytes(g.data(), g.size());
|
||||
}
|
||||
// Leading newline terminates any partial garbage line first:
|
||||
// without it the next bytes would correctly merge into that line.
|
||||
c.on_bytes("\ndata: alive\n\n");
|
||||
T_CHECK(r, events >= 1);
|
||||
}
|
||||
|
||||
return r.report("shared/robustness");
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// Route: /socket.io/ chat. Packet vectors for all 7 types,
|
||||
// namespace connect/refuse, rooms, ack round-trip, client parity
|
||||
// over an in-process server plus long-polling-only mode.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_main.h"
|
||||
#include "realtime/shared/mini_json.h"
|
||||
#include "realtime/socketio/ack_tracker.h"
|
||||
#include "realtime/socketio/client/socketio_client.h"
|
||||
#include "realtime/socketio/packet_codec.h"
|
||||
#include "realtime/socketio/socketio_server.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
using socketio::PacketCodec;
|
||||
using socketio::SocketPacket;
|
||||
using socketio::SocketPacketType;
|
||||
|
||||
// Official-style vectors for text packets.
|
||||
{
|
||||
auto ev = PacketCodec::decode_text("2[\"hi\",\"a\"]");
|
||||
T_CHECK(r, ev.has_value() && ev->type == SocketPacketType::kEvent);
|
||||
T_CHECK(r, ev->nsp == "/" && ev->ack_id < 0);
|
||||
T_CHECK(r, ev->data.array()[0].string() == "hi");
|
||||
auto back = PacketCodec::encode_text(*ev);
|
||||
T_CHECK(r, back.has_value() && *back == "2[\"hi\",\"a\"]");
|
||||
}
|
||||
{
|
||||
auto ev = PacketCodec::decode_text("2/chat,13[\"msg\",1]");
|
||||
T_CHECK(r, ev.has_value() && ev->nsp == "/chat" && ev->ack_id == 13);
|
||||
auto back = PacketCodec::encode_text(*ev);
|
||||
T_CHECK(r, back.has_value() && *back == "2/chat,13[\"msg\",1]");
|
||||
}
|
||||
{
|
||||
auto ack = PacketCodec::decode_text("336[\"ok\"]");
|
||||
T_CHECK(r, ack.has_value() && ack->type == SocketPacketType::kAck &&
|
||||
ack->ack_id == 36);
|
||||
}
|
||||
{
|
||||
auto disc = PacketCodec::decode_text("1/chat,");
|
||||
T_CHECK(r, disc.has_value() &&
|
||||
disc->type == SocketPacketType::kDisconnect &&
|
||||
disc->nsp == "/chat");
|
||||
}
|
||||
{
|
||||
auto conn = PacketCodec::decode_text("0{\"token\":\"t\"}");
|
||||
T_CHECK(r, conn.has_value() &&
|
||||
conn->type == SocketPacketType::kConnect);
|
||||
}
|
||||
{
|
||||
auto err = PacketCodec::decode_text("4{\"message\":\"no\"}");
|
||||
T_CHECK(r, err.has_value() &&
|
||||
err->type == SocketPacketType::kConnectError);
|
||||
}
|
||||
// Binary with placeholders.
|
||||
{
|
||||
auto bin = PacketCodec::decode_text(
|
||||
"51-[\"frame\",{\"_placeholder\":true,\"num\":0}]");
|
||||
T_CHECK(r, bin.has_value() &&
|
||||
bin->type == SocketPacketType::kBinaryEvent);
|
||||
T_CHECK(r, bin->attachments.size() == 1);
|
||||
std::vector<std::vector<uint8_t>> frames = {{1, 2, 3}};
|
||||
T_CHECK(r, PacketCodec::attach(*bin, frames));
|
||||
T_CHECK(r, bin->attachments[0] == frames[0]);
|
||||
auto back = PacketCodec::encode_text(*bin);
|
||||
T_CHECK(r, back.has_value());
|
||||
}
|
||||
T_CHECK(r, !PacketCodec::decode_text("").has_value());
|
||||
T_CHECK(r, !PacketCodec::decode_text("9[]").has_value());
|
||||
T_CHECK(r, !PacketCodec::valid_nsp("chat"));
|
||||
T_CHECK(r, !PacketCodec::valid_nsp("/a,b"));
|
||||
|
||||
// Ack tracker expiry.
|
||||
{
|
||||
socketio::AckTracker acks(std::chrono::milliseconds(10));
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
long long id = acks.expect(t0);
|
||||
T_CHECK(r, acks.pending() == 1);
|
||||
T_CHECK(r, acks.resolve(id));
|
||||
T_CHECK(r, !acks.resolve(id));
|
||||
acks.expect(t0);
|
||||
T_CHECK(r, acks.tick(t0 + std::chrono::milliseconds(50)) == 1);
|
||||
T_CHECK(r, acks.pending() == 0);
|
||||
}
|
||||
|
||||
// In-process client/server session with rooms and acks.
|
||||
socketio::SocketIoServer server;
|
||||
struct Out {
|
||||
std::string sid;
|
||||
std::string text;
|
||||
};
|
||||
std::vector<Out> server_out;
|
||||
server.set_sink([&](const std::string& sid, const std::string& text,
|
||||
const std::vector<std::vector<uint8_t>>&) {
|
||||
server_out.push_back({sid, text});
|
||||
});
|
||||
server.dispatcher().on("/", "join", [&](const std::string& sid,
|
||||
const shared::Json& args, auto ack) {
|
||||
(void)ack;
|
||||
std::string room = args.array()[1].string();
|
||||
server.rooms().join("/", room, sid);
|
||||
});
|
||||
server.dispatcher().on("/", "say", [&](const std::string& sid,
|
||||
const shared::Json& args, auto ack) {
|
||||
std::string room = args.array()[1].string();
|
||||
std::string msg = args.array()[2].string();
|
||||
shared::Json fwd = shared::Json::make_array();
|
||||
fwd.push(shared::Json::str(msg));
|
||||
server.emit_to_room("/", room, "said", fwd, sid, false);
|
||||
if (ack) {
|
||||
shared::Json reply = shared::Json::make_array();
|
||||
reply.push(shared::Json::str("ok"));
|
||||
ack(std::move(reply));
|
||||
}
|
||||
});
|
||||
|
||||
socketio::client::SocketIoClient alice;
|
||||
std::vector<std::string> alice_out;
|
||||
alice.on_emit([&](const std::string& text,
|
||||
const std::vector<std::vector<uint8_t>>&) {
|
||||
alice_out.push_back(text);
|
||||
auto p = PacketCodec::decode_text(text);
|
||||
if (p.has_value()) {
|
||||
server.on_packet("alice", *p);
|
||||
}
|
||||
});
|
||||
// Long-polling-only client exposes the same API.
|
||||
socketio::client::SocketIoClient poller(true);
|
||||
T_CHECK(r, poller.polling_only());
|
||||
poller.on_emit([&](const std::string& text,
|
||||
const std::vector<std::vector<uint8_t>>&) {
|
||||
auto p = PacketCodec::decode_text(text);
|
||||
if (p.has_value()) {
|
||||
server.on_packet("poller", *p);
|
||||
}
|
||||
});
|
||||
// Pump helper: server replies back into each client.
|
||||
auto pump_server = [&] {
|
||||
for (const auto& o : server_out) {
|
||||
auto p = PacketCodec::decode_text(o.text);
|
||||
if (!p.has_value()) {
|
||||
continue;
|
||||
}
|
||||
if (o.sid == "alice") {
|
||||
alice.on_packet(*p);
|
||||
} else if (o.sid == "poller") {
|
||||
poller.on_packet(*p);
|
||||
}
|
||||
// "bob" speaks the raw codec directly; nothing to feed.
|
||||
}
|
||||
server_out.clear();
|
||||
};
|
||||
|
||||
bool alice_joined = false;
|
||||
alice.on_connect([&](const std::string& nsp) {
|
||||
(void)nsp;
|
||||
alice_joined = true;
|
||||
});
|
||||
std::vector<std::string> heard;
|
||||
alice.on_event("/", "said",
|
||||
[&](const std::string&, const shared::Json& args, auto) {
|
||||
heard.push_back(args.array()[1].string());
|
||||
});
|
||||
bool acked = false;
|
||||
alice.connect_nsp("/");
|
||||
pump_server();
|
||||
T_CHECK(r, alice_joined && alice.connected_nsp("/"));
|
||||
|
||||
shared::Json join_args = shared::Json::make_array();
|
||||
join_args.push(shared::Json::str("lobby"));
|
||||
alice.emit("/", "join", join_args);
|
||||
pump_server();
|
||||
T_CHECK(r, server.rooms().room_size("/", "lobby") == 1);
|
||||
|
||||
// Bob joins through the raw codec path (third-party shape).
|
||||
auto raw_join = PacketCodec::decode_text("0{}");
|
||||
server.on_packet("bob", *raw_join);
|
||||
pump_server();
|
||||
auto bob_join = PacketCodec::decode_text("2[\"join\",\"lobby\"]");
|
||||
server.on_packet("bob", *bob_join);
|
||||
T_CHECK(r, server.rooms().room_size("/", "lobby") == 2);
|
||||
|
||||
shared::Json say_args = shared::Json::make_array();
|
||||
say_args.push(shared::Json::str("lobby"));
|
||||
say_args.push(shared::Json::str("hello"));
|
||||
alice.emit("/", "say", say_args, [&](shared::Json reply) {
|
||||
acked = reply.array()[0].string() == "ok";
|
||||
});
|
||||
pump_server(); // Server emits broadcast plus ack.
|
||||
pump_server(); // Ack text flows back to alice.
|
||||
T_CHECK(r, acked);
|
||||
// Alice excluded herself from the broadcast; bob got one packet.
|
||||
T_CHECK(r, heard.empty());
|
||||
|
||||
// Long-polling-only client connects through the same path.
|
||||
poller.connect_nsp("/");
|
||||
pump_server();
|
||||
T_CHECK(r, poller.connected_nsp("/"));
|
||||
|
||||
// Namespace refusal carries CONNECT_ERROR.
|
||||
server.get_or_create_namespace("/vip");
|
||||
server.get_or_create_namespace("/vip") =
|
||||
socketio::Namespace("/vip", [](const std::string&,
|
||||
const shared::Json&) {
|
||||
return std::string("members only");
|
||||
});
|
||||
std::string refusal;
|
||||
alice.on_connect_error([&](const std::string&, const std::string& msg) {
|
||||
refusal = msg;
|
||||
});
|
||||
alice.connect_nsp("/vip");
|
||||
pump_server();
|
||||
T_CHECK(r, refusal == "members only");
|
||||
T_CHECK(r, !alice.connected_nsp("/vip"));
|
||||
|
||||
return r.report("socketio/chat");
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// SSE client: head handling, stream parsing, reconnect state.
|
||||
|
||||
#include "test_main.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "realtime/sse/sse_client.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
|
||||
// Opens on 200 plus event-stream.
|
||||
{
|
||||
sse::SseClient c;
|
||||
bool opened = false;
|
||||
c.on_open([&] { opened = true; });
|
||||
shared::HttpResponse head;
|
||||
head.status = 200;
|
||||
shared::set_header(head, "Content-Type", "text/event-stream");
|
||||
T_CHECK(r, c.on_head(head));
|
||||
T_CHECK(r, opened);
|
||||
T_CHECK(r, c.state() == shared::ClientState::kOpen);
|
||||
}
|
||||
|
||||
// Wrong content type fails cleanly.
|
||||
{
|
||||
sse::SseClient c;
|
||||
shared::HttpResponse head;
|
||||
head.status = 200;
|
||||
shared::set_header(head, "Content-Type", "text/html");
|
||||
T_CHECK(r, !c.on_head(head));
|
||||
T_CHECK(r, !c.failure_reason().empty());
|
||||
}
|
||||
|
||||
// Redirect and stop.
|
||||
{
|
||||
sse::SseClient c;
|
||||
shared::HttpResponse head;
|
||||
head.status = 307;
|
||||
shared::set_header(head, "Location", "/sse/other");
|
||||
T_CHECK(r, !c.on_head(head));
|
||||
T_CHECK(r, c.redirect_url() == "/sse/other");
|
||||
}
|
||||
{
|
||||
sse::SseClient c;
|
||||
shared::HttpResponse head;
|
||||
head.status = 204;
|
||||
T_CHECK(r, !c.on_head(head));
|
||||
T_CHECK(r, c.stopped());
|
||||
T_CHECK(r, c.state() == shared::ClientState::kClosed);
|
||||
}
|
||||
|
||||
// Stream parsing: multiline data joins, ids tracked, retry honored.
|
||||
{
|
||||
sse::SseClient c;
|
||||
shared::HttpResponse head;
|
||||
head.status = 200;
|
||||
shared::set_header(head, "Content-Type", "text/event-stream");
|
||||
c.on_head(head);
|
||||
std::vector<sse::SseEvent> got;
|
||||
c.on_event([&](const sse::SseEvent& e) { got.push_back(e); });
|
||||
c.on_bytes(": keep-alive\n\n");
|
||||
c.on_bytes("event: tick\ndata: one\ndata: two\nid: 7\nretry: 5000\n\n");
|
||||
T_CHECK(r, got.size() == 1);
|
||||
T_CHECK(r, got[0].event == "tick");
|
||||
T_CHECK(r, got[0].data == "one\ntwo");
|
||||
T_CHECK(r, got[0].id == "7");
|
||||
T_CHECK(r, c.last_event_id() == "7");
|
||||
T_CHECK(r, c.retry_delay() == std::chrono::milliseconds(5000));
|
||||
// Partial delivery across feeds still dispatches.
|
||||
c.on_bytes("data: half");
|
||||
T_CHECK(r, got.size() == 1);
|
||||
c.on_bytes("-done\n\n");
|
||||
T_CHECK(r, got.size() == 2);
|
||||
T_CHECK(r, got[1].data == "half-done");
|
||||
T_CHECK(r, got[1].event.empty()); // Default message type.
|
||||
}
|
||||
|
||||
return r.report("sse/client");
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Route: /sse/feed. Byte-exact encoding, headers, replay, stop.
|
||||
|
||||
#include "test_main.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "realtime/sse/event_encoder.h"
|
||||
#include "realtime/sse/event_store.h"
|
||||
#include "realtime/sse/sse_response.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
|
||||
// Byte-exact encoding with all fields.
|
||||
{
|
||||
sse::SseEvent e;
|
||||
e.event = "price";
|
||||
e.data = "line1\nline2";
|
||||
e.id = "42";
|
||||
T_CHECK(r, sse::EventEncoder::encode(e) ==
|
||||
"event: price\ndata: line1\ndata: line2\nid: 42\n\n");
|
||||
}
|
||||
// Default type omits the event line; CRLF normalizes.
|
||||
{
|
||||
sse::SseEvent e;
|
||||
e.data = "a\r\nb\rc";
|
||||
T_CHECK(r, sse::EventEncoder::encode(e) ==
|
||||
"data: a\ndata: b\ndata: c\n\n");
|
||||
}
|
||||
// Retry clamps to 1 s..300 s.
|
||||
T_CHECK(r, sse::EventEncoder::clamp_retry(std::chrono::milliseconds(5)) ==
|
||||
std::chrono::milliseconds(1000));
|
||||
T_CHECK(r,
|
||||
sse::EventEncoder::clamp_retry(std::chrono::milliseconds(9999999)) ==
|
||||
std::chrono::milliseconds(300000));
|
||||
|
||||
// Response headers per rule 6.
|
||||
{
|
||||
sse::SseResponse res;
|
||||
auto head = res.start();
|
||||
T_CHECK(r, head.status == 200 && head.stream);
|
||||
T_CHECK(r, shared::header_first(head, "Content-Type") ==
|
||||
"text/event-stream");
|
||||
T_CHECK(r, shared::header_first(head, "Cache-Control") == "no-store");
|
||||
}
|
||||
|
||||
// Store assigns ids and replays after Last-Event-ID.
|
||||
{
|
||||
sse::EventStore store(10, std::chrono::minutes(5));
|
||||
sse::SseEvent a, b, c;
|
||||
a.data = "a";
|
||||
b.data = "b";
|
||||
c.data = "c";
|
||||
auto sa = store.append(a);
|
||||
auto sb = store.append(b);
|
||||
store.append(c);
|
||||
T_CHECK(r, sa.id == "1" && sb.id == "2");
|
||||
auto replay = store.replay_after("1");
|
||||
T_CHECK(r, replay.size() == 2);
|
||||
T_CHECK(r, replay[0].data == "b" && replay[1].data == "c");
|
||||
T_CHECK(r, store.replay_after("3").empty());
|
||||
// Unknown id replays the whole window.
|
||||
T_CHECK(r, store.replay_after("zzz").size() == 3);
|
||||
}
|
||||
|
||||
// Cap eviction: count wins over age here.
|
||||
{
|
||||
sse::EventStore store(2, std::chrono::minutes(5));
|
||||
sse::SseEvent e;
|
||||
e.data = "x";
|
||||
store.append(e);
|
||||
store.append(e);
|
||||
store.append(e);
|
||||
T_CHECK(r, store.size() == 2);
|
||||
}
|
||||
|
||||
// SseResponse wires store plus encoding plus 204 stop.
|
||||
{
|
||||
sse::SseResponse res;
|
||||
res.set_retry(std::chrono::milliseconds(2000));
|
||||
sse::SseEvent e;
|
||||
e.event = "msg";
|
||||
e.data = "hi";
|
||||
std::string wire = res.send(e);
|
||||
T_CHECK(r, wire.find("retry: 2000\n") != std::string::npos);
|
||||
T_CHECK(r, wire.find("id: 1\n") != std::string::npos);
|
||||
sse::SseEvent e2;
|
||||
e2.data = "again";
|
||||
std::string wire2 = res.send(e2);
|
||||
T_CHECK(r, wire2.find("retry:") == std::string::npos); // Once only.
|
||||
std::string replay = res.replay_bytes("1");
|
||||
T_CHECK(r, replay.find("data: again") != std::string::npos);
|
||||
T_CHECK(r, sse::SseResponse::stop().status == 204);
|
||||
}
|
||||
|
||||
T_CHECK(r, sse::SseResponse::keep_alive() == ": ping\n\n");
|
||||
|
||||
return r.report("sse/feed");
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Route: /stream/download. Chunked framing, range parsing,
|
||||
// passthrough pump with bounded memory and disconnect cleanup.
|
||||
|
||||
#include "test_main.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "realtime/streaming/chunked_body.h"
|
||||
#include "realtime/streaming/passthrough_body.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
|
||||
// Chunked framing is byte-exact.
|
||||
{
|
||||
streaming::ChunkedBody body;
|
||||
std::string out = body.write("hello");
|
||||
out += body.flush();
|
||||
out += body.finish();
|
||||
T_CHECK(r, out == "5\r\nhello\r\n0\r\n\r\n");
|
||||
T_CHECK(r, body.finish().empty()); // Idempotent.
|
||||
T_CHECK(r, body.total_bytes() == 5);
|
||||
}
|
||||
|
||||
// Empty writes produce no chunks.
|
||||
{
|
||||
streaming::ChunkedBody body;
|
||||
T_CHECK(r, body.write("").empty());
|
||||
T_CHECK(r, body.finish() == "0\r\n\r\n");
|
||||
}
|
||||
|
||||
// Range parsing: single ranges only.
|
||||
{
|
||||
auto full = streaming::parse_range("bytes=0-99", 100);
|
||||
T_CHECK(r, full.satisfiable && full.first == 0 && full.last == 99);
|
||||
auto tail = streaming::parse_range("bytes=-10", 100);
|
||||
T_CHECK(r, tail.satisfiable && tail.first == 90 && tail.last == 99);
|
||||
auto open = streaming::parse_range("bytes=50-", 100);
|
||||
T_CHECK(r, open.satisfiable && open.first == 50 && open.last == 99);
|
||||
T_CHECK(r, !streaming::parse_range("bytes=0-10,20-30", 100).satisfiable);
|
||||
T_CHECK(r, !streaming::parse_range("bytes=200-", 100).satisfiable);
|
||||
T_CHECK(r, !streaming::parse_range("items=0-1", 100).satisfiable);
|
||||
}
|
||||
|
||||
// Passthrough pumps 8 MiB through a 64 KiB ring with flat memory.
|
||||
{
|
||||
const std::size_t kTotal = 8u * 1024u * 1024u;
|
||||
std::size_t produced = 0;
|
||||
std::size_t consumed = 0;
|
||||
uint64_t checksum = 0;
|
||||
streaming::PassthroughBody pump(64u * 1024u);
|
||||
std::size_t moved = pump.pump(
|
||||
[&](uint8_t* out, std::size_t max) {
|
||||
std::size_t left = kTotal - produced;
|
||||
std::size_t n = left < max ? left : max;
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
out[i] = static_cast<uint8_t>((produced + i) & 0xFFu);
|
||||
}
|
||||
produced += n;
|
||||
return n;
|
||||
},
|
||||
[&](const uint8_t* data, std::size_t len) {
|
||||
for (std::size_t i = 0; i < len; ++i) {
|
||||
checksum += data[i];
|
||||
}
|
||||
consumed += len;
|
||||
return true;
|
||||
});
|
||||
T_CHECK(r, moved == kTotal && consumed == kTotal);
|
||||
T_CHECK(r, !pump.aborted());
|
||||
// Sum of 0..255 repeating over 8 MiB.
|
||||
uint64_t expect = (kTotal / 256) * (255u * 256u / 2);
|
||||
T_CHECK(r, checksum == expect);
|
||||
}
|
||||
|
||||
// Client disconnect aborts the pump promptly.
|
||||
{
|
||||
streaming::PassthroughBody pump(4096);
|
||||
std::size_t calls = 0;
|
||||
std::size_t moved = pump.pump(
|
||||
[&](uint8_t* out, std::size_t max) {
|
||||
(void)out;
|
||||
++calls;
|
||||
return max; // Endless producer.
|
||||
},
|
||||
[&](const uint8_t*, std::size_t) { return false; });
|
||||
T_CHECK(r, pump.aborted());
|
||||
T_CHECK(r, moved == 0 && calls == 1);
|
||||
}
|
||||
|
||||
// Max-bytes cap truncates.
|
||||
{
|
||||
streaming::PassthroughBody pump(4096);
|
||||
std::size_t moved = pump.pump(
|
||||
[&](uint8_t* out, std::size_t max) {
|
||||
(void)out;
|
||||
return max;
|
||||
},
|
||||
[&](const uint8_t*, std::size_t) { return true; }, 100);
|
||||
T_CHECK(r, moved == 100);
|
||||
}
|
||||
|
||||
return r.report("stream/passthrough");
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
// Minimal test helper for realtime integration tests. Tests run
|
||||
// through real objects and real sockets (socketpair loopback), never
|
||||
// mocks. CHECK records failures; main returns nonzero when any fail.
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace realtime_test {
|
||||
|
||||
class Results {
|
||||
public:
|
||||
void check(bool ok, const char* expr, const char* file, int line) {
|
||||
++total_;
|
||||
if (ok) {
|
||||
++passed_;
|
||||
} else {
|
||||
++failed_;
|
||||
failures_.push_back(std::string(file) + ":" + std::to_string(line) +
|
||||
": " + expr);
|
||||
}
|
||||
}
|
||||
|
||||
int report(const char* name) {
|
||||
std::printf("%s: passed=%d failed=%d total=%d\n", name, passed_, failed_,
|
||||
total_);
|
||||
for (const auto& f : failures_) {
|
||||
std::printf(" FAIL %s\n", f.c_str());
|
||||
}
|
||||
return failed_ == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private:
|
||||
int total_ = 0;
|
||||
int passed_ = 0;
|
||||
int failed_ = 0;
|
||||
std::vector<std::string> failures_;
|
||||
};
|
||||
|
||||
} // namespace realtime_test
|
||||
|
||||
#define T_CHECK(results, expr) \
|
||||
(results).check((expr), #expr, __FILE__, __LINE__)
|
||||
@@ -0,0 +1,139 @@
|
||||
// Route: /ws/echo. Full round-trip over a real socketpair: client
|
||||
// handshake bytes, server view admit/accept, text plus binary echo,
|
||||
// close handshake. Exercises the real FD path, not memory doubles.
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_main.h"
|
||||
#include "realtime/shared/transport.h"
|
||||
#include "realtime/websocket/client/client_handshake.h"
|
||||
#include "realtime/websocket/client/websocket_client.h"
|
||||
#include "realtime/websocket/server/websocket_handler.h"
|
||||
#include "realtime/websocket/server/websocket_view.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
namespace {
|
||||
|
||||
class EchoHandler : public websocket::server::WebSocketHandler {
|
||||
public:
|
||||
void on_text(const std::string& message) override {
|
||||
send_text("echo:" + message);
|
||||
}
|
||||
void on_binary(const std::vector<uint8_t>& payload) override {
|
||||
send_binary(payload);
|
||||
}
|
||||
};
|
||||
|
||||
std::string read_available(int fd) {
|
||||
char buf[65536];
|
||||
ssize_t n = ::read(fd, buf, sizeof(buf));
|
||||
return n <= 0 ? std::string{} : std::string(buf, buf + n);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
|
||||
int sv[2];
|
||||
T_CHECK(r, ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
|
||||
|
||||
websocket::server::WebSocketView view(
|
||||
[] { return std::make_unique<EchoHandler>(); });
|
||||
|
||||
// Client builds the handshake, sends it over the real socket.
|
||||
websocket::client::WebSocketClient client;
|
||||
shared::FdTransport client_fd(sv[0]);
|
||||
client.bind(&client_fd, "localhost", "/ws/echo");
|
||||
std::string key;
|
||||
shared::HttpRequest hs_req =
|
||||
websocket::client::ClientHandshake::build_request(
|
||||
"localhost", "/ws/echo", {}, key);
|
||||
std::string wire = websocket::client::ClientHandshake::render(hs_req);
|
||||
T_CHECK(r, client_fd.send(wire));
|
||||
|
||||
// Server reads raw bytes and admits from the parsed head.
|
||||
std::string got = read_available(sv[1]);
|
||||
T_CHECK(r, got.find("Sec-WebSocket-Key: ") != std::string::npos);
|
||||
auto admit = view.admit(hs_req);
|
||||
T_CHECK(r, admit.ok);
|
||||
|
||||
// Server 101 travels back; client validates the accept hash.
|
||||
T_CHECK(r, websocket::client::ClientHandshake::check_response(
|
||||
admit.response, key)
|
||||
.ok);
|
||||
client.note_open();
|
||||
|
||||
// Bind the server connection to the other FD.
|
||||
shared::FdTransport server_fd(sv[1]);
|
||||
shared::ConnectionContext ctx;
|
||||
ctx.route = "/ws/echo";
|
||||
ctx.correlation_id = "echo-1";
|
||||
websocket::server::WebSocketConnection* conn =
|
||||
view.accept(&server_fd, ctx);
|
||||
T_CHECK(r, conn != nullptr);
|
||||
|
||||
// Client text round-trips through the echo handler.
|
||||
std::string echoed;
|
||||
client.on_message([&](bool is_text, const std::vector<uint8_t>& p) {
|
||||
(void)is_text;
|
||||
echoed = std::string(p.begin(), p.end());
|
||||
});
|
||||
T_CHECK(r, client.send_text("hello"));
|
||||
std::string c2s = read_available(sv[1]);
|
||||
T_CHECK(r, !c2s.empty());
|
||||
T_CHECK(r, conn->on_bytes(reinterpret_cast<const uint8_t*>(c2s.data()),
|
||||
c2s.size()));
|
||||
T_CHECK(r, conn->flush());
|
||||
std::string s2c = read_available(sv[0]);
|
||||
T_CHECK(r, !s2c.empty());
|
||||
T_CHECK(r, client.on_bytes(reinterpret_cast<const uint8_t*>(s2c.data()),
|
||||
s2c.size()));
|
||||
T_CHECK(r, echoed == "echo:hello");
|
||||
|
||||
// Binary round-trips byte-exact.
|
||||
std::vector<uint8_t> bin_in = {0x00, 0xFF, 0x01, 0xFE};
|
||||
std::vector<uint8_t> bin_out;
|
||||
client.on_message([&](bool is_text, const std::vector<uint8_t>& p) {
|
||||
(void)is_text;
|
||||
bin_out = p;
|
||||
});
|
||||
T_CHECK(r, client.send_binary(bin_in.data(), bin_in.size()));
|
||||
c2s = read_available(sv[1]);
|
||||
T_CHECK(r, conn->on_bytes(reinterpret_cast<const uint8_t*>(c2s.data()),
|
||||
c2s.size()));
|
||||
T_CHECK(r, conn->flush());
|
||||
s2c = read_available(sv[0]);
|
||||
T_CHECK(r, client.on_bytes(reinterpret_cast<const uint8_t*>(s2c.data()),
|
||||
s2c.size()));
|
||||
T_CHECK(r, bin_out == bin_in);
|
||||
|
||||
// Ping from the client is answered with an identical pong.
|
||||
client.send_ping({'p', 'i'});
|
||||
c2s = read_available(sv[1]);
|
||||
T_CHECK(r, conn->on_bytes(reinterpret_cast<const uint8_t*>(c2s.data()),
|
||||
c2s.size()));
|
||||
s2c = read_available(sv[0]);
|
||||
T_CHECK(r, s2c.size() == 4 && s2c[0] == (char)0x8A && s2c[2] == 'p');
|
||||
|
||||
// Clean close both directions.
|
||||
bool client_closed = false;
|
||||
client.on_close([&](uint16_t, const std::string&) { client_closed = true; });
|
||||
client.close(1000, "done");
|
||||
c2s = read_available(sv[1]);
|
||||
conn->on_bytes(reinterpret_cast<const uint8_t*>(c2s.data()), c2s.size());
|
||||
T_CHECK(r, !conn->open());
|
||||
s2c = read_available(sv[0]);
|
||||
client.on_bytes(reinterpret_cast<const uint8_t*>(s2c.data()), s2c.size());
|
||||
T_CHECK(r, client_closed);
|
||||
|
||||
::close(sv[0]);
|
||||
::close(sv[1]);
|
||||
return r.report("ws/echo");
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// Route: /ws/* framing. Byte-level RFC 6455 vectors: masked parse,
|
||||
// fragmentation, control limits, UTF-8 and mask rejection.
|
||||
|
||||
#include "test_main.h"
|
||||
|
||||
#include "realtime/shared/transport.h"
|
||||
#include "realtime/websocket/server/frame_parser.h"
|
||||
#include "realtime/websocket/server/frame_serializer.h"
|
||||
#include "realtime/websocket/server/websocket_response.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
namespace {
|
||||
|
||||
// RFC 6455 section 5.7 masked "Hello" with mask 37 fa 21 3d.
|
||||
std::vector<uint8_t> rfc_hello() {
|
||||
return {0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
using server = websocket::server::FrameParser;
|
||||
using serializer = websocket::server::FrameSerializer;
|
||||
using websocket::server::CloseCode;
|
||||
using websocket::server::Opcode;
|
||||
using websocket::server::ParseOutcome;
|
||||
|
||||
// Golden masked frame decodes to "Hello".
|
||||
{
|
||||
server p(true);
|
||||
auto wire = rfc_hello();
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFrame);
|
||||
T_CHECK(r, step.frame.opcode == Opcode::kText);
|
||||
T_CHECK(r, std::string(step.frame.payload.begin(),
|
||||
step.frame.payload.end()) == "Hello");
|
||||
}
|
||||
|
||||
// Unmasked client frame fails with 1002 (rule 2).
|
||||
{
|
||||
server p(true);
|
||||
auto wire = serializer::text("hi");
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFailed);
|
||||
T_CHECK(r, step.fail_code == CloseCode::kProtocolError);
|
||||
}
|
||||
|
||||
// Server frames are never masked: round-trip unmasked parse.
|
||||
{
|
||||
server p(false);
|
||||
auto wire = serializer::text("hello");
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFrame);
|
||||
}
|
||||
{
|
||||
server p(false);
|
||||
uint8_t mask[4] = {1, 2, 3, 4};
|
||||
auto wire = serializer::masked_frame(true, Opcode::kText,
|
||||
reinterpret_cast<const uint8_t*>("hi"),
|
||||
2, mask);
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFailed);
|
||||
}
|
||||
|
||||
// Fragmented control frame is a protocol error (rule 4).
|
||||
{
|
||||
server p(true);
|
||||
uint8_t mask[4] = {0, 0, 0, 0};
|
||||
uint8_t payload[1] = {'x'};
|
||||
auto wire =
|
||||
serializer::masked_frame(false, Opcode::kPing, payload, 1, mask);
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFailed);
|
||||
}
|
||||
|
||||
// Control payload over 125 bytes fails.
|
||||
{
|
||||
server p(true);
|
||||
std::vector<uint8_t> big(126, 'a');
|
||||
uint8_t mask[4] = {0, 0, 0, 0};
|
||||
auto wire =
|
||||
serializer::masked_frame(true, Opcode::kPing, big.data(), big.size(),
|
||||
mask);
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFailed);
|
||||
}
|
||||
|
||||
// 16-bit and 64-bit lengths round-trip.
|
||||
for (std::size_t n : {126u, 1000u, 65536u}) {
|
||||
std::vector<uint8_t> payload(n, 'b');
|
||||
auto wire = serializer::frame(true, Opcode::kBinary, payload);
|
||||
server p(false);
|
||||
std::size_t consumed = 0;
|
||||
auto step = p.feed(wire.data(), wire.size(), consumed);
|
||||
T_CHECK(r, step.outcome == ParseOutcome::kFrame);
|
||||
T_CHECK(r, step.frame.payload.size() == n);
|
||||
}
|
||||
|
||||
// Invalid UTF-8 text fails the connection with 1007 (rule 3).
|
||||
{
|
||||
shared::MemoryTransport t;
|
||||
shared::ConnectionContext ctx;
|
||||
websocket::server::WebSocketConnection conn(&t, ctx);
|
||||
bool closed = false;
|
||||
conn.on_close([&](uint16_t code, const std::string&) {
|
||||
closed = code == 1007;
|
||||
});
|
||||
uint8_t mask[4] = {9, 9, 9, 9};
|
||||
uint8_t bad[2] = {0xC3, 0x28}; // Invalid 2-byte sequence.
|
||||
auto wire =
|
||||
serializer::masked_frame(true, Opcode::kText, bad, 2, mask);
|
||||
T_CHECK(r, !conn.on_bytes(wire.data(), wire.size()));
|
||||
T_CHECK(r, closed);
|
||||
}
|
||||
|
||||
// Fragmented message reassembles; ping is answered with pong.
|
||||
{
|
||||
shared::MemoryTransport t;
|
||||
shared::ConnectionContext ctx;
|
||||
websocket::server::WebSocketConnection conn(&t, ctx);
|
||||
std::string got;
|
||||
conn.on_message([&](bool is_text, const std::vector<uint8_t>& p) {
|
||||
got = std::string(p.begin(), p.end());
|
||||
(void)is_text;
|
||||
});
|
||||
uint8_t mask[4] = {0, 0, 0, 0};
|
||||
auto f1 = serializer::masked_frame(
|
||||
false, Opcode::kText, reinterpret_cast<const uint8_t*>("he"), 2, mask);
|
||||
auto f2 = serializer::masked_frame(
|
||||
true, Opcode::kContinuation,
|
||||
reinterpret_cast<const uint8_t*>("llo"), 3, mask);
|
||||
T_CHECK(r, conn.on_bytes(f1.data(), f1.size()));
|
||||
T_CHECK(r, conn.on_bytes(f2.data(), f2.size()));
|
||||
T_CHECK(r, got == "hello");
|
||||
auto ping = serializer::masked_frame(true, Opcode::kPing,
|
||||
reinterpret_cast<const uint8_t*>("p"),
|
||||
1, mask);
|
||||
T_CHECK(r, conn.on_bytes(ping.data(), ping.size()));
|
||||
// Server answered 0x8a pong with payload "p".
|
||||
T_CHECK(r, t.sent().size() == 3 && t.sent()[0] == 0x8A &&
|
||||
t.sent()[2] == 'p');
|
||||
}
|
||||
|
||||
// Close handshake echoes the code.
|
||||
{
|
||||
shared::MemoryTransport t;
|
||||
shared::ConnectionContext ctx;
|
||||
websocket::server::WebSocketConnection conn(&t, ctx);
|
||||
uint16_t code = 0;
|
||||
conn.on_close([&](uint16_t c, const std::string&) { code = c; });
|
||||
uint8_t mask[4] = {0, 0, 0, 0};
|
||||
uint8_t body[2] = {0x03, 0xE8}; // 1000.
|
||||
auto wire =
|
||||
serializer::masked_frame(true, Opcode::kClose, body, 2, mask);
|
||||
conn.on_bytes(wire.data(), wire.size());
|
||||
T_CHECK(r, code == 1000);
|
||||
T_CHECK(r, !conn.open());
|
||||
}
|
||||
|
||||
return r.report("ws/frames");
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Route: /ws/* handshake. Golden RFC 6455 vectors plus failure modes.
|
||||
|
||||
#include "test_main.h"
|
||||
|
||||
#include "realtime/shared/http_seam.h"
|
||||
#include "realtime/websocket/server/handshake_validator.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
namespace {
|
||||
|
||||
websocket::server::HandshakeValidator validator() {
|
||||
websocket::server::HandshakeConfig cfg;
|
||||
cfg.subprotocols = {"chat", "super"};
|
||||
return websocket::server::HandshakeValidator(cfg);
|
||||
}
|
||||
|
||||
shared::HttpRequest base_req() {
|
||||
shared::HttpRequest req;
|
||||
req.method = "GET";
|
||||
req.path = "/ws/chat";
|
||||
req.headers.emplace("Upgrade", "websocket");
|
||||
req.headers.emplace("Connection", "Upgrade");
|
||||
req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
|
||||
req.headers.emplace("Sec-WebSocket-Version", "13");
|
||||
return req;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
|
||||
// RFC 6455 section 1.3 golden vector.
|
||||
T_CHECK(r, websocket::server::HandshakeValidator::accept_for(
|
||||
"dGhlIHNhbXBsZSBub25jZQ==") == "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
|
||||
|
||||
auto ok = validator().validate(base_req());
|
||||
T_CHECK(r, ok.ok);
|
||||
T_CHECK(r, ok.response.status == 101);
|
||||
T_CHECK(r, shared::header_first(ok.response, "Sec-WebSocket-Accept") ==
|
||||
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
|
||||
T_CHECK(r, shared::header_first(ok.response, "Upgrade") == "websocket");
|
||||
|
||||
// Subprotocol negotiation picks the server's first match.
|
||||
auto req = base_req();
|
||||
req.headers.emplace("Sec-WebSocket-Protocol", "super, chat");
|
||||
auto sub = validator().validate(req);
|
||||
T_CHECK(r, sub.ok && sub.subprotocol == "chat");
|
||||
|
||||
// Unknown subprotocol fails when the server offers any.
|
||||
req = base_req();
|
||||
req.headers.emplace("Sec-WebSocket-Protocol", "nope");
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
|
||||
// Failure modes.
|
||||
req = base_req();
|
||||
req.method = "POST";
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
req = base_req();
|
||||
req.headers.erase("Upgrade");
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
req = base_req();
|
||||
req.headers.erase("Connection");
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
req = base_req();
|
||||
req.headers.erase("Sec-WebSocket-Key");
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
req = base_req();
|
||||
req.headers.emplace("Sec-WebSocket-Key", "!!!!");
|
||||
req.headers.erase("Sec-WebSocket-Key");
|
||||
req.headers.emplace("Sec-WebSocket-Key", "!!!!");
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
req = base_req();
|
||||
req.headers.erase("Sec-WebSocket-Key");
|
||||
req.headers.emplace("Sec-WebSocket-Key", "aGk="); // Decodes to 2 bytes.
|
||||
T_CHECK(r, !validator().validate(req).ok);
|
||||
|
||||
// Case-insensitive token match on Connection with extras.
|
||||
req = base_req();
|
||||
req.headers.erase("Connection");
|
||||
req.headers.emplace("Connection", "keep-alive, Upgrade");
|
||||
T_CHECK(r, validator().validate(req).ok);
|
||||
|
||||
return r.report("ws/handshake");
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Heartbeat manager: ping schedule plus pong-timeout close.
|
||||
|
||||
#include "test_main.h"
|
||||
|
||||
#include "realtime/websocket/server/heartbeat_manager.h"
|
||||
|
||||
using namespace molo::realtime;
|
||||
|
||||
int main() {
|
||||
realtime_test::Results r;
|
||||
using clock = std::chrono::steady_clock;
|
||||
using websocket::server::HeartbeatManager;
|
||||
|
||||
// Pings fire on interval while activity flows.
|
||||
{
|
||||
HeartbeatManager hb(std::chrono::milliseconds(25),
|
||||
std::chrono::milliseconds(100));
|
||||
int pings = 0;
|
||||
bool dead = false;
|
||||
hb.on_ping([&] { ++pings; });
|
||||
hb.on_timeout([&] { dead = true; });
|
||||
auto t0 = clock::now();
|
||||
hb.start(t0);
|
||||
hb.note_activity(t0);
|
||||
T_CHECK(r, hb.tick(t0 + std::chrono::milliseconds(10)));
|
||||
T_CHECK(r, pings == 0);
|
||||
hb.note_activity(t0 + std::chrono::milliseconds(10));
|
||||
T_CHECK(r, hb.tick(t0 + std::chrono::milliseconds(30)));
|
||||
T_CHECK(r, pings == 1);
|
||||
T_CHECK(r, !dead);
|
||||
}
|
||||
|
||||
// Silence past the timeout fires once and sticks.
|
||||
{
|
||||
HeartbeatManager hb(std::chrono::milliseconds(25),
|
||||
std::chrono::milliseconds(50));
|
||||
int pings = 0;
|
||||
int timeouts = 0;
|
||||
hb.on_ping([&] { ++pings; });
|
||||
hb.on_timeout([&] { ++timeouts; });
|
||||
auto t0 = clock::now();
|
||||
hb.start(t0);
|
||||
T_CHECK(r, !hb.tick(t0 + std::chrono::milliseconds(60)));
|
||||
T_CHECK(r, timeouts == 1);
|
||||
T_CHECK(r, !hb.tick(t0 + std::chrono::milliseconds(70)));
|
||||
T_CHECK(r, timeouts == 1);
|
||||
T_CHECK(r, hb.timed_out());
|
||||
}
|
||||
|
||||
return r.report("ws/heartbeat");
|
||||
}
|
||||
Reference in New Issue
Block a user