#include "mologram/TableService.hpp"
#include <algorithm>
#include <stdexcept>
namespace mologram {
void TableService::on(const std::string& method, Handler h) {
if (!ProtocolMethods::known(method)) throw std::logic_error("method not declared in SPEC: " + method);
handlers_[method] = std::move(h);
}
RequestId TableService::call(const std::string& method, const js::Value& params, Reply cb) {
RequestId id = next_++;
const MethodDef* def = ProtocolMethods::find(method);
auto it = handlers_.find(method);
if (!def || it == handlers_.end()) {
rejected_++;
cb(RpcResult::failure(ErrorCode::UnknownMethod, "unknown method: " + method));
return id;
}
if (!params.isObj() && !params.isNull()) {
rejected_++;
cb(RpcResult::failure(ErrorCode::BadParams, method + ": params must be an object"));
return id;
}
js::Value p = params.isNull() ? js::Value(js::Object{}) : params;
auto accepted = def->accepted();
for (const auto& kv : *p.asObj()) {
if (std::find(accepted.begin(), accepted.end(), kv.first) == accepted.end()) {
rejected_++;
cb(RpcResult::failure(ErrorCode::BadParams, method + ": unknown parameter " + kv.first));
return id;
}
}
for (const auto& r : def->required()) {
if (!p.find(r)) {
rejected_++;
cb(RpcResult::failure(ErrorCode::BadParams, method + ": missing parameter " + r));
return id;
}
}
auto flag = std::make_shared<std::atomic<bool>>(false);
{ std::lock_guard<std::mutex> g(cancelMutex_); flags_[id] = flag; }
Handler h = it->second;
execute([this, id, h, p, flag, cb, method]() {
RpcResult r = flag->load() ? RpcResult::failure(ErrorCode::Cancelled, "cancelled before start") : h(p, CancelFlag(flag));
onResult(method, r);
{ std::lock_guard<std::mutex> g(cancelMutex_); flags_.erase(id); }
cb(r);
});
return id;
}
void TableService::cancel(RequestId id) {
std::lock_guard<std::mutex> g(cancelMutex_);
auto it = flags_.find(id);
if (it != flags_.end()) it->second->store(true);
}
void TableService::cancelAll() {
std::lock_guard<std::mutex> g(cancelMutex_);
for (auto& kv : flags_) kv.second->store(true);
}
void TableService::addSink(IEventSink* sink) {
std::lock_guard<std::mutex> g(sinkMutex_);
if (std::find(sinks_.begin(), sinks_.end(), sink) == sinks_.end()) sinks_.push_back(sink);
}
void TableService::removeSink(IEventSink* sink) {
std::lock_guard<std::mutex> g(sinkMutex_);
sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end());
}
void TableService::emit(const Event& e) {
std::vector<IEventSink*> copy;
{ std::lock_guard<std::mutex> g(sinkMutex_); copy = sinks_; }
for (auto* s : copy) s->onEvent(e);
}
} // namespace mologram