#include "mologram/Connection.hpp"
#include <cerrno>
#include <sys/socket.h>
#include "mologram/SocketUtil.hpp"
namespace mologram {
Connection::Connection(Fd fd, ITelegramService& service, DaemonStats& stats, std::function<void()> wake)
: fd_(std::move(fd)), service_(service), stats_(stats), wake_(std::move(wake)) {
SocketUtil::setNonBlocking(fd_.get());
stats_.connections++;
}
Connection::~Connection() { cancelAll(); }
void Connection::send(const js::Value& frame) {
{
std::lock_guard<std::mutex> g(mutex_);
if (closing_) return;
out_ += FrameCodec::encode(frame);
}
wake_();
}
bool Connection::wantsWrite() {
std::lock_guard<std::mutex> g(mutex_);
return !out_.empty();
}
bool Connection::onWritable() {
std::lock_guard<std::mutex> g(mutex_);
while (!out_.empty()) {
ssize_t n = ::send(fd_.get(), out_.data(), out_.size(), MSG_NOSIGNAL);
if (n < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) return true; if (errno == EINTR) continue; return false; }
out_.erase(0, (size_t)n);
}
return !closing_;
}
bool Connection::onReadable() {
char buf[65536];
for (;;) {
ssize_t n = ::recv(fd_.get(), buf, sizeof(buf), 0);
if (n == 0) return false;
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (errno == EINTR) continue;
return false;
}
reader_.feed(buf, (size_t)n);
}
for (;;) {
js::Value frame;
auto st = reader_.next(frame);
if (st == FrameReader::Status::NeedMore) return true;
if (st == FrameReader::Status::BadFrame) {
stats_.rejectedFrames++;
js::Object o;
o["v"] = js::Value(Wire::kVersion); o["ok"] = js::Value(false); o["id"] = js::id(0);
o["e"] = RpcError{ErrorCode::BadFrame, reader_.error()}.toJson();
std::string bytes = FrameCodec::encode(js::Value(std::move(o)));
::send(fd_.get(), bytes.data(), bytes.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
return false;
}
handle(frame);
if (closing_) return false;
}
}
void Connection::handle(const js::Value& frame) {
Wire::Incoming in;
RpcError err;
if (!Wire::parse(frame, in, err)) {
if (err.code == ErrorCode::BadVersion) stats_.badVersion++; else stats_.rejectedFrames++;
std::string bytes = FrameCodec::encode(Wire::response(0, RpcResult::failure(err.code, err.text)));
::send(fd_.get(), bytes.data(), bytes.size(), MSG_NOSIGNAL | MSG_DONTWAIT); // flush now: the connection closes right after
std::lock_guard<std::mutex> g(mutex_);
closing_ = true;
return;
}
if (in.kind == Wire::Kind::Cancel) {
std::lock_guard<std::mutex> g(mutex_);
auto it = inflight_.find(in.id);
if (it != inflight_.end()) service_.cancel(it->second);
return;
}
if (in.kind != Wire::Kind::Request) {
stats_.rejectedFrames++;
send(Wire::response(0, RpcResult::failure(ErrorCode::BadFrame, "only requests and cancels are accepted from a UI process")));
return;
}
stats_.requests++;
requested_ = true;
std::weak_ptr<Connection> weak = weak_from_this();
RequestId clientId = in.id;
auto done = std::make_shared<std::atomic<bool>>(false);
RequestId svc = service_.call(in.method, in.params, [weak, clientId, done](const RpcResult& r) {
if (auto self = weak.lock()) {
{ std::lock_guard<std::mutex> g(self->mutex_); done->store(true); self->inflight_.erase(clientId); }
self->send(Wire::response(clientId, r));
}
});
std::lock_guard<std::mutex> g(mutex_);
if (!done->load()) inflight_[clientId] = svc; // a reply that ran inline has nothing left to cancel
}
void Connection::cancelAll() {
std::map<RequestId, RequestId> copy;
{
std::lock_guard<std::mutex> g(mutex_);
copy.swap(inflight_);
closing_ = true;
}
for (auto& kv : copy) service_.cancel(kv.second);
}
} // namespace mologram