Skip to content
Repos

mologram

C++ 2.2 KB69 lines Opens in site

Directory Raw Download

#include "mologram/Wire.hpp"

namespace mologram {

static js::Object base() {
  js::Object o;
  o["v"] = js::Value(Wire::kVersion);
  return o;
}

js::Value Wire::request(RequestId id, const std::string& method, const js::Value& params) {
  js::Object o = base();
  o["id"] = js::id((std::int64_t)id); o["m"] = js::Value(method); o["p"] = params;
  return js::Value(std::move(o));
}

js::Value Wire::response(RequestId id, const RpcResult& r) {
  js::Object o = base();
  o["id"] = js::id((std::int64_t)id); o["ok"] = js::Value(r.ok);
  if (r.ok) o["r"] = r.value; else o["e"] = r.error.toJson();
  return js::Value(std::move(o));
}

js::Value Wire::event(const Event& e) {
  js::Object o = base();
  o["ev"] = js::Value(e.name); o["d"] = e.data;
  return js::Value(std::move(o));
}

js::Value Wire::cancel(RequestId id) {
  js::Object o = base();
  o["cancel"] = js::id((std::int64_t)id);
  return js::Value(std::move(o));
}

bool Wire::parse(const js::Value& f, Incoming& out, RpcError& err) {
  const js::Value* v = f.find("v");
  if (!v || !v->isNum() || v->asInt() != kVersion) {
    err = {ErrorCode::BadVersion, "unsupported protocol version " + (v && v->isNum() ? std::to_string(v->asInt()) : std::string("(none)"))};
    return false;
  }
  if (f.find("cancel")) { out.kind = Kind::Cancel; out.id = (RequestId)js::getId(f, "cancel"); return true; }
  if (f.find("ev")) {
    out.kind = Kind::Event;
    out.event.name = js::getStr(f, "ev");
    if (const js::Value* d = f.find("d")) out.event.data = *d;
    return true;
  }
  if (f.find("m")) {
    out.kind = Kind::Request;
    out.id = (RequestId)js::getId(f, "id");
    out.method = js::getStr(f, "m");
    const js::Value* p = f.find("p");
    out.params = p ? *p : js::Value(js::Object{});
    return true;
  }
  if (f.find("ok")) {
    out.kind = Kind::Response;
    out.id = (RequestId)js::getId(f, "id");
    out.result.ok = js::getBool(f, "ok");
    if (out.result.ok) { if (const js::Value* r = f.find("r")) out.result.value = *r; }
    else if (const js::Value* e = f.find("e")) out.result.error = RpcError::fromJson(*e);
    return true;
  }
  err = {ErrorCode::BadFrame, "frame has no request, response, event or cancel"};
  return false;
}

} // namespace mologram
20.8ms