realm-js/src/rpc.hpp

90 lines
2.5 KiB
C++
Raw Normal View History

2016-02-18 19:59:34 +00:00
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
2015-10-22 17:44:10 +00:00
#pragma once
#include <functional>
#include <future>
#include <thread>
#include "concurrent_deque.hpp"
2015-12-01 22:44:09 +00:00
#include "json.hpp"
2016-04-12 21:42:05 +00:00
#include "jsc_types.hpp"
#include "jsc_protected.hpp"
2015-10-22 17:44:10 +00:00
namespace realm {
2016-04-12 21:42:05 +00:00
class ObjectSchema;
namespace rpc {
2015-10-22 17:44:10 +00:00
using json = nlohmann::json;
2015-10-22 17:44:10 +00:00
using RPCObjectID = u_int64_t;
using RPCRequest = std::function<json(const json)>;
class RPCWorker {
public:
RPCWorker();
~RPCWorker();
void add_task(std::function<json()>);
json pop_task_result();
void try_run_task();
void stop();
private:
bool m_stop = false;
std::thread m_thread;
ConcurrentDeque<std::packaged_task<json()>> m_tasks;
ConcurrentDeque<std::future<json>> m_futures;
};
2015-10-22 17:44:10 +00:00
class RPCServer {
public:
RPCServer();
~RPCServer();
json perform_request(std::string name, const json &args);
2015-10-22 17:44:10 +00:00
private:
2015-10-23 00:59:05 +00:00
JSGlobalContextRef m_context;
std::mutex m_request_mutex;
2015-10-23 00:59:05 +00:00
std::map<std::string, RPCRequest> m_requests;
std::map<RPCObjectID, js::Protected<JSObjectRef>> m_objects;
std::map<RPCObjectID, js::Protected<JSObjectRef>> m_callbacks;
// The key here is the same as the value in m_callbacks. We use the raw pointer as a key here,
// because protecting the value in m_callbacks pins the function object and prevents it from being moved
// by the garbage collector upon compaction.
std::map<JSObjectRef, RPCObjectID> m_callback_ids;
ConcurrentDeque<json> m_callback_results;
2015-10-23 00:59:05 +00:00
RPCObjectID m_session_id;
RPCWorker m_worker;
static void run_callback(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], jsc::ReturnValue &);
2015-10-22 17:44:10 +00:00
RPCObjectID store_object(JSObjectRef object);
json serialize_json_value(JSValueRef value);
JSValueRef deserialize_json_value(const json dict);
2016-04-12 21:42:05 +00:00
json serialize_object_schema(const ObjectSchema &objectSchema);
2015-10-22 17:44:10 +00:00
};
2016-04-12 21:42:05 +00:00
} // rpc
} // realm