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:
2026-10-23 18:20:04 +02:00
parent 54068f1953
commit 3c4334cec9
1068 changed files with 100899 additions and 2 deletions
@@ -0,0 +1,125 @@
// Incremental frame parser. See frame_parser.h.
#include "realtime/websocket/server/frame_parser.h"
namespace molo::realtime::websocket::server {
FrameParser::FrameParser(bool require_mask, std::size_t max_frame_payload)
: require_mask_(require_mask), max_frame_payload_(max_frame_payload) {}
void FrameParser::reset() {
buf_.clear();
failed_ = false;
}
ParseStep FrameParser::feed(const uint8_t* data, std::size_t len,
std::size_t& consumed) {
consumed = 0;
ParseStep step;
if (failed_) {
step.outcome = ParseOutcome::kFailed;
step.fail_code = CloseCode::kProtocolError;
step.fail_reason = "parser already failed";
return step;
}
buf_.insert(buf_.end(), data, data + len);
consumed = len;
if (buf_.size() < 2) {
return step; // kNeedMore.
}
return parse_header();
}
ParseStep FrameParser::parse_header() {
ParseStep step;
uint8_t b0 = buf_[0];
uint8_t b1 = buf_[1];
bool fin = (b0 & 0x80u) != 0;
bool rsv = (b0 & 0x70u) != 0;
auto opcode = static_cast<Opcode>(b0 & 0x0Fu);
bool masked = (b1 & 0x80u) != 0;
uint64_t plen = b1 & 0x7Fu;
auto fail = [&](CloseCode code, const std::string& reason) {
failed_ = true;
step.outcome = ParseOutcome::kFailed;
step.fail_code = code;
step.fail_reason = reason;
return step;
};
if (rsv) {
return fail(CloseCode::kProtocolError, "RSV bits set without extension");
}
if (!is_control(opcode) && !is_data(opcode)) {
return fail(CloseCode::kProtocolError, "unknown opcode");
}
if (is_control(opcode) && !fin) {
return fail(CloseCode::kProtocolError, "fragmented control frame");
}
if (require_mask_ && !masked) {
return fail(CloseCode::kProtocolError, "client frame without mask");
}
if (!require_mask_ && masked) {
return fail(CloseCode::kProtocolError, "server frame must not be masked");
}
std::size_t off = 2;
if (plen == 126u) {
if (buf_.size() < 4) {
return step;
}
plen = (static_cast<uint64_t>(buf_[2]) << 8) | buf_[3];
off = 4;
if (plen < 126u) {
return fail(CloseCode::kProtocolError, "non-minimal length encoding");
}
} else if (plen == 127u) {
if (buf_.size() < 10) {
return step;
}
plen = 0;
for (int i = 0; i < 8; ++i) {
plen = (plen << 8) | buf_[2 + i];
}
off = 10;
if ((plen >> 63) != 0) {
return fail(CloseCode::kProtocolError, "length bit 63 set");
}
if (plen < 65536u) {
return fail(CloseCode::kProtocolError, "non-minimal length encoding");
}
}
if (is_control(opcode) && plen > shared::Caps::kMaxControlPayloadBytes) {
return fail(CloseCode::kProtocolError, "control payload over 125 bytes");
}
if (plen > max_frame_payload_) {
return fail(CloseCode::kMessageTooBig, "frame payload over cap");
}
uint8_t mask[4] = {0, 0, 0, 0};
if (masked) {
if (buf_.size() < off + 4) {
return step;
}
for (int i = 0; i < 4; ++i) {
mask[i] = buf_[off + i];
}
off += 4;
}
if (buf_.size() < off + plen) {
return step;
}
Frame frame;
frame.fin = fin;
frame.opcode = opcode;
frame.payload.assign(buf_.begin() + off, buf_.begin() + off + plen);
if (masked) {
for (std::size_t i = 0; i < frame.payload.size(); ++i) {
frame.payload[i] ^= mask[i % 4];
}
}
buf_.erase(buf_.begin(), buf_.begin() + off + static_cast<std::size_t>(plen));
step.outcome = ParseOutcome::kFrame;
step.frame = std::move(frame);
return step;
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,62 @@
#pragma once
// Incremental WebSocket frame parser (RFC 6455 section 5). Feed raw
// bytes; the parser emits complete frames or a protocol failure with
// the close code to answer. Client frames MUST be masked (rule 2):
// unmasked frames fail with 1002. Control frames MUST have FIN set
// and payload at most 125 bytes (rule 4).
#include <cstddef>
#include <cstdint>
#include <optional>
#include <vector>
#include "realtime/shared/caps.h"
#include "realtime/websocket/server/opcode.h"
namespace molo::realtime::websocket::server {
struct Frame {
bool fin = true;
Opcode opcode = Opcode::kText;
std::vector<uint8_t> payload; // Already unmasked.
};
enum class ParseOutcome : std::uint8_t {
kNeedMore,
kFrame,
kFailed,
};
struct ParseStep {
ParseOutcome outcome = ParseOutcome::kNeedMore;
Frame frame;
CloseCode fail_code = CloseCode::kProtocolError;
std::string fail_reason;
};
class FrameParser {
public:
// require_mask=true for server-side parsing of client bytes,
// false for client-side parsing of server bytes.
explicit FrameParser(
bool require_mask = true,
std::size_t max_frame_payload = shared::Caps::kMaxFramePayloadBytes);
// Feeds bytes, returning one step per call. Callers loop until
// kNeedMore or kFailed. Consumed count tells how many bytes of
// the input were used.
ParseStep feed(const uint8_t* data, std::size_t len, std::size_t& consumed);
bool failed() const { return failed_; }
void reset();
private:
ParseStep parse_header();
bool require_mask_;
std::size_t max_frame_payload_;
std::vector<uint8_t> buf_;
bool failed_ = false;
};
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,92 @@
// Frame serializer. See frame_serializer.h.
#include "realtime/websocket/server/frame_serializer.h"
namespace molo::realtime::websocket::server {
namespace {
void append_length(std::vector<uint8_t>& out, std::size_t len, bool masked) {
uint8_t flag = masked ? 0x80u : 0x00u;
if (len < 126u) {
out.push_back(static_cast<uint8_t>(len) | flag);
} else if (len < 65536u) {
out.push_back(126u | flag);
out.push_back(static_cast<uint8_t>((len >> 8) & 0xFFu));
out.push_back(static_cast<uint8_t>(len & 0xFFu));
} else {
out.push_back(127u | flag);
for (int i = 7; i >= 0; --i) {
out.push_back(static_cast<uint8_t>((len >> (i * 8)) & 0xFFu));
}
}
}
} // namespace
std::vector<uint8_t> FrameSerializer::frame(bool fin, Opcode opcode,
const uint8_t* payload,
std::size_t len) {
std::vector<uint8_t> out;
out.reserve(10 + len);
out.push_back((fin ? 0x80u : 0x00u) |
static_cast<std::uint8_t>(opcode));
append_length(out, len, false);
out.insert(out.end(), payload, payload + len);
return out;
}
std::vector<uint8_t> FrameSerializer::frame(
bool fin, Opcode opcode, const std::vector<uint8_t>& payload) {
return frame(fin, opcode, payload.data(), payload.size());
}
std::vector<uint8_t> FrameSerializer::text(const std::string& text) {
return frame(true, Opcode::kText,
reinterpret_cast<const uint8_t*>(text.data()), text.size());
}
std::vector<uint8_t> FrameSerializer::binary(
const std::vector<uint8_t>& payload) {
return frame(true, Opcode::kBinary, payload);
}
std::vector<uint8_t> FrameSerializer::masked_frame(
bool fin, Opcode opcode, const uint8_t* payload, std::size_t len,
const uint8_t mask[4]) {
std::vector<uint8_t> out;
out.reserve(14 + len);
out.push_back((fin ? 0x80u : 0x00u) |
static_cast<std::uint8_t>(opcode));
append_length(out, len, true);
out.insert(out.end(), mask, mask + 4);
for (std::size_t i = 0; i < len; ++i) {
out.push_back(static_cast<uint8_t>(payload[i] ^ mask[i % 4]));
}
return out;
}
std::vector<uint8_t> FrameSerializer::close_frame(CloseCode code,
const std::string& reason) {
std::vector<uint8_t> body;
auto raw = static_cast<std::uint16_t>(code);
body.push_back(static_cast<uint8_t>((raw >> 8) & 0xFFu));
body.push_back(static_cast<uint8_t>(raw & 0xFFu));
std::size_t room = 125 - body.size();
std::size_t take = reason.size() < room ? reason.size() : room;
body.insert(body.end(), reason.begin(), reason.begin() + take);
return frame(true, Opcode::kClose, body);
}
std::vector<uint8_t> FrameSerializer::ping(
const std::vector<uint8_t>& payload) {
std::size_t take = payload.size() < 125 ? payload.size() : 125;
return frame(true, Opcode::kPing, payload.data(), take);
}
std::vector<uint8_t> FrameSerializer::pong(
const std::vector<uint8_t>& payload) {
std::size_t take = payload.size() < 125 ? payload.size() : 125;
return frame(true, Opcode::kPong, payload.data(), take);
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,40 @@
#pragma once
// WebSocket frame serializer (RFC 6455 section 5). Server-side
// frames are never masked (rule 2). Client-side masking lives in
// the websocket client, which uses with_mask().
#include <cstdint>
#include <string>
#include <vector>
#include "realtime/websocket/server/opcode.h"
namespace molo::realtime::websocket::server {
class FrameSerializer {
public:
// Serializes one frame without masking.
static std::vector<uint8_t> frame(bool fin, Opcode opcode,
const uint8_t* payload, std::size_t len);
static std::vector<uint8_t> frame(bool fin, Opcode opcode,
const std::vector<uint8_t>& payload);
static std::vector<uint8_t> text(const std::string& text);
static std::vector<uint8_t> binary(const std::vector<uint8_t>& payload);
// Serializes one masked frame (client to server) with the given
// 4-byte mask key.
static std::vector<uint8_t> masked_frame(bool fin, Opcode opcode,
const uint8_t* payload,
std::size_t len,
const uint8_t mask[4]);
// Close frame body: 2-byte big-endian code plus UTF-8 reason,
// truncated to 125 bytes total.
static std::vector<uint8_t> close_frame(CloseCode code,
const std::string& reason);
static std::vector<uint8_t> ping(const std::vector<uint8_t>& payload);
static std::vector<uint8_t> pong(const std::vector<uint8_t>& payload);
};
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,94 @@
// Opening handshake validation. See handshake_validator.h.
#include "realtime/websocket/server/handshake_validator.h"
#include "realtime/shared/base64.h"
#include "realtime/shared/realtime_metrics.h"
#include "realtime/shared/sha1.h"
namespace molo::realtime::websocket::server {
namespace {
constexpr char kGuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
HandshakeResult fail(const std::string& reason) {
HandshakeResult r;
r.ok = false;
r.failure_reason = reason;
r.response.status = 400;
shared::set_header(r.response, "Content-Type", "text/plain");
r.response.body = "Bad Request: " + reason;
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kHandshakeFailures);
return r;
}
} // namespace
HandshakeValidator::HandshakeValidator(HandshakeConfig config)
: config_(std::move(config)) {}
std::string HandshakeValidator::accept_for(const std::string& key) {
shared::Sha1::Digest d = shared::Sha1::hash(key + kGuid);
return shared::base64_encode(d.data(), d.size());
}
HandshakeResult HandshakeValidator::validate(
const shared::HttpRequest& req) const {
if (req.method != "GET") {
return fail("WebSocket handshake requires GET");
}
if (!shared::header_has_token(shared::header_first(req, "Upgrade"),
"websocket")) {
return fail("missing Upgrade: websocket");
}
if (!shared::header_has_token(shared::header_first(req, "Connection"),
"Upgrade")) {
return fail("missing Connection: Upgrade");
}
std::string key = shared::header_first(req, "Sec-WebSocket-Key");
if (key.empty()) {
return fail("missing Sec-WebSocket-Key");
}
auto raw = shared::base64_decode(key);
if (!raw.has_value() || raw->size() != 16) {
return fail("Sec-WebSocket-Key must decode to 16 bytes");
}
std::string version = shared::header_first(req, "Sec-WebSocket-Version");
if (!version.empty() && version != "13") {
HandshakeResult r = fail("unsupported Sec-WebSocket-Version");
shared::set_header(r.response, "Sec-WebSocket-Version", "13");
return r;
}
std::string picked;
std::string asked = shared::header_first(req, "Sec-WebSocket-Protocol");
if (!asked.empty()) {
bool found = false;
for (const std::string& offered : config_.subprotocols) {
if (shared::header_has_token(asked, offered)) {
picked = offered;
found = true;
break;
}
}
if (!found && (config_.require_subprotocol ||
!config_.subprotocols.empty())) {
return fail("no supported Sec-WebSocket-Protocol");
}
} else if (config_.require_subprotocol) {
return fail("Sec-WebSocket-Protocol required");
}
HandshakeResult r;
r.ok = true;
r.accept_key = accept_for(key);
r.subprotocol = picked;
r.response.status = 101;
shared::set_header(r.response, "Upgrade", "websocket");
shared::set_header(r.response, "Connection", "Upgrade");
shared::set_header(r.response, "Sec-WebSocket-Accept", r.accept_key);
if (!picked.empty()) {
shared::set_header(r.response, "Sec-WebSocket-Protocol", picked);
}
return r;
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,46 @@
#pragma once
// Opening handshake validation per RFC 6455 section 4. Requires
// Upgrade/Connection headers and a 16-byte Sec-WebSocket-Key, picks
// at most one subprotocol, and builds the 101 response with the
// accept hash. Pure function of request plus config: no I/O.
#include <optional>
#include <string>
#include <vector>
#include "realtime/shared/http_seam.h"
namespace molo::realtime::websocket::server {
struct HandshakeConfig {
// Subprotocols the server offers, in preference order. Empty
// means the server speaks no subprotocol: a request asking for
// one is still accepted when require_subprotocol is false, with
// no protocol echoed.
std::vector<std::string> subprotocols;
bool require_subprotocol = false;
};
struct HandshakeResult {
bool ok = false;
shared::HttpResponse response;
std::string accept_key;
std::string subprotocol;
std::string failure_reason;
};
class HandshakeValidator {
public:
explicit HandshakeValidator(HandshakeConfig config = HandshakeConfig{});
HandshakeResult validate(const shared::HttpRequest& req) const;
// base64(SHA-1(key + GUID)) per RFC 6455 section 1.3.
static std::string accept_for(const std::string& key);
private:
HandshakeConfig config_;
};
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,48 @@
// Application heartbeat. See heartbeat_manager.h.
#include "realtime/websocket/server/heartbeat_manager.h"
#include "realtime/shared/realtime_metrics.h"
namespace molo::realtime::websocket::server {
HeartbeatManager::HeartbeatManager(std::chrono::milliseconds interval,
std::chrono::milliseconds timeout)
: interval_(interval), timeout_(timeout) {}
void HeartbeatManager::start(std::chrono::steady_clock::time_point now) {
if (started_) {
return;
}
started_ = true;
last_activity_ = now;
next_ping_ = now + interval_;
}
void HeartbeatManager::note_activity(std::chrono::steady_clock::time_point now) {
last_activity_ = now;
}
bool HeartbeatManager::tick(std::chrono::steady_clock::time_point now) {
if (!started_ || timed_out_) {
return !timed_out_;
}
if (now - last_activity_ >= timeout_) {
timed_out_ = true;
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kHeartbeatTimeouts);
if (timeout_fn_) {
timeout_fn_();
}
return false;
}
if (now >= next_ping_) {
next_ping_ = now + interval_;
if (ping_fn_) {
ping_fn_();
}
}
return true;
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,49 @@
#pragma once
// Application heartbeat for one connection. Sends pings every
// interval; when no frame at all arrives within the pong timeout the
// peer is dead and the manager closes it with 1001. The runtime
// calls tick(now) from its timer wheel; any inbound frame should
// call note_activity().
#include <chrono>
#include <cstdint>
#include <functional>
#include "realtime/shared/caps.h"
namespace molo::realtime::websocket::server {
class HeartbeatManager {
public:
using PingFn = std::function<void()>;
using TimeoutFn = std::function<void()>;
explicit HeartbeatManager(
std::chrono::milliseconds interval = shared::Caps::kPingInterval,
std::chrono::milliseconds timeout = shared::Caps::kPongTimeout);
void on_ping(PingFn fn) { ping_fn_ = std::move(fn); }
void on_timeout(TimeoutFn fn) { timeout_fn_ = std::move(fn); }
// Starts the schedule at now. Idempotent.
void start(std::chrono::steady_clock::time_point now);
// Any inbound frame resets the dead-peer deadline.
void note_activity(std::chrono::steady_clock::time_point now);
// Fires due pings; fires the timeout callback once when the peer
// is silent past the deadline. Returns false after timeout.
bool tick(std::chrono::steady_clock::time_point now);
bool timed_out() const { return timed_out_; }
private:
std::chrono::milliseconds interval_;
std::chrono::milliseconds timeout_;
PingFn ping_fn_;
TimeoutFn timeout_fn_;
std::chrono::steady_clock::time_point last_activity_;
std::chrono::steady_clock::time_point next_ping_;
bool started_ = false;
bool timed_out_ = false;
};
} // namespace molo::realtime::websocket::server
+40
View File
@@ -0,0 +1,40 @@
#pragma once
// WebSocket opcodes and close codes per RFC 6455 sections 5.2 and
// 7.4. One enum header shared by parser, serializer, views and
// clients so codes stay consistent.
#include <cstdint>
namespace molo::realtime::websocket::server {
enum class Opcode : std::uint8_t {
kContinuation = 0x0,
kText = 0x1,
kBinary = 0x2,
kClose = 0x8,
kPing = 0x9,
kPong = 0xA,
};
inline bool is_control(Opcode op) {
return static_cast<std::uint8_t>(op) >= 0x8u;
}
inline bool is_data(Opcode op) {
return op == Opcode::kText || op == Opcode::kBinary ||
op == Opcode::kContinuation;
}
enum class CloseCode : std::uint16_t {
kNormal = 1000,
kGoingAway = 1001,
kProtocolError = 1002,
kUnsupportedData = 1003,
kBadUtf8 = 1007,
kPolicyViolation = 1008,
kMessageTooBig = 1009,
kInternalError = 1011,
};
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,21 @@
// WebSocket handler base. See websocket_handler.h.
#include "realtime/websocket/server/websocket_handler.h"
namespace molo::realtime::websocket::server {
bool WebSocketHandler::send_text(const std::string& text) {
return connection_ != nullptr && connection_->send_text(text);
}
bool WebSocketHandler::send_binary(const std::vector<uint8_t>& payload) {
return connection_ != nullptr && connection_->send_binary(payload);
}
void WebSocketHandler::close(CloseCode code, const std::string& reason) {
if (connection_ != nullptr) {
connection_->close(code, reason);
}
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,46 @@
#pragma once
// Base class for WebSocket endpoint logic. Users subclass and
// override on_text / on_binary / on_open / on_close. The handler
// never touches sockets: it sends through the connection, which the
// runtime binds after the handshake. Routers mount WebSocketView,
// which owns one handler per connection.
#include <cstdint>
#include <string>
#include <vector>
#include "realtime/websocket/server/websocket_response.h"
namespace molo::realtime::websocket::server {
class WebSocketHandler {
public:
virtual ~WebSocketHandler() = default;
virtual void on_open() {}
virtual void on_text(const std::string& message) {
(void)message;
}
virtual void on_binary(const std::vector<uint8_t>& payload) {
(void)payload;
}
virtual void on_close(std::uint16_t code, const std::string& reason) {
(void)code;
(void)reason;
}
// Bound by the view before on_open. Null until then.
WebSocketConnection* connection() { return connection_; }
protected:
bool send_text(const std::string& text);
bool send_binary(const std::vector<uint8_t>& payload);
void close(CloseCode code, const std::string& reason);
private:
friend class WebSocketView;
WebSocketConnection* connection_ = nullptr;
};
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,234 @@
// WebSocket connection and 101 response. See websocket_response.h.
#include "realtime/websocket/server/websocket_response.h"
#include "realtime/shared/realtime_log.h"
#include "realtime/shared/realtime_metrics.h"
#include "realtime/shared/utf8.h"
#include "realtime/websocket/server/frame_serializer.h"
namespace molo::realtime::websocket::server {
WebSocketConnection::WebSocketConnection(shared::ITransport* transport,
shared::ConnectionContext context,
WebSocketConfig config)
: transport_(transport),
context_(std::move(context)),
config_(config),
parser_(true),
send_queue_(config.send_queue_depth, config.shed_policy) {
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kConnectionsOpened);
}
bool WebSocketConnection::on_bytes(const uint8_t* data, std::size_t len) {
shared::RealtimeMetrics::instance().inc(shared::RealtimeMetric::kBytesReceived,
len);
std::size_t off = 0;
while (off < len && state_ != State::kClosed) {
std::size_t consumed = 0;
ParseStep step = parser_.feed(data + off, len - off, consumed);
off += consumed;
if (step.outcome == ParseOutcome::kNeedMore) {
break;
}
if (step.outcome == ParseOutcome::kFailed) {
fail(step.fail_code, step.fail_reason);
return false;
}
handle_frame(step.frame);
}
return state_ != State::kClosed;
}
bool WebSocketConnection::send_text(const std::string& text) {
shared::SendItem item;
item.is_text = true;
item.bytes.assign(text.begin(), text.end());
return send_queue_.push(std::move(item));
}
bool WebSocketConnection::send_binary(const std::vector<uint8_t>& payload) {
shared::SendItem item;
item.is_text = false;
item.bytes = payload;
return send_queue_.push(std::move(item));
}
bool WebSocketConnection::flush() {
shared::SendItem item;
while (send_queue_.pop(item)) {
std::vector<uint8_t> wire =
item.is_text ? FrameSerializer::frame(
true, Opcode::kText, item.bytes.data(),
item.bytes.size())
: FrameSerializer::frame(
true, Opcode::kBinary, item.bytes.data(),
item.bytes.size());
if (!transport_->send(wire)) {
send_queue_.close();
finish_close(static_cast<std::uint16_t>(CloseCode::kGoingAway),
"transport failed");
return false;
}
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kMessagesSent);
shared::RealtimeMetrics::instance().inc(shared::RealtimeMetric::kBytesSent,
wire.size());
}
if (send_queue_.must_close()) {
send_queue_.clear_must_close();
close(CloseCode::kPolicyViolation, "send queue full");
return false;
}
return state_ != State::kClosed;
}
void WebSocketConnection::close(CloseCode code, const std::string& reason) {
if (state_ != State::kOpen) {
return;
}
state_ = State::kClosing;
transport_->send(FrameSerializer::close_frame(code, reason));
finish_close(static_cast<std::uint16_t>(code), reason);
}
void WebSocketConnection::handle_frame(const Frame& frame) {
switch (frame.opcode) {
case Opcode::kPing: {
transport_->send(FrameSerializer::pong(frame.payload));
if (ping_cb_) {
ping_cb_();
}
return;
}
case Opcode::kPong:
return;
case Opcode::kClose: {
std::uint16_t code =
static_cast<std::uint16_t>(CloseCode::kNormal);
std::string reason;
if (frame.payload.size() == 1) {
fail(CloseCode::kProtocolError, "close body of 1 byte");
return;
}
if (frame.payload.size() >= 2) {
code = static_cast<std::uint16_t>((frame.payload[0] << 8) |
frame.payload[1]);
reason.assign(frame.payload.begin() + 2, frame.payload.end());
if (!shared::is_valid_utf8(reason)) {
fail(CloseCode::kBadUtf8, "close reason is not UTF-8");
return;
}
}
if (state_ == State::kOpen) {
state_ = State::kClosing;
transport_->send(FrameSerializer::close_frame(
static_cast<CloseCode>(code), reason));
}
finish_close(code, reason);
return;
}
default:
break;
}
// Data frames: reassembly with caps.
if (frame.opcode == Opcode::kText || frame.opcode == Opcode::kBinary) {
if (in_message_) {
fail(CloseCode::kProtocolError, "new message before FIN");
return;
}
if (!frame.fin) {
in_message_ = true;
message_is_text_ = frame.opcode == Opcode::kText;
message_buf_ = frame.payload;
message_frames_ = 1;
if (message_buf_.size() > config_.max_message_bytes) {
fail(CloseCode::kMessageTooBig, "message over cap");
}
return;
}
if (frame.opcode == Opcode::kText &&
!shared::is_valid_utf8(frame.payload.data(),
frame.payload.size())) {
fail(CloseCode::kBadUtf8, "text frame is not UTF-8");
return;
}
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kMessagesReceived);
if (message_cb_) {
message_cb_(frame.opcode == Opcode::kText, frame.payload);
}
return;
}
// Continuation.
if (!in_message_) {
fail(CloseCode::kProtocolError, "stray continuation");
return;
}
++message_frames_;
if (message_frames_ > config_.max_frames_per_message) {
fail(CloseCode::kProtocolError, "too many frames per message");
return;
}
if (message_buf_.size() + frame.payload.size() > config_.max_message_bytes) {
fail(CloseCode::kMessageTooBig, "message over cap");
return;
}
message_buf_.insert(message_buf_.end(), frame.payload.begin(),
frame.payload.end());
if (frame.fin) {
in_message_ = false;
if (message_is_text_ &&
!shared::is_valid_utf8(message_buf_.data(), message_buf_.size())) {
fail(CloseCode::kBadUtf8, "text message is not UTF-8");
return;
}
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kMessagesReceived);
if (message_cb_) {
message_cb_(message_is_text_, message_buf_);
}
message_buf_.clear();
message_buf_.shrink_to_fit();
}
}
void WebSocketConnection::fail(CloseCode code, const std::string& reason) {
shared::RealtimeLog::warn("websocket", context_.correlation_id,
"protocol failure: " + reason);
if (state_ == State::kOpen) {
state_ = State::kClosing;
transport_->send(FrameSerializer::close_frame(code, reason));
}
finish_close(static_cast<std::uint16_t>(code), reason);
}
void WebSocketConnection::finish_close(std::uint16_t code,
const std::string& reason) {
if (state_ == State::kClosed) {
return;
}
state_ = State::kClosed;
send_queue_.close();
shared::RealtimeMetrics::instance().inc(
shared::RealtimeMetric::kConnectionsClosed);
if (close_cb_) {
close_cb_(code, reason);
}
}
shared::HttpResponse WebSocketResponse::switching_protocols(
const std::string& accept_key, const std::string& subprotocol) {
shared::HttpResponse res;
res.status = 101;
shared::set_header(res, "Upgrade", "websocket");
shared::set_header(res, "Connection", "Upgrade");
shared::set_header(res, "Sec-WebSocket-Accept", accept_key);
if (!subprotocol.empty()) {
shared::set_header(res, "Sec-WebSocket-Protocol", subprotocol);
}
return res;
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,103 @@
#pragma once
// The 101 upgrade response plus the live connection it opens. The
// response carries handshake headers; open() binds a transport and a
// context and returns the connection that pumps bytes. Message
// reassembly, UTF-8 checks and control-frame handling live here so
// handlers only see complete messages.
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
#include "realtime/shared/caps.h"
#include "realtime/shared/connection_context.h"
#include "realtime/shared/http_seam.h"
#include "realtime/shared/send_queue.h"
#include "realtime/shared/transport.h"
#include "realtime/websocket/server/frame_parser.h"
#include "realtime/websocket/server/opcode.h"
namespace molo::realtime::websocket::server {
struct WebSocketConfig {
std::size_t max_message_bytes = shared::Caps::kMaxMessageBytes;
std::size_t max_frames_per_message = shared::Caps::kMaxFramesPerMessage;
std::size_t send_queue_depth = shared::Caps::kSendQueueDepth;
shared::ShedPolicy shed_policy = shared::ShedPolicy::kDropOldest;
};
class WebSocketConnection {
public:
using MessageCallback =
std::function<void(bool is_text, const std::vector<uint8_t>& payload)>;
using CloseCallback =
std::function<void(std::uint16_t code, const std::string& reason)>;
WebSocketConnection(shared::ITransport* transport,
shared::ConnectionContext context,
WebSocketConfig config = WebSocketConfig{});
WebSocketConnection(const WebSocketConnection&) = delete;
WebSocketConnection& operator=(const WebSocketConnection&) = delete;
// Feeds peer bytes. Returns false when the connection failed and
// must be torn down (close frame already queued or sent).
bool on_bytes(const uint8_t* data, std::size_t len);
// Queues a text or binary message for the peer. Returns false when
// shed by policy.
bool send_text(const std::string& text);
bool send_binary(const std::vector<uint8_t>& payload);
// Flushes the send queue to the transport. Returns false when the
// transport failed or the close policy fired.
bool flush();
// Starts the closing handshake with the given code.
void close(CloseCode code, const std::string& reason);
bool open() const { return state_ == State::kOpen; }
bool closing() const { return state_ == State::kClosing; }
void on_message(MessageCallback cb) { message_cb_ = std::move(cb); }
void on_close(CloseCallback cb) { close_cb_ = std::move(cb); }
void on_ping(std::function<void()> cb) { ping_cb_ = std::move(cb); }
const shared::ConnectionContext& context() const { return context_; }
shared::SendQueue& send_queue() { return send_queue_; }
private:
enum class State : std::uint8_t { kOpen, kClosing, kClosed };
void handle_frame(const Frame& frame);
void fail(CloseCode code, const std::string& reason);
void finish_close(std::uint16_t code, const std::string& reason);
shared::ITransport* transport_;
shared::ConnectionContext context_;
WebSocketConfig config_;
FrameParser parser_;
shared::SendQueue send_queue_;
State state_ = State::kOpen;
// Reassembly buffer for fragmented messages.
std::vector<uint8_t> message_buf_;
bool message_is_text_ = false;
bool in_message_ = false;
std::size_t message_frames_ = 0;
MessageCallback message_cb_;
CloseCallback close_cb_;
std::function<void()> ping_cb_;
};
class WebSocketResponse {
public:
// Builds the 101 handshake response headers. The accept key comes
// from HandshakeValidator; this class only renders the response.
static shared::HttpResponse switching_protocols(
const std::string& accept_key, const std::string& subprotocol);
};
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,51 @@
// Router-mountable WebSocket view. See websocket_view.h.
#include "realtime/websocket/server/websocket_view.h"
#include "realtime/shared/realtime_log.h"
namespace molo::realtime::websocket::server {
WebSocketView::WebSocketView(HandlerFactory factory, HandshakeConfig handshake,
WebSocketConfig socket)
: factory_(std::move(factory)),
validator_(std::move(handshake)),
socket_config_(socket) {}
WebSocketView::Admit WebSocketView::admit(
const shared::HttpRequest& req) const {
HandshakeResult r = validator_.validate(req);
Admit admit;
admit.ok = r.ok;
admit.response = r.response;
admit.subprotocol = r.subprotocol;
admit.failure_reason = r.failure_reason;
return admit;
}
WebSocketConnection* WebSocketView::accept(shared::ITransport* transport,
shared::ConnectionContext context) {
auto handler = factory_();
auto conn = std::make_unique<WebSocketConnection>(transport, context,
socket_config_);
WebSocketConnection* raw = conn.get();
handler->connection_ = raw;
WebSocketHandler* h = handler.get();
raw->on_message([h](bool is_text, const std::vector<uint8_t>& payload) {
if (is_text) {
h->on_text(std::string(payload.begin(), payload.end()));
} else {
h->on_binary(payload);
}
});
raw->on_close([h](std::uint16_t code, const std::string& reason) {
h->on_close(code, reason);
});
connections_.push_back(Entry{std::move(handler), std::move(conn)});
shared::RealtimeLog::info("websocket", context.correlation_id,
"open route=" + context.route);
h->on_open();
return raw;
}
} // namespace molo::realtime::websocket::server
@@ -0,0 +1,58 @@
#pragma once
// Router-mountable WebSocket endpoint. The view runs the handshake
// (after middleware, auth and session per rule 1), answers 101, and
// binds one handler plus one connection per upgrade. Factories keep
// handler construction in user code.
#include <functional>
#include <memory>
#include <vector>
#include "realtime/shared/connection_context.h"
#include "realtime/shared/http_seam.h"
#include "realtime/shared/transport.h"
#include "realtime/websocket/server/handshake_validator.h"
#include "realtime/websocket/server/websocket_handler.h"
#include "realtime/websocket/server/websocket_response.h"
namespace molo::realtime::websocket::server {
class WebSocketView {
public:
using HandlerFactory = std::function<std::unique_ptr<WebSocketHandler>()>;
explicit WebSocketView(HandlerFactory factory,
HandshakeConfig handshake = HandshakeConfig{},
WebSocketConfig socket = WebSocketConfig{});
// Runs the handshake. On success returns ok=true with the 101
// response; the caller then passes the live transport to
// accept(). On failure returns the 4xx response to send.
struct Admit {
bool ok = false;
shared::HttpResponse response;
std::string subprotocol;
std::string failure_reason;
};
Admit admit(const shared::HttpRequest& req) const;
// Binds transport plus context, wires a fresh handler, and fires
// on_open. The view owns both for the life of the connection.
WebSocketConnection* accept(shared::ITransport* transport,
shared::ConnectionContext context);
std::size_t open_connections() const { return connections_.size(); }
private:
HandlerFactory factory_;
HandshakeValidator validator_;
WebSocketConfig socket_config_;
struct Entry {
std::unique_ptr<WebSocketHandler> handler;
std::unique_ptr<WebSocketConnection> connection;
};
std::vector<Entry> connections_;
};
} // namespace molo::realtime::websocket::server