1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2016 Realm Inc.
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
17 ////////////////////////////////////////////////////////////////////////////
19 #ifndef REALM_OS_SYNC_CLIENT_HPP
20 #define REALM_OS_SYNC_CLIENT_HPP
22 #include "binding_callback_thread_observer.hpp"
24 #include <realm/sync/client.hpp>
25 #include <realm/util/scope_exit.hpp>
29 #include "sync/sync_manager.hpp"
30 #include "sync/impl/network_reachability.hpp"
32 #if NETWORK_REACHABILITY_AVAILABLE
33 #include "sync/impl/apple/network_reachability_observer.hpp"
39 using ReconnectMode = sync::Client::ReconnectMode;
42 SyncClient(std::unique_ptr<util::Logger> logger, ReconnectMode reconnect_mode, bool multiplex_sessions)
43 : m_client(make_client(*logger, reconnect_mode, multiplex_sessions)) // Throws
44 , m_logger(std::move(logger))
46 if (g_binding_callback_thread_observer) {
47 g_binding_callback_thread_observer->did_create_thread();
48 auto will_destroy_thread = util::make_scope_exit([&]() noexcept {
49 g_binding_callback_thread_observer->will_destroy_thread();
52 m_client.run(); // Throws
54 catch (std::exception const& e) {
55 g_binding_callback_thread_observer->handle_error(e);
59 m_client.run(); // Throws
62 #if NETWORK_REACHABILITY_AVAILABLE
63 , m_reachability_observer(none, [=](const NetworkReachabilityStatus status) {
64 if (status != NotReachable)
65 SyncManager::shared().reconnect();
68 if (!m_reachability_observer.start_observing())
69 m_logger->error("Failed to set up network reachability observer");
76 void cancel_reconnect_delay() {
77 m_client.cancel_reconnect_delay();
83 if (m_thread.joinable())
87 std::unique_ptr<sync::Session> make_session(std::string path, sync::Session::Config config)
89 return std::make_unique<sync::Session>(m_client, std::move(path), std::move(config));
99 static sync::Client make_client(util::Logger& logger, ReconnectMode reconnect_mode, bool multiplex_sessions)
101 sync::Client::Config config;
102 config.logger = &logger;
103 config.reconnect_mode = std::move(reconnect_mode);
104 config.one_connection_per_session = !multiplex_sessions;
105 return sync::Client(std::move(config)); // Throws
108 sync::Client m_client;
109 const std::unique_ptr<util::Logger> m_logger;
110 std::thread m_thread;
111 #if NETWORK_REACHABILITY_AVAILABLE
112 NetworkReachabilityObserver m_reachability_observer;
119 #endif // REALM_OS_SYNC_CLIENT_HPP