• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

realm / realm-core / 1786

28 Oct 2023 12:35PM UTC coverage: 91.562% (-0.02%) from 91.582%
1786

push

Evergreen

web-flow
Improve configurations for sanitized builds (#6911)

* Refactor sanitizer flags for different build types:

** Enable address sanitizer for msvc
** Allow to build with sanitizer for diffent optimized build (also Debug)
** Make RelASAN, RelTSAN, RelUSAN, RelUSAN just shortcuts for half-optimized builds

* Fix usage of moved object for fuzz tester
* Check asan/tsan on macos x64/arm64
* Check asan with msvc 2019
* Remove Jenkins sanitized builders replaced by evergreen configs
* Work-around stack-use-after-scope with msvc2019 and mpark
* Fix crash on check with staled ColKeys
* fix a buffer overrun in a test
* fix a race in async_open_realm test util
* Add some logger related test fixes
* Work around catch2 limmitation with not thread safe asserts and TSAN races
* Run multiprocesses tests under sanitizers
* add assert for an error reported by undefined sanitizer
* Workaround uv scheduler main thread only constraint for callbacks called from non main thread and requesting a realm

---------

Co-authored-by: James Stone <james.stone@mongodb.com>

94310 of 173648 branches covered (0.0%)

54 of 63 new or added lines in 15 files covered. (85.71%)

2212 existing lines in 52 files now uncovered.

230602 of 251853 relevant lines covered (91.56%)

6943670.77 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.46
/src/realm/sync/noinst/client_impl_base.cpp
1
#include <system_error>
2
#include <sstream>
3

4
#include <realm/util/assert.hpp>
5
#include <realm/util/safe_int_ops.hpp>
6
#include <realm/util/random.hpp>
7
#include <realm/util/memory_stream.hpp>
8
#include <realm/util/basic_system_errors.hpp>
9
#include <realm/util/scope_exit.hpp>
10
#include <realm/util/to_string.hpp>
11
#include <realm/util/uri.hpp>
12
#include <realm/util/platform_info.hpp>
13
#include <realm/sync/impl/clock.hpp>
14
#include <realm/impl/simulated_failure.hpp>
15
#include <realm/sync/network/http.hpp>
16
#include <realm/sync/network/websocket.hpp>
17
#include <realm/sync/noinst/client_history_impl.hpp>
18
#include <realm/sync/noinst/client_impl_base.hpp>
19
#include <realm/sync/noinst/compact_changesets.hpp>
20
#include <realm/sync/protocol.hpp>
21
#include <realm/version.hpp>
22
#include <realm/sync/changeset_parser.hpp>
23

24
#include <realm/sync/network/websocket.hpp> // Only for websocket::Error TODO remove
25

26
// NOTE: The protocol specification is in `/doc/protocol.md`
27

28
using namespace realm;
29
using namespace _impl;
30
using namespace realm::util;
31
using namespace realm::sync;
32
using namespace realm::sync::websocket;
33

34
// clang-format off
35
using Connection      = ClientImpl::Connection;
36
using Session         = ClientImpl::Session;
37
using UploadChangeset = ClientHistory::UploadChangeset;
38

39
// These are a work-around for a bug in MSVC. It cannot find in-class types
40
// mentioned in signature of out-of-line member function definitions.
41
using ConnectionTerminationReason = ClientImpl::ConnectionTerminationReason;
42
using OutputBuffer                = ClientImpl::OutputBuffer;
43
using ReceivedChangesets          = ClientProtocol::ReceivedChangesets;
44
// clang-format on
45

46
void ClientImpl::ReconnectInfo::reset() noexcept
47
{
1,800✔
48
    m_backoff_state.reset();
1,800✔
49
    scheduled_reset = false;
1,800✔
50
}
1,800✔
51

52

53
void ClientImpl::ReconnectInfo::update(ConnectionTerminationReason new_reason,
54
                                       std::optional<ResumptionDelayInfo> new_delay_info)
55
{
3,330✔
56
    m_backoff_state.update(new_reason, new_delay_info);
3,330✔
57
}
3,330✔
58

59

60
std::chrono::milliseconds ClientImpl::ReconnectInfo::delay_interval()
61
{
5,420✔
62
    if (scheduled_reset) {
5,420✔
63
        reset();
4✔
64
    }
4✔
65

2,856✔
66
    if (!m_backoff_state.triggering_error) {
5,420✔
67
        return std::chrono::milliseconds::zero();
4,164✔
68
    }
4,164✔
69

698✔
70
    switch (*m_backoff_state.triggering_error) {
1,256✔
71
        case ConnectionTerminationReason::closed_voluntarily:
80✔
72
            return std::chrono::milliseconds::zero();
80✔
73
        case ConnectionTerminationReason::server_said_do_not_reconnect:
18✔
74
            return std::chrono::milliseconds::max();
18✔
75
        default:
1,154✔
76
            if (m_reconnect_mode == ReconnectMode::testing) {
1,154✔
77
                return std::chrono::milliseconds::max();
930✔
78
            }
930✔
79

112✔
80
            REALM_ASSERT(m_reconnect_mode == ReconnectMode::normal);
224✔
81
            return m_backoff_state.delay_interval();
224✔
82
    }
1,256✔
83
}
1,256✔
84

85

86
bool ClientImpl::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
87
                                      port_type& port, std::string& path) const
88
{
3,334✔
89
    util::Uri uri(url); // Throws
3,334✔
90
    uri.canonicalize(); // Throws
3,334✔
91
    std::string userinfo, address_2, port_2;
3,334✔
92
    bool realm_scheme = (uri.get_scheme() == "realm:" || uri.get_scheme() == "realms:");
3,334✔
93
    bool ws_scheme = (uri.get_scheme() == "ws:" || uri.get_scheme() == "wss:");
3,334✔
94
    bool good = ((realm_scheme || ws_scheme) && uri.get_auth(userinfo, address_2, port_2) && userinfo.empty() &&
3,334✔
95
                 !address_2.empty() && uri.get_query().empty() && uri.get_frag().empty()); // Throws
3,334✔
96
    if (REALM_UNLIKELY(!good))
3,334✔
97
        return false;
1,492✔
98
    ProtocolEnvelope protocol_2;
3,334✔
99
    port_type port_3;
3,334✔
100
    if (realm_scheme) {
3,334✔
101
        if (uri.get_scheme() == "realm:") {
×
102
            protocol_2 = ProtocolEnvelope::realm;
×
103
            port_3 = (m_enable_default_port_hack ? 80 : 7800);
×
104
        }
×
105
        else {
×
106
            protocol_2 = ProtocolEnvelope::realms;
×
107
            port_3 = (m_enable_default_port_hack ? 443 : 7801);
×
108
        }
×
109
    }
×
110
    else {
3,334✔
111
        REALM_ASSERT(ws_scheme);
3,334✔
112
        if (uri.get_scheme() == "ws:") {
3,334✔
113
            protocol_2 = ProtocolEnvelope::ws;
3,330✔
114
            port_3 = 80;
3,330✔
115
        }
3,330✔
116
        else {
4✔
117
            protocol_2 = ProtocolEnvelope::wss;
4✔
118
            port_3 = 443;
4✔
119
        }
4✔
120
    }
3,334✔
121
    if (!port_2.empty()) {
3,334✔
122
        std::istringstream in(port_2);    // Throws
3,334✔
123
        in.imbue(std::locale::classic()); // Throws
3,334✔
124
        in >> port_3;
3,334✔
125
        if (REALM_UNLIKELY(!in || !in.eof() || port_3 < 1))
3,334✔
126
            return false;
1,492✔
127
    }
3,334✔
128
    std::string path_2 = uri.get_path(); // Throws (copy)
3,334✔
129

1,492✔
130
    protocol = protocol_2;
3,334✔
131
    address = std::move(address_2);
3,334✔
132
    port = port_3;
3,334✔
133
    path = std::move(path_2);
3,334✔
134
    return true;
3,334✔
135
}
3,334✔
136

137

138
ClientImpl::ClientImpl(ClientConfig config)
139
    : logger_ptr{config.logger ? std::move(config.logger) : util::Logger::get_default_logger()}
140
    , logger{*logger_ptr}
141
    , m_reconnect_mode{config.reconnect_mode}
142
    , m_connect_timeout{config.connect_timeout}
143
    , m_connection_linger_time{config.one_connection_per_session ? 0 : config.connection_linger_time}
144
    , m_ping_keepalive_period{config.ping_keepalive_period}
145
    , m_pong_keepalive_timeout{config.pong_keepalive_timeout}
146
    , m_fast_reconnect_limit{config.fast_reconnect_limit}
147
    , m_reconnect_backoff_info{config.reconnect_backoff_info}
148
    , m_disable_upload_activation_delay{config.disable_upload_activation_delay}
149
    , m_dry_run{config.dry_run}
150
    , m_enable_default_port_hack{config.enable_default_port_hack}
151
    , m_disable_upload_compaction{config.disable_upload_compaction}
152
    , m_fix_up_object_ids{config.fix_up_object_ids}
153
    , m_roundtrip_time_handler{std::move(config.roundtrip_time_handler)}
154
    , m_socket_provider{std::move(config.socket_provider)}
155
    , m_client_protocol{} // Throws
156
    , m_one_connection_per_session{config.one_connection_per_session}
157
    , m_random{}
158
{
8,974✔
159
    // FIXME: Would be better if seeding was up to the application.
4,418✔
160
    util::seed_prng_nondeterministically(m_random); // Throws
8,974✔
161

4,418✔
162
    logger.info("Realm sync client (%1)", REALM_VER_CHUNK); // Throws
8,974✔
163
    logger.debug("Supported protocol versions: %1-%2", get_oldest_supported_protocol_version(),
8,974✔
164
                 get_current_protocol_version()); // Throws
8,974✔
165
    logger.info("Platform: %1", util::get_platform_info());
8,974✔
166
    const char* build_mode;
8,974✔
167
#if REALM_DEBUG
8,974✔
168
    build_mode = "Debug";
8,974✔
169
#else
170
    build_mode = "Release";
171
#endif
172
    logger.debug("Build mode: %1", build_mode);
8,974✔
173
    logger.debug("Config param: one_connection_per_session = %1",
8,974✔
174
                 config.one_connection_per_session); // Throws
8,974✔
175
    logger.debug("Config param: connect_timeout = %1 ms",
8,974✔
176
                 config.connect_timeout); // Throws
8,974✔
177
    logger.debug("Config param: connection_linger_time = %1 ms",
8,974✔
178
                 config.connection_linger_time); // Throws
8,974✔
179
    logger.debug("Config param: ping_keepalive_period = %1 ms",
8,974✔
180
                 config.ping_keepalive_period); // Throws
8,974✔
181
    logger.debug("Config param: pong_keepalive_timeout = %1 ms",
8,974✔
182
                 config.pong_keepalive_timeout); // Throws
8,974✔
183
    logger.debug("Config param: fast_reconnect_limit = %1 ms",
8,974✔
184
                 config.fast_reconnect_limit); // Throws
8,974✔
185
    logger.debug("Config param: disable_upload_compaction = %1",
8,974✔
186
                 config.disable_upload_compaction); // Throws
8,974✔
187
    logger.debug("Config param: disable_sync_to_disk = %1",
8,974✔
188
                 config.disable_sync_to_disk); // Throws
8,974✔
189
    logger.debug("Config param: reconnect backoff info: max_delay: %1 ms, initial_delay: %2 ms, multiplier: %3",
8,974✔
190
                 m_reconnect_backoff_info.max_resumption_delay_interval.count(),
8,974✔
191
                 m_reconnect_backoff_info.resumption_delay_interval.count(),
8,974✔
192
                 m_reconnect_backoff_info.resumption_delay_backoff_multiplier);
8,974✔
193

4,418✔
194
    if (config.reconnect_mode != ReconnectMode::normal) {
8,974✔
195
        logger.warn("Testing/debugging feature 'nonnormal reconnect mode' enabled - "
772✔
196
                    "never do this in production!");
772✔
197
    }
772✔
198

4,418✔
199
    if (config.dry_run) {
8,974✔
UNCOV
200
        logger.warn("Testing/debugging feature 'dry run' enabled - "
×
UNCOV
201
                    "never do this in production!");
×
UNCOV
202
    }
×
203

4,418✔
204
    REALM_ASSERT_EX(m_socket_provider, "Must provide socket provider in sync Client config");
8,974✔
205

4,418✔
206
    if (m_one_connection_per_session) {
8,974✔
207
        // FIXME: Re-enable this warning when the load balancer is able to handle
2✔
208
        // multiplexing.
2✔
209
        //        logger.warn("Testing/debugging feature 'one connection per session' enabled - "
2✔
210
        //            "never do this in production");
2✔
211
    }
4✔
212

4,418✔
213
    if (config.disable_upload_activation_delay) {
8,974✔
214
        logger.warn("Testing/debugging feature 'disable_upload_activation_delay' enabled - "
×
215
                    "never do this in production");
×
UNCOV
216
    }
×
217

4,418✔
218
    if (config.disable_sync_to_disk) {
8,974✔
219
        logger.warn("Testing/debugging feature 'disable_sync_to_disk' enabled - "
×
UNCOV
220
                    "never do this in production");
×
221
    }
×
222

4,418✔
223
    m_actualize_and_finalize = create_trigger([this](Status status) {
14,562✔
224
        if (status == ErrorCodes::OperationAborted)
14,562✔
UNCOV
225
            return;
×
226
        else if (!status.is_ok())
14,562✔
UNCOV
227
            throw Exception(status);
×
228
        actualize_and_finalize_session_wrappers(); // Throws
14,562✔
229
    });
14,562✔
230
}
8,974✔
231

232

233
void ClientImpl::post(SyncSocketProvider::FunctionHandler&& handler)
234
{
160,318✔
235
    REALM_ASSERT(m_socket_provider);
160,318✔
236
    {
160,318✔
237
        std::lock_guard lock(m_drain_mutex);
160,318✔
238
        ++m_outstanding_posts;
160,318✔
239
        m_drained = false;
160,318✔
240
    }
160,318✔
241
    m_socket_provider->post([handler = std::move(handler), this](Status status) {
160,324✔
242
        auto decr_guard = util::make_scope_exit([&]() noexcept {
160,326✔
243
            std::lock_guard lock(m_drain_mutex);
160,320✔
244
            REALM_ASSERT(m_outstanding_posts);
160,320✔
245
            --m_outstanding_posts;
160,320✔
246
            m_drain_cv.notify_all();
160,320✔
247
        });
160,320✔
248
        handler(status);
160,324✔
249
    });
160,324✔
250
}
160,318✔
251

252

253
void ClientImpl::drain_connections()
254
{
8,974✔
255
    logger.debug("Draining connections during sync client shutdown");
8,974✔
256
    for (auto& server_slot_pair : m_server_slots) {
5,658✔
257
        auto& server_slot = server_slot_pair.second;
2,344✔
258

1,104✔
259
        if (server_slot.connection) {
2,344✔
260
            auto& conn = server_slot.connection;
2,242✔
261
            conn->force_close();
2,242✔
262
        }
2,242✔
263
        else {
102✔
264
            for (auto& conn_pair : server_slot.alt_connections) {
48✔
UNCOV
265
                conn_pair.second->force_close();
×
UNCOV
266
            }
×
267
        }
102✔
268
    }
2,344✔
269
}
8,974✔
270

271

272
SyncSocketProvider::SyncTimer ClientImpl::create_timer(std::chrono::milliseconds delay,
273
                                                       SyncSocketProvider::FunctionHandler&& handler)
274
{
16,238✔
275
    REALM_ASSERT(m_socket_provider);
16,238✔
276
    {
16,238✔
277
        std::lock_guard lock(m_drain_mutex);
16,238✔
278
        ++m_outstanding_posts;
16,238✔
279
        m_drained = false;
16,238✔
280
    }
16,238✔
281
    return m_socket_provider->create_timer(delay, [handler = std::move(handler), this](Status status) {
16,248✔
282
        handler(status);
16,244✔
283

8,036✔
284
        std::lock_guard lock(m_drain_mutex);
16,244✔
285
        REALM_ASSERT(m_outstanding_posts);
16,244✔
286
        --m_outstanding_posts;
16,244✔
287
        m_drain_cv.notify_all();
16,244✔
288
    });
16,244✔
289
}
16,238✔
290

291

292
ClientImpl::SyncTrigger ClientImpl::create_trigger(SyncSocketProvider::FunctionHandler&& handler)
293
{
11,430✔
294
    REALM_ASSERT(m_socket_provider);
11,430✔
295
    return std::make_unique<Trigger<ClientImpl>>(this, std::move(handler));
11,430✔
296
}
11,430✔
297

298
Connection::~Connection()
299
{
2,456✔
300
    if (m_websocket_sentinel) {
2,456✔
UNCOV
301
        m_websocket_sentinel->destroyed = true;
×
UNCOV
302
        m_websocket_sentinel.reset();
×
UNCOV
303
    }
×
304
}
2,456✔
305

306
void Connection::activate()
307
{
2,460✔
308
    REALM_ASSERT(m_on_idle);
2,460✔
309
    m_activated = true;
2,460✔
310
    if (m_num_active_sessions == 0)
2,460✔
UNCOV
311
        m_on_idle->trigger();
×
312
    // We cannot in general connect immediately, because a prior failure to
1,160✔
313
    // connect may require a delay before reconnecting (see `m_reconnect_info`).
1,160✔
314
    initiate_reconnect_wait(); // Throws
2,460✔
315
}
2,460✔
316

317

318
void Connection::activate_session(std::unique_ptr<Session> sess)
319
{
9,614✔
320
    REALM_ASSERT(sess);
9,614✔
321
    REALM_ASSERT(&sess->m_conn == this);
9,614✔
322
    REALM_ASSERT(!m_force_closed);
9,614✔
323
    Session& sess_2 = *sess;
9,614✔
324
    session_ident_type ident = sess->m_ident;
9,614✔
325
    auto p = m_sessions.emplace(ident, std::move(sess)); // Throws
9,614✔
326
    bool was_inserted = p.second;
9,614✔
327
    REALM_ASSERT(was_inserted);
9,614✔
328
    // Save the session ident to the historical list of session idents
4,632✔
329
    m_session_history.insert(ident);
9,614✔
330
    sess_2.activate(); // Throws
9,614✔
331
    if (m_state == ConnectionState::connected) {
9,614✔
332
        bool fast_reconnect = false;
6,686✔
333
        sess_2.connection_established(fast_reconnect); // Throws
6,686✔
334
    }
6,686✔
335
    ++m_num_active_sessions;
9,614✔
336
}
9,614✔
337

338

339
void Connection::initiate_session_deactivation(Session* sess)
340
{
9,610✔
341
    REALM_ASSERT(sess);
9,610✔
342
    REALM_ASSERT(&sess->m_conn == this);
9,610✔
343
    REALM_ASSERT(m_num_active_sessions);
9,610✔
344
    // Since the client may be waiting for m_num_active_sessions to reach 0
4,632✔
345
    // in stop_and_wait() (on a separate thread), deactivate Session before
4,632✔
346
    // decrementing the num active sessions value.
4,632✔
347
    sess->initiate_deactivation(); // Throws
9,610✔
348
    if (sess->m_state == Session::Deactivated) {
9,610✔
349
        finish_session_deactivation(sess);
996✔
350
    }
996✔
351
    if (REALM_UNLIKELY(--m_num_active_sessions == 0)) {
9,610✔
352
        if (m_activated && m_state == ConnectionState::disconnected)
3,956✔
353
            m_on_idle->trigger();
324✔
354
    }
3,956✔
355
}
9,610✔
356

357

358
void Connection::cancel_reconnect_delay()
359
{
2,004✔
360
    REALM_ASSERT(m_activated);
2,004✔
361

1,146✔
362
    if (m_reconnect_delay_in_progress) {
2,004✔
363
        if (m_nonzero_reconnect_delay)
1,792✔
364
            logger.detail("Canceling reconnect delay"); // Throws
900✔
365

1,040✔
366
        // Cancel the in-progress wait operation by destroying the timer
1,040✔
367
        // object. Destruction is needed in this case, because a new wait
1,040✔
368
        // operation might have to be initiated before the previous one
1,040✔
369
        // completes (its completion handler starts to execute), so the new wait
1,040✔
370
        // operation must be done on a new timer object.
1,040✔
371
        m_reconnect_disconnect_timer.reset();
1,792✔
372
        m_reconnect_delay_in_progress = false;
1,792✔
373
        m_reconnect_info.reset();
1,792✔
374
        initiate_reconnect_wait(); // Throws
1,792✔
375
        return;
1,792✔
376
    }
1,792✔
377

106✔
378
    // If we are not disconnected, then we need to make sure the next time we get disconnected
106✔
379
    // that we are allowed to re-connect as quickly as possible.
106✔
380
    //
106✔
381
    // Setting m_reconnect_info.scheduled_reset will cause initiate_reconnect_wait to reset the
106✔
382
    // backoff/delay state before calculating the next delay, unless a PONG message is received
106✔
383
    // for the urgent PING message we send below.
106✔
384
    //
106✔
385
    // If we get a PONG message for the urgent PING message sent below, then the connection is
106✔
386
    // healthy and we can calculate the next delay normally.
106✔
387
    if (m_state != ConnectionState::disconnected) {
212✔
388
        m_reconnect_info.scheduled_reset = true;
212✔
389
        m_ping_after_scheduled_reset_of_reconnect_info = false;
212✔
390

106✔
391
        schedule_urgent_ping(); // Throws
212✔
392
        return;
212✔
393
    }
212✔
394
    // Nothing to do in this case. The next reconnect attemp will be made as
106✔
395
    // soon as there are any sessions that are both active and unsuspended.
106✔
396
}
212✔
397

398
void ClientImpl::Connection::finish_session_deactivation(Session* sess)
399
{
7,918✔
400
    REALM_ASSERT(sess->m_state == Session::Deactivated);
7,918✔
401
    auto ident = sess->m_ident;
7,918✔
402
    m_sessions.erase(ident);
7,918✔
403
    m_session_history.erase(ident);
7,918✔
404
}
7,918✔
405

406
void Connection::force_close()
407
{
2,242✔
408
    if (m_force_closed) {
2,242✔
UNCOV
409
        return;
×
UNCOV
410
    }
×
411

1,056✔
412
    m_force_closed = true;
2,242✔
413

1,056✔
414
    if (m_state != ConnectionState::disconnected) {
2,242✔
415
        voluntary_disconnect();
2,162✔
416
    }
2,162✔
417

1,056✔
418
    REALM_ASSERT_EX(m_state == ConnectionState::disconnected, m_state);
2,242✔
419
    if (m_reconnect_delay_in_progress || m_disconnect_delay_in_progress) {
2,242✔
420
        m_reconnect_disconnect_timer.reset();
80✔
421
        m_reconnect_delay_in_progress = false;
80✔
422
        m_disconnect_delay_in_progress = false;
80✔
423
    }
80✔
424

1,056✔
425
    // We must copy any session pointers we want to close to a vector because force_closing
1,056✔
426
    // the session may remove it from m_sessions and invalidate the iterator uses to loop
1,056✔
427
    // through the map. By copying to a separate vector we ensure our iterators remain valid.
1,056✔
428
    std::vector<Session*> to_close;
2,242✔
429
    for (auto& session_pair : m_sessions) {
1,130✔
430
        if (session_pair.second->m_state == Session::State::Active) {
146✔
431
            to_close.push_back(session_pair.second.get());
144✔
432
        }
144✔
433
    }
146✔
434

1,056✔
435
    for (auto& sess : to_close) {
1,128✔
436
        sess->force_close();
144✔
437
    }
144✔
438

1,056✔
439
    logger.debug("Force closed idle connection");
2,242✔
440
}
2,242✔
441

442

443
void Connection::websocket_connected_handler(const std::string& protocol)
444
{
3,208✔
445
    if (!protocol.empty()) {
3,208✔
446
        std::string_view expected_prefix =
3,208✔
447
            is_flx_sync_connection() ? get_flx_websocket_protocol_prefix() : get_pbs_websocket_protocol_prefix();
2,942✔
448
        // FIXME: Use std::string_view::begins_with() in C++20.
1,608✔
449
        auto prefix_matches = [&](std::string_view other) {
3,208✔
450
            return protocol.size() >= other.size() && (protocol.substr(0, other.size()) == other);
3,208✔
451
        };
3,208✔
452
        if (prefix_matches(expected_prefix)) {
3,208✔
453
            util::MemoryInputStream in;
3,208✔
454
            in.set_buffer(protocol.data() + expected_prefix.size(), protocol.data() + protocol.size());
3,208✔
455
            in.imbue(std::locale::classic());
3,208✔
456
            in.unsetf(std::ios_base::skipws);
3,208✔
457
            int value_2 = 0;
3,208✔
458
            in >> value_2;
3,208✔
459
            if (in && in.eof() && value_2 >= 0) {
3,208✔
460
                bool good_version =
3,208✔
461
                    (value_2 >= get_oldest_supported_protocol_version() && value_2 <= get_current_protocol_version());
3,208✔
462
                if (good_version) {
3,208✔
463
                    logger.detail("Negotiated protocol version: %1", value_2);
3,208✔
464
                    // For now, grab the connection ID from the websocket if it supports it. In the future, the server
1,608✔
465
                    // will provide the appservices connection ID via a log message.
1,608✔
466
                    // TODO: Remove once the server starts sending the connection ID
1,608✔
467
                    receive_appservices_request_id(m_websocket->get_appservices_request_id());
3,208✔
468
                    m_negotiated_protocol_version = value_2;
3,208✔
469
                    handle_connection_established(); // Throws
3,208✔
470
                    return;
3,208✔
471
                }
3,208✔
472
            }
×
473
        }
3,208✔
474
        close_due_to_client_side_error({ErrorCodes::SyncProtocolNegotiationFailed,
×
475
                                        util::format("Bad protocol info from server: '%1'", protocol)},
×
476
                                       IsFatal{true}, ConnectionTerminationReason::bad_headers_in_http_response);
×
UNCOV
477
    }
×
UNCOV
478
    else {
×
UNCOV
479
        close_due_to_client_side_error(
×
UNCOV
480
            {ErrorCodes::SyncProtocolNegotiationFailed, "Missing protocol info from server"}, IsFatal{true},
×
UNCOV
481
            ConnectionTerminationReason::bad_headers_in_http_response);
×
UNCOV
482
    }
×
483
}
3,208✔
484

485

486
bool Connection::websocket_binary_message_received(util::Span<const char> data)
487
{
77,034✔
488
    if (m_force_closed) {
77,034✔
UNCOV
489
        logger.debug("Received binary message after connection was force closed");
×
UNCOV
490
        return false;
×
UNCOV
491
    }
×
492

38,224✔
493
    using sf = SimulatedFailure;
77,034✔
494
    if (sf::check_trigger(sf::sync_client__read_head)) {
77,034✔
495
        close_due_to_client_side_error(
426✔
496
            {ErrorCodes::RuntimeError, "Simulated failure during sync client websocket read"}, IsFatal{false},
426✔
497
            ConnectionTerminationReason::read_or_write_error);
426✔
498
        return bool(m_websocket);
426✔
499
    }
426✔
500

37,956✔
501
    handle_message_received(data);
76,608✔
502
    return bool(m_websocket);
76,608✔
503
}
76,608✔
504

505

506
void Connection::websocket_error_handler()
507
{
560✔
508
    m_websocket_error_received = true;
560✔
509
}
560✔
510

511
bool Connection::websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg)
512
{
688✔
513
    if (m_force_closed) {
688✔
UNCOV
514
        logger.debug("Received websocket close message after connection was force closed");
×
UNCOV
515
        return false;
×
UNCOV
516
    }
×
517
    logger.info("Closing the websocket with error code=%1, message='%2', was_clean=%3", error_code, msg, was_clean);
688✔
518

362✔
519
    switch (error_code) {
688✔
520
        case WebSocketError::websocket_ok:
76✔
521
            break;
76✔
522
        case WebSocketError::websocket_resolve_failed:
4✔
523
            [[fallthrough]];
4✔
524
        case WebSocketError::websocket_connection_failed: {
4✔
525
            SessionErrorInfo error_info(
4✔
526
                {ErrorCodes::SyncConnectFailed, util::format("Failed to connect to sync: %1", msg)}, IsFatal{false});
4✔
527
            involuntary_disconnect(std::move(error_info), ConnectionTerminationReason::connect_operation_failed);
4✔
528
            break;
4✔
529
        }
4✔
530
        case WebSocketError::websocket_read_error:
546✔
531
            [[fallthrough]];
546✔
532
        case WebSocketError::websocket_write_error: {
546✔
533
            close_due_to_transient_error({ErrorCodes::ConnectionClosed, msg},
546✔
534
                                         ConnectionTerminationReason::read_or_write_error);
546✔
535
            break;
546✔
536
        }
546✔
537
        case WebSocketError::websocket_going_away:
290✔
538
            [[fallthrough]];
×
539
        case WebSocketError::websocket_protocol_error:
✔
540
            [[fallthrough]];
×
541
        case WebSocketError::websocket_unsupported_data:
✔
542
            [[fallthrough]];
×
543
        case WebSocketError::websocket_invalid_payload_data:
✔
544
            [[fallthrough]];
×
545
        case WebSocketError::websocket_policy_violation:
✔
546
            [[fallthrough]];
×
547
        case WebSocketError::websocket_reserved:
✔
548
            [[fallthrough]];
×
549
        case WebSocketError::websocket_no_status_received:
✔
UNCOV
550
            [[fallthrough]];
×
UNCOV
551
        case WebSocketError::websocket_invalid_extension: {
✔
UNCOV
552
            close_due_to_client_side_error({ErrorCodes::SyncProtocolInvariantFailed, msg}, IsFatal{false},
×
UNCOV
553
                                           ConnectionTerminationReason::websocket_protocol_violation); // Throws
×
UNCOV
554
            break;
×
UNCOV
555
        }
×
556
        case WebSocketError::websocket_message_too_big: {
4✔
557
            auto message = util::format(
4✔
558
                "Sync websocket closed because the server received a message that was too large: %1", msg);
4✔
559
            SessionErrorInfo error_info(Status(ErrorCodes::LimitExceeded, std::move(message)), IsFatal{false});
4✔
560
            error_info.server_requests_action = ProtocolErrorInfo::Action::ClientReset;
4✔
561
            involuntary_disconnect(std::move(error_info),
4✔
562
                                   ConnectionTerminationReason::websocket_protocol_violation); // Throws
4✔
563
            break;
4✔
564
        }
×
565
        case WebSocketError::websocket_tls_handshake_failed: {
10✔
566
            close_due_to_client_side_error(
10✔
567
                Status(ErrorCodes::TlsHandshakeFailed, util::format("TLS handshake failed: %1", msg)), IsFatal{false},
10✔
568
                ConnectionTerminationReason::ssl_certificate_rejected); // Throws
10✔
569
            break;
10✔
570
        }
×
571
        case WebSocketError::websocket_client_too_old:
✔
572
            [[fallthrough]];
×
573
        case WebSocketError::websocket_client_too_new:
✔
574
            [[fallthrough]];
×
575
        case WebSocketError::websocket_protocol_mismatch: {
✔
576
            close_due_to_client_side_error({ErrorCodes::SyncProtocolNegotiationFailed, msg}, IsFatal{true},
×
577
                                           ConnectionTerminationReason::http_response_says_fatal_error); // Throws
×
578
            break;
×
579
        }
×
580
        case WebSocketError::websocket_fatal_error: {
✔
581
            involuntary_disconnect(SessionErrorInfo({ErrorCodes::ConnectionClosed, msg}, IsFatal{true}),
×
582
                                   ConnectionTerminationReason::http_response_says_fatal_error);
×
583
            break;
×
584
        }
×
585
        case WebSocketError::websocket_forbidden: {
✔
UNCOV
586
            SessionErrorInfo error_info({ErrorCodes::AuthError, msg}, IsFatal{true});
×
UNCOV
587
            error_info.server_requests_action = ProtocolErrorInfo::Action::LogOutUser;
×
UNCOV
588
            involuntary_disconnect(std::move(error_info),
×
UNCOV
589
                                   ConnectionTerminationReason::http_response_says_fatal_error);
×
UNCOV
590
            break;
×
UNCOV
591
        }
×
592
        case WebSocketError::websocket_unauthorized: {
36✔
593
            SessionErrorInfo error_info(
36✔
594
                {ErrorCodes::AuthError,
36✔
595
                 util::format("Websocket was closed because of an authentication issue: %1", msg)},
36✔
596
                IsFatal{false});
36✔
597
            error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshUser;
36✔
598
            involuntary_disconnect(std::move(error_info),
36✔
599
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
36✔
600
            break;
36✔
UNCOV
601
        }
×
602
        case WebSocketError::websocket_moved_permanently: {
12✔
603
            SessionErrorInfo error_info({ErrorCodes::ConnectionClosed, msg}, IsFatal{false});
12✔
604
            error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshLocation;
12✔
605
            involuntary_disconnect(std::move(error_info),
12✔
606
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
12✔
607
            break;
12✔
608
        }
×
609
        case WebSocketError::websocket_abnormal_closure: {
✔
610
            SessionErrorInfo error_info({ErrorCodes::ConnectionClosed, msg}, IsFatal{false});
×
611
            error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshUser;
×
612
            involuntary_disconnect(std::move(error_info),
×
613
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
×
614
            break;
×
615
        }
×
UNCOV
616
        case WebSocketError::websocket_internal_server_error:
✔
UNCOV
617
            [[fallthrough]];
×
UNCOV
618
        case WebSocketError::websocket_retry_error: {
✔
UNCOV
619
            involuntary_disconnect(SessionErrorInfo({ErrorCodes::ConnectionClosed, msg}, IsFatal{false}),
×
UNCOV
620
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
×
UNCOV
621
            break;
×
622
        }
688✔
623
    }
688✔
624

362✔
625
    return bool(m_websocket);
688✔
626
}
688✔
627

628
// Guarantees that handle_reconnect_wait() is never called from within the
629
// execution of initiate_reconnect_wait() (no callback reentrance).
630
void Connection::initiate_reconnect_wait()
631
{
7,578✔
632
    REALM_ASSERT(m_activated);
7,578✔
633
    REALM_ASSERT(!m_reconnect_delay_in_progress);
7,578✔
634
    REALM_ASSERT(!m_disconnect_delay_in_progress);
7,578✔
635

3,870✔
636
    // If we've been force closed then we don't need/want to reconnect. Just return early here.
3,870✔
637
    if (m_force_closed) {
7,578✔
638
        return;
2,160✔
639
    }
2,160✔
640

2,856✔
641
    m_reconnect_delay_in_progress = true;
5,418✔
642
    auto delay = m_reconnect_info.delay_interval();
5,418✔
643
    if (delay == std::chrono::milliseconds::max()) {
5,418✔
644
        logger.detail("Reconnection delayed indefinitely"); // Throws
948✔
645
        // Not actually starting a timer corresponds to an infinite wait
546✔
646
        m_nonzero_reconnect_delay = true;
948✔
647
        return;
948✔
648
    }
948✔
649

2,310✔
650
    if (delay == std::chrono::milliseconds::zero()) {
4,470✔
651
        m_nonzero_reconnect_delay = false;
4,244✔
652
    }
4,244✔
653
    else {
226✔
654
        logger.detail("Allowing reconnection in %1 milliseconds", delay.count()); // Throws
226✔
655
        m_nonzero_reconnect_delay = true;
226✔
656
    }
226✔
657

2,310✔
658
    // We create a timer for the reconnect_disconnect timer even if the delay is zero because
2,310✔
659
    // we need it to be cancelable in case the connection is terminated before the timer
2,310✔
660
    // callback is run.
2,310✔
661
    m_reconnect_disconnect_timer = m_client.create_timer(delay, [this](Status status) {
4,472✔
662
        // If the operation is aborted, the connection object may have been
2,310✔
663
        // destroyed.
2,310✔
664
        if (status != ErrorCodes::OperationAborted)
4,472✔
665
            handle_reconnect_wait(status); // Throws
3,328✔
666
    });                                    // Throws
4,472✔
667
}
4,470✔
668

669

670
void Connection::handle_reconnect_wait(Status status)
671
{
3,330✔
672
    if (!status.is_ok()) {
3,330✔
UNCOV
673
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
UNCOV
674
        throw Exception(status);
×
UNCOV
675
    }
×
676

1,670✔
677
    REALM_ASSERT(m_reconnect_delay_in_progress);
3,330✔
678
    m_reconnect_delay_in_progress = false;
3,330✔
679

1,670✔
680
    if (m_num_active_unsuspended_sessions > 0)
3,330✔
681
        initiate_reconnect(); // Throws
3,330✔
682
}
3,330✔
683

684
struct Connection::WebSocketObserverShim : public sync::WebSocketObserver {
685
    explicit WebSocketObserverShim(Connection* conn)
686
        : conn(conn)
687
        , sentinel(conn->m_websocket_sentinel)
688
    {
3,330✔
689
    }
3,330✔
690

691
    Connection* conn;
692
    util::bind_ptr<LifecycleSentinel> sentinel;
693

694
    void websocket_connected_handler(const std::string& protocol) override
695
    {
3,208✔
696
        if (sentinel->destroyed) {
3,208✔
UNCOV
697
            return;
×
UNCOV
698
        }
×
699

1,608✔
700
        return conn->websocket_connected_handler(protocol);
3,208✔
701
    }
3,208✔
702

703
    void websocket_error_handler() override
704
    {
560✔
705
        if (sentinel->destroyed) {
560✔
UNCOV
706
            return;
×
UNCOV
707
        }
×
708

298✔
709
        conn->websocket_error_handler();
560✔
710
    }
560✔
711

712
    bool websocket_binary_message_received(util::Span<const char> data) override
713
    {
77,034✔
714
        if (sentinel->destroyed) {
77,034✔
UNCOV
715
            return false;
×
UNCOV
716
        }
×
717

38,224✔
718
        return conn->websocket_binary_message_received(data);
77,034✔
719
    }
77,034✔
720

721
    bool websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg) override
722
    {
688✔
723
        if (sentinel->destroyed) {
688✔
UNCOV
724
            return true;
×
UNCOV
725
        }
×
726

362✔
727
        return conn->websocket_closed_handler(was_clean, error_code, msg);
688✔
728
    }
688✔
729
};
730

731
void Connection::initiate_reconnect()
732
{
3,330✔
733
    REALM_ASSERT(m_activated);
3,330✔
734

1,670✔
735
    m_state = ConnectionState::connecting;
3,330✔
736
    report_connection_state_change(ConnectionState::connecting); // Throws
3,330✔
737
    if (m_websocket_sentinel) {
3,330✔
UNCOV
738
        m_websocket_sentinel->destroyed = true;
×
UNCOV
739
    }
×
740
    m_websocket_sentinel = util::make_bind<LifecycleSentinel>();
3,330✔
741
    m_websocket.reset();
3,330✔
742

1,670✔
743
    // Watchdog
1,670✔
744
    initiate_connect_wait(); // Throws
3,330✔
745

1,670✔
746
    std::vector<std::string> sec_websocket_protocol;
3,330✔
747
    {
3,330✔
748
        auto protocol_prefix =
3,330✔
749
            is_flx_sync_connection() ? get_flx_websocket_protocol_prefix() : get_pbs_websocket_protocol_prefix();
3,058✔
750
        int min = get_oldest_supported_protocol_version();
3,330✔
751
        int max = get_current_protocol_version();
3,330✔
752
        REALM_ASSERT_3(min, <=, max);
3,330✔
753
        // List protocol version in descending order to ensure that the server
1,670✔
754
        // selects the highest possible version.
1,670✔
755
        for (int version = max; version >= min; --version) {
33,284✔
756
            sec_websocket_protocol.push_back(util::format("%1%2", protocol_prefix, version)); // Throws
29,954✔
757
        }
29,954✔
758
    }
3,330✔
759

1,670✔
760
    logger.info("Connecting to '%1%2:%3%4'", to_string(m_server_endpoint.envelope), m_server_endpoint.address,
3,330✔
761
                m_server_endpoint.port, m_http_request_path_prefix);
3,330✔
762

1,670✔
763
    m_websocket_error_received = false;
3,330✔
764
    m_websocket =
3,330✔
765
        m_client.m_socket_provider->connect(std::make_unique<WebSocketObserverShim>(this),
3,330✔
766
                                            WebSocketEndpoint{
3,330✔
767
                                                m_server_endpoint.address,
3,330✔
768
                                                m_server_endpoint.port,
3,330✔
769
                                                get_http_request_path(),
3,330✔
770
                                                std::move(sec_websocket_protocol),
3,330✔
771
                                                is_ssl(m_server_endpoint.envelope),
3,330✔
772
                                                /// DEPRECATED - The following will be removed in a future release
1,670✔
773
                                                {m_custom_http_headers.begin(), m_custom_http_headers.end()},
3,330✔
774
                                                m_verify_servers_ssl_certificate,
3,330✔
775
                                                m_ssl_trust_certificate_path,
3,330✔
776
                                                m_ssl_verify_callback,
3,330✔
777
                                                m_proxy_config,
3,330✔
778
                                            });
3,330✔
779
}
3,330✔
780

781

782
void Connection::initiate_connect_wait()
783
{
3,324✔
784
    // Deploy a watchdog to enforce an upper bound on the time it can take to
1,670✔
785
    // fully establish the connection (including SSL and WebSocket
1,670✔
786
    // handshakes). Without such a watchdog, connect operations could take very
1,670✔
787
    // long, or even indefinite time.
1,670✔
788
    milliseconds_type time = m_client.m_connect_timeout;
3,324✔
789

1,670✔
790
    m_connect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
3,330✔
791
        // If the operation is aborted, the connection object may have been
1,670✔
792
        // destroyed.
1,670✔
793
        if (status != ErrorCodes::OperationAborted)
3,330✔
794
            handle_connect_wait(status); // Throws
×
795
    });                                  // Throws
3,330✔
796
}
3,324✔
797

798

799
void Connection::handle_connect_wait(Status status)
800
{
×
801
    if (!status.is_ok()) {
×
802
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
803
        throw Exception(status);
×
804
    }
×
805

806
    REALM_ASSERT_EX(m_state == ConnectionState::connecting, m_state);
×
UNCOV
807
    logger.info("Connect timeout"); // Throws
×
UNCOV
808
    involuntary_disconnect(
×
UNCOV
809
        SessionErrorInfo{Status{ErrorCodes::SyncConnectTimeout, "Sync connection was not fully established in time"},
×
UNCOV
810
                         IsFatal{false}},
×
UNCOV
811
        ConnectionTerminationReason::sync_connect_timeout); // Throws
×
UNCOV
812
}
×
813

814

815
void Connection::handle_connection_established()
816
{
3,208✔
817
    // Cancel connect timeout watchdog
1,608✔
818
    m_connect_timer.reset();
3,208✔
819

1,608✔
820
    m_state = ConnectionState::connected;
3,208✔
821

1,608✔
822
    milliseconds_type now = monotonic_clock_now();
3,208✔
823
    m_pong_wait_started_at = now; // Initially, no time was spent waiting for a PONG message
3,208✔
824
    initiate_ping_delay(now);     // Throws
3,208✔
825

1,608✔
826
    bool fast_reconnect = false;
3,208✔
827
    if (m_disconnect_has_occurred) {
3,208✔
828
        milliseconds_type time = now - m_disconnect_time;
956✔
829
        if (time <= m_client.m_fast_reconnect_limit)
956✔
830
            fast_reconnect = true;
956✔
831
    }
956✔
832

1,608✔
833
    for (auto& p : m_sessions) {
4,272✔
834
        Session& sess = *p.second;
4,272✔
835
        sess.connection_established(fast_reconnect); // Throws
4,272✔
836
    }
4,272✔
837

1,608✔
838
    report_connection_state_change(ConnectionState::connected); // Throws
3,208✔
839
}
3,208✔
840

841

842
void Connection::schedule_urgent_ping()
843
{
212✔
844
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
212✔
845
    if (m_ping_delay_in_progress) {
212✔
846
        m_heartbeat_timer.reset();
160✔
847
        m_ping_delay_in_progress = false;
160✔
848
        m_minimize_next_ping_delay = true;
160✔
849
        milliseconds_type now = monotonic_clock_now();
160✔
850
        initiate_ping_delay(now); // Throws
160✔
851
        return;
160✔
852
    }
160✔
853
    REALM_ASSERT_EX(m_state == ConnectionState::connecting || m_waiting_for_pong, m_state);
52!
854
    if (!m_send_ping)
52!
855
        m_minimize_next_ping_delay = true;
52✔
856
}
52✔
857

858

859
void Connection::initiate_ping_delay(milliseconds_type now)
860
{
3,564✔
861
    REALM_ASSERT(!m_ping_delay_in_progress);
3,564✔
862
    REALM_ASSERT(!m_waiting_for_pong);
3,564✔
863
    REALM_ASSERT(!m_send_ping);
3,564✔
864

1,744✔
865
    milliseconds_type delay = 0;
3,564✔
866
    if (!m_minimize_next_ping_delay) {
3,564✔
867
        delay = m_client.m_ping_keepalive_period;
3,398✔
868
        // Make a randomized deduction of up to 10%, or up to 100% if this is
1,684✔
869
        // the first PING message to be sent since the connection was
1,684✔
870
        // established. The purpose of this randomized deduction is to reduce
1,684✔
871
        // the risk of many connections sending PING messages simultaneously to
1,684✔
872
        // the server.
1,684✔
873
        milliseconds_type max_deduction = (m_ping_sent ? delay / 10 : delay);
3,284✔
874
        auto distr = std::uniform_int_distribution<milliseconds_type>(0, max_deduction);
3,398✔
875
        milliseconds_type randomized_deduction = distr(m_client.get_random());
3,398✔
876
        delay -= randomized_deduction;
3,398✔
877
        // Deduct the time spent waiting for PONG
1,684✔
878
        REALM_ASSERT_3(now, >=, m_pong_wait_started_at);
3,398✔
879
        milliseconds_type spent_time = now - m_pong_wait_started_at;
3,398✔
880
        if (spent_time < delay) {
3,398✔
881
            delay -= spent_time;
3,390✔
882
        }
3,390✔
883
        else {
8✔
884
            delay = 0;
8✔
885
        }
8✔
886
    }
3,398✔
887
    else {
166✔
888
        m_minimize_next_ping_delay = false;
166✔
889
    }
166✔
890

1,744✔
891

1,744✔
892
    m_ping_delay_in_progress = true;
3,564✔
893

1,744✔
894
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
3,564✔
895
        if (status == ErrorCodes::OperationAborted)
3,560✔
896
            return;
3,346✔
897
        else if (!status.is_ok())
214✔
UNCOV
898
            throw Exception(status);
×
899

86✔
900
        handle_ping_delay();                                    // Throws
214✔
901
    });                                                         // Throws
214✔
902
    logger.debug("Will emit a ping in %1 milliseconds", delay); // Throws
3,564✔
903
}
3,564✔
904

905

906
void Connection::handle_ping_delay()
907
{
214✔
908
    REALM_ASSERT(m_ping_delay_in_progress);
214✔
909
    m_ping_delay_in_progress = false;
214✔
910
    m_send_ping = true;
214✔
911

88✔
912
    initiate_pong_timeout(); // Throws
214✔
913

88✔
914
    if (m_state == ConnectionState::connected && !m_sending)
214✔
915
        send_next_message(); // Throws
186✔
916
}
214✔
917

918

919
void Connection::initiate_pong_timeout()
920
{
214✔
921
    REALM_ASSERT(!m_ping_delay_in_progress);
214✔
922
    REALM_ASSERT(!m_waiting_for_pong);
214✔
923
    REALM_ASSERT(m_send_ping);
214✔
924

88✔
925
    m_waiting_for_pong = true;
214✔
926
    m_pong_wait_started_at = monotonic_clock_now();
214✔
927

88✔
928
    milliseconds_type time = m_client.m_pong_keepalive_timeout;
214✔
929
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
214✔
930
        if (status == ErrorCodes::OperationAborted)
214✔
931
            return;
202✔
932
        else if (!status.is_ok())
12✔
UNCOV
933
            throw Exception(status);
×
934

6✔
935
        handle_pong_timeout(); // Throws
12✔
936
    });                        // Throws
12✔
937
}
214✔
938

939

940
void Connection::handle_pong_timeout()
941
{
12✔
942
    REALM_ASSERT(m_waiting_for_pong);
12✔
943
    logger.debug("Timeout on reception of PONG message"); // Throws
12✔
944
    close_due_to_transient_error({ErrorCodes::ConnectionClosed, "Timed out waiting for PONG response from server"},
12✔
945
                                 ConnectionTerminationReason::pong_timeout);
12✔
946
}
12✔
947

948

949
void Connection::initiate_write_message(const OutputBuffer& out, Session* sess)
950
{
97,138✔
951
    // Stop sending messages if an websocket error was received.
47,410✔
952
    if (m_websocket_error_received)
97,138✔
UNCOV
953
        return;
×
954

47,410✔
955
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
97,138✔
956
        if (sentinel->destroyed) {
97,008✔
957
            return;
1,448✔
958
        }
1,448✔
959
        if (!status.is_ok()) {
95,560✔
UNCOV
960
            if (status != ErrorCodes::Error::OperationAborted) {
×
961
                // Write errors will be handled by the websocket_write_error_handler() callback
UNCOV
962
                logger.error("Connection: write failed %1: %2", status.code_string(), status.reason());
×
UNCOV
963
            }
×
UNCOV
964
            return;
×
UNCOV
965
        }
×
966
        handle_write_message(); // Throws
95,560✔
967
    });                         // Throws
95,560✔
968
    m_sending_session = sess;
97,138✔
969
    m_sending = true;
97,138✔
970
}
97,138✔
971

972

973
void Connection::handle_write_message()
974
{
95,560✔
975
    m_sending_session->message_sent(); // Throws
95,560✔
976
    if (m_sending_session->m_state == Session::Deactivated) {
95,560✔
977
        finish_session_deactivation(m_sending_session);
106✔
978
    }
106✔
979
    m_sending_session = nullptr;
95,560✔
980
    m_sending = false;
95,560✔
981
    send_next_message(); // Throws
95,560✔
982
}
95,560✔
983

984

985
void Connection::send_next_message()
986
{
155,114✔
987
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
155,114✔
988
    REALM_ASSERT(!m_sending_session);
155,114✔
989
    REALM_ASSERT(!m_sending);
155,114✔
990
    if (m_send_ping) {
155,114✔
991
        send_ping(); // Throws
202✔
992
        return;
202✔
993
    }
202✔
994
    while (!m_sessions_enlisted_to_send.empty()) {
216,130✔
995
        // The state of being connected is not supposed to be able to change
76,486✔
996
        // across this loop thanks to the "no callback reentrance" guarantee
76,486✔
997
        // provided by Websocket::async_write_text(), and friends.
76,486✔
998
        REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
158,560✔
999

76,486✔
1000
        Session& sess = *m_sessions_enlisted_to_send.front();
158,560✔
1001
        m_sessions_enlisted_to_send.pop_front();
158,560✔
1002
        sess.send_message(); // Throws
158,560✔
1003

76,486✔
1004
        if (sess.m_state == Session::Deactivated) {
158,560✔
1005
            finish_session_deactivation(&sess);
2,090✔
1006
        }
2,090✔
1007

76,486✔
1008
        // An enlisted session may choose to not send a message. In that case,
76,486✔
1009
        // we should pass the opportunity to the next enlisted session.
76,486✔
1010
        if (m_sending)
158,560✔
1011
            break;
97,342✔
1012
    }
158,560✔
1013
}
154,912✔
1014

1015

1016
void Connection::send_ping()
1017
{
202✔
1018
    REALM_ASSERT(!m_ping_delay_in_progress);
202✔
1019
    REALM_ASSERT(m_waiting_for_pong);
202✔
1020
    REALM_ASSERT(m_send_ping);
202✔
1021

82✔
1022
    m_send_ping = false;
202✔
1023
    if (m_reconnect_info.scheduled_reset)
202✔
1024
        m_ping_after_scheduled_reset_of_reconnect_info = true;
160✔
1025

82✔
1026
    m_last_ping_sent_at = monotonic_clock_now();
202✔
1027
    logger.debug("Sending: PING(timestamp=%1, rtt=%2)", m_last_ping_sent_at,
202✔
1028
                 m_previous_ping_rtt); // Throws
202✔
1029

82✔
1030
    ClientProtocol& protocol = get_client_protocol();
202✔
1031
    OutputBuffer& out = get_output_buffer();
202✔
1032
    protocol.make_ping(out, m_last_ping_sent_at, m_previous_ping_rtt); // Throws
202✔
1033
    initiate_write_ping(out);                                          // Throws
202✔
1034
    m_ping_sent = true;
202✔
1035
}
202✔
1036

1037

1038
void Connection::initiate_write_ping(const OutputBuffer& out)
1039
{
202✔
1040
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
202✔
1041
        if (sentinel->destroyed) {
202✔
1042
            return;
×
1043
        }
×
1044
        if (!status.is_ok()) {
202✔
UNCOV
1045
            if (status != ErrorCodes::Error::OperationAborted) {
×
1046
                // Write errors will be handled by the websocket_write_error_handler() callback
UNCOV
1047
                logger.error("Connection: send ping failed %1: %2", status.code_string(), status.reason());
×
UNCOV
1048
            }
×
UNCOV
1049
            return;
×
UNCOV
1050
        }
×
1051
        handle_write_ping(); // Throws
202✔
1052
    });                      // Throws
202✔
1053
    m_sending = true;
202✔
1054
}
202✔
1055

1056

1057
void Connection::handle_write_ping()
1058
{
202✔
1059
    REALM_ASSERT(m_sending);
202✔
1060
    REALM_ASSERT(!m_sending_session);
202✔
1061
    m_sending = false;
202✔
1062
    send_next_message(); // Throws
202✔
1063
}
202✔
1064

1065

1066
void Connection::handle_message_received(util::Span<const char> data)
1067
{
76,608✔
1068
    // parse_message_received() parses the message and calls the proper handler
37,956✔
1069
    // on the Connection object (this).
37,956✔
1070
    get_client_protocol().parse_message_received<Connection>(*this, std::string_view(data.data(), data.size()));
76,608✔
1071
}
76,608✔
1072

1073

1074
void Connection::initiate_disconnect_wait()
1075
{
4,284✔
1076
    REALM_ASSERT(!m_reconnect_delay_in_progress);
4,284✔
1077

2,026✔
1078
    if (m_disconnect_delay_in_progress) {
4,284✔
1079
        m_reconnect_disconnect_timer.reset();
2,060✔
1080
        m_disconnect_delay_in_progress = false;
2,060✔
1081
    }
2,060✔
1082

2,026✔
1083
    milliseconds_type time = m_client.m_connection_linger_time;
4,284✔
1084

2,026✔
1085
    m_reconnect_disconnect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
4,284✔
1086
        // If the operation is aborted, the connection object may have been
2,026✔
1087
        // destroyed.
2,026✔
1088
        if (status != ErrorCodes::OperationAborted)
4,284✔
1089
            handle_disconnect_wait(status); // Throws
12✔
1090
    });                                     // Throws
4,284✔
1091
    m_disconnect_delay_in_progress = true;
4,284✔
1092
}
4,284✔
1093

1094

1095
void Connection::handle_disconnect_wait(Status status)
1096
{
12✔
1097
    if (!status.is_ok()) {
12✔
UNCOV
1098
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
UNCOV
1099
        throw Exception(status);
×
UNCOV
1100
    }
×
1101

6✔
1102
    m_disconnect_delay_in_progress = false;
12✔
1103

6✔
1104
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
12✔
1105
    if (m_num_active_unsuspended_sessions == 0) {
12✔
1106
        if (m_client.m_connection_linger_time > 0)
12✔
UNCOV
1107
            logger.detail("Linger time expired"); // Throws
×
1108
        voluntary_disconnect();                   // Throws
12✔
1109
        logger.info("Disconnected");              // Throws
12✔
1110
    }
12✔
1111
}
12✔
1112

1113

1114
void Connection::close_due_to_protocol_error(Status status)
1115
{
4✔
1116
    SessionErrorInfo error_info(std::move(status), IsFatal{true});
4✔
1117
    error_info.server_requests_action = ProtocolErrorInfo::Action::ProtocolViolation;
4✔
1118
    involuntary_disconnect(std::move(error_info),
4✔
1119
                           ConnectionTerminationReason::sync_protocol_violation); // Throws
4✔
1120
}
4✔
1121

1122

1123
void Connection::close_due_to_client_side_error(Status status, IsFatal is_fatal, ConnectionTerminationReason reason)
1124
{
436✔
1125
    logger.info("Connection closed due to error: %1", status); // Throws
436✔
1126

274✔
1127
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
436✔
1128
}
436✔
1129

1130

1131
void Connection::close_due_to_transient_error(Status status, ConnectionTerminationReason reason)
1132
{
558✔
1133
    logger.info("Connection closed due to transient error: %1", status); // Throws
558✔
1134
    SessionErrorInfo error_info{std::move(status), IsFatal{false}};
558✔
1135
    error_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
558✔
1136

296✔
1137
    involuntary_disconnect(std::move(error_info), reason); // Throw
558✔
1138
}
558✔
1139

1140

1141
// Close connection due to error discovered on the server-side, and then
1142
// reported to the client by way of a connection-level ERROR message.
1143
void Connection::close_due_to_server_side_error(ProtocolError error_code, const ProtocolErrorInfo& info)
1144
{
66✔
1145
    logger.info("Connection closed due to error reported by server: %1 (%2)", info.message,
66✔
1146
                int(error_code)); // Throws
66✔
1147

32✔
1148
    const auto reason = info.is_fatal ? ConnectionTerminationReason::server_said_do_not_reconnect
42✔
1149
                                      : ConnectionTerminationReason::server_said_try_again_later;
56✔
1150
    involuntary_disconnect(SessionErrorInfo{info, protocol_error_to_status(error_code, info.message)},
66✔
1151
                           reason); // Throws
66✔
1152
}
66✔
1153

1154

1155
void Connection::disconnect(const SessionErrorInfo& info)
1156
{
3,330✔
1157
    // Cancel connect timeout watchdog
1,670✔
1158
    m_connect_timer.reset();
3,330✔
1159

1,670✔
1160
    if (m_state == ConnectionState::connected) {
3,330✔
1161
        m_disconnect_time = monotonic_clock_now();
3,206✔
1162
        m_disconnect_has_occurred = true;
3,206✔
1163

1,608✔
1164
        // Sessions that are in the Deactivating state at this time can be
1,608✔
1165
        // immediately discarded, in part because they are no longer enlisted to
1,608✔
1166
        // send. Such sessions will be taken to the Deactivated state by
1,608✔
1167
        // Session::connection_lost(), and then they will be removed from
1,608✔
1168
        // `m_sessions`.
1,608✔
1169
        auto i = m_sessions.begin(), end = m_sessions.end();
3,206✔
1170
        while (i != end) {
6,930✔
1171
            // Prevent invalidation of the main iterator when erasing elements
2,034✔
1172
            auto j = i++;
3,724✔
1173
            Session& sess = *j->second;
3,724✔
1174
            sess.connection_lost(); // Throws
3,724✔
1175
            if (sess.m_state == Session::Unactivated || sess.m_state == Session::Deactivated)
3,724✔
1176
                m_sessions.erase(j);
1,696✔
1177
        }
3,724✔
1178
    }
3,206✔
1179

1,670✔
1180
    change_state_to_disconnected();
3,330✔
1181

1,670✔
1182
    m_ping_delay_in_progress = false;
3,330✔
1183
    m_waiting_for_pong = false;
3,330✔
1184
    m_send_ping = false;
3,330✔
1185
    m_minimize_next_ping_delay = false;
3,330✔
1186
    m_ping_after_scheduled_reset_of_reconnect_info = false;
3,330✔
1187
    m_ping_sent = false;
3,330✔
1188
    m_heartbeat_timer.reset();
3,330✔
1189
    m_previous_ping_rtt = 0;
3,330✔
1190

1,670✔
1191
    m_websocket_sentinel->destroyed = true;
3,330✔
1192
    m_websocket_sentinel.reset();
3,330✔
1193
    m_websocket.reset();
3,330✔
1194
    m_input_body_buffer.reset();
3,330✔
1195
    m_sending_session = nullptr;
3,330✔
1196
    m_sessions_enlisted_to_send.clear();
3,330✔
1197
    m_sending = false;
3,330✔
1198

1,670✔
1199
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
3,330✔
1200
    initiate_reconnect_wait();                                           // Throws
3,330✔
1201
}
3,330✔
1202

1203
bool Connection::is_flx_sync_connection() const noexcept
1204
{
104,598✔
1205
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
104,598✔
1206
}
104,598✔
1207

1208
void Connection::receive_pong(milliseconds_type timestamp)
1209
{
196✔
1210
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
196✔
1211

82✔
1212
    bool legal_at_this_time = (m_waiting_for_pong && !m_send_ping);
196✔
1213
    if (REALM_UNLIKELY(!legal_at_this_time)) {
196✔
1214
        close_due_to_protocol_error(
×
1215
            {ErrorCodes::SyncProtocolInvariantFailed, "Received PONG message when it was not valid"}); // Throws
×
1216
        return;
×
1217
    }
×
1218

82✔
1219
    if (REALM_UNLIKELY(timestamp != m_last_ping_sent_at)) {
196✔
UNCOV
1220
        close_due_to_protocol_error(
×
UNCOV
1221
            {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
1222
             util::format("Received PONG message with an invalid timestamp (expected %1, received %2)",
×
UNCOV
1223
                          m_last_ping_sent_at, timestamp)}); // Throws
×
UNCOV
1224
        return;
×
UNCOV
1225
    }
×
1226

82✔
1227
    milliseconds_type now = monotonic_clock_now();
196✔
1228
    milliseconds_type round_trip_time = now - timestamp;
196✔
1229
    logger.debug("Round trip time was %1 milliseconds", round_trip_time);
196✔
1230
    m_previous_ping_rtt = round_trip_time;
196✔
1231

82✔
1232
    // If this PONG message is a response to a PING mesage that was sent after
82✔
1233
    // the last invocation of cancel_reconnect_delay(), then the connection is
82✔
1234
    // still good, and we do not have to skip the next reconnect delay.
82✔
1235
    if (m_ping_after_scheduled_reset_of_reconnect_info) {
196✔
1236
        REALM_ASSERT(m_reconnect_info.scheduled_reset);
152✔
1237
        m_ping_after_scheduled_reset_of_reconnect_info = false;
152✔
1238
        m_reconnect_info.scheduled_reset = false;
152✔
1239
    }
152✔
1240

82✔
1241
    m_heartbeat_timer.reset();
196✔
1242
    m_waiting_for_pong = false;
196✔
1243

82✔
1244
    initiate_ping_delay(now); // Throws
196✔
1245

82✔
1246
    if (m_client.m_roundtrip_time_handler)
196✔
1247
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
×
1248
}
196✔
1249

1250
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
1251
{
69,666✔
1252
    if (session_ident == 0) {
69,666✔
UNCOV
1253
        return nullptr;
×
UNCOV
1254
    }
×
1255

34,848✔
1256
    auto* sess = get_session(session_ident);
69,666✔
1257
    if (REALM_LIKELY(sess)) {
69,670✔
1258
        return sess;
69,670✔
1259
    }
69,670✔
1260
    // Check the history to see if the message received was for a previous session
2,147,483,647✔
1261
    if (auto it = m_session_history.find(session_ident); it == m_session_history.end()) {
4,294,967,294✔
UNCOV
1262
        logger.error("Bad session identifier in %1 message, session_ident = %2", message, session_ident);
×
UNCOV
1263
        close_due_to_protocol_error(
×
UNCOV
1264
            {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
1265
             util::format("Received message %1 for session iden %2 when that session never existed", message,
×
UNCOV
1266
                          session_ident)});
×
UNCOV
1267
    }
×
1268
    else {
4,294,967,294✔
1269
        logger.error("Received %1 message for closed session, session_ident = %2", message,
4,294,967,294✔
1270
                     session_ident); // Throws
4,294,967,294✔
1271
    }
4,294,967,294✔
1272
    return nullptr;
4,294,967,294✔
1273
}
4,294,967,294✔
1274

1275
void Connection::receive_error_message(const ProtocolErrorInfo& info, session_ident_type session_ident)
1276
{
962✔
1277
    Session* sess = nullptr;
962✔
1278
    if (session_ident != 0) {
962✔
1279
        sess = find_and_validate_session(session_ident, "ERROR");
892✔
1280
        if (REALM_UNLIKELY(!sess)) {
892✔
UNCOV
1281
            return;
×
UNCOV
1282
        }
×
1283
        if (auto status = sess->receive_error_message(info); !status.is_ok()) {
892✔
1284
            close_due_to_protocol_error(std::move(status)); // Throws
×
UNCOV
1285
            return;
×
UNCOV
1286
        }
×
1287

454✔
1288
        if (sess->m_state == Session::Deactivated) {
892✔
UNCOV
1289
            finish_session_deactivation(sess);
×
UNCOV
1290
        }
×
1291
        return;
892✔
1292
    }
892✔
1293

34✔
1294
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
70✔
1295
                info.message, info.raw_error_code, info.is_fatal, session_ident,
70✔
1296
                info.server_requests_action); // Throws
70✔
1297

34✔
1298
    bool known_error_code = bool(get_protocol_error_message(info.raw_error_code));
70✔
1299
    if (REALM_LIKELY(known_error_code)) {
70✔
1300
        ProtocolError error_code = ProtocolError(info.raw_error_code);
66✔
1301
        if (REALM_LIKELY(!is_session_level_error(error_code))) {
66✔
1302
            close_due_to_server_side_error(error_code, info); // Throws
66✔
1303
            return;
66✔
1304
        }
66✔
UNCOV
1305
        close_due_to_protocol_error(
×
UNCOV
1306
            {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
1307
             util::format("Received ERROR message with a non-connection-level error code %1 without a session ident",
×
UNCOV
1308
                          info.raw_error_code)});
×
UNCOV
1309
    }
×
1310
    else {
4✔
1311
        close_due_to_protocol_error(
4✔
1312
            {ErrorCodes::SyncProtocolInvariantFailed,
4✔
1313
             util::format("Received ERROR message with unknown error code %1", info.raw_error_code)});
4✔
1314
    }
4✔
1315
}
70✔
1316

1317

1318
void Connection::receive_query_error_message(int raw_error_code, std::string_view message, int64_t query_version,
1319
                                             session_ident_type session_ident)
1320
{
16✔
1321
    if (session_ident == 0) {
16✔
1322
        return close_due_to_protocol_error(
×
1323
            {ErrorCodes::SyncProtocolInvariantFailed, "Received query error message for session ident 0"});
×
UNCOV
1324
    }
×
1325

8✔
1326
    if (!is_flx_sync_connection()) {
16✔
1327
        return close_due_to_protocol_error({ErrorCodes::SyncProtocolInvariantFailed,
×
1328
                                            "Received a FLX query error message on a non-FLX sync connection"});
×
UNCOV
1329
    }
×
1330

8✔
1331
    Session* sess = find_and_validate_session(session_ident, "QUERY_ERROR");
16✔
1332
    if (REALM_UNLIKELY(!sess)) {
16✔
UNCOV
1333
        return;
×
UNCOV
1334
    }
×
1335

8✔
1336
    if (auto status = sess->receive_query_error_message(raw_error_code, message, query_version); !status.is_ok()) {
16✔
UNCOV
1337
        close_due_to_protocol_error(std::move(status));
×
UNCOV
1338
    }
×
1339
}
16✔
1340

1341

1342
void Connection::receive_ident_message(session_ident_type session_ident, SaltedFileIdent client_file_ident)
1343
{
3,220✔
1344
    Session* sess = find_and_validate_session(session_ident, "IDENT");
3,220✔
1345
    if (REALM_UNLIKELY(!sess)) {
3,220✔
UNCOV
1346
        return;
×
UNCOV
1347
    }
×
1348

1,520✔
1349
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
3,220✔
UNCOV
1350
        close_due_to_protocol_error(std::move(status)); // Throws
×
1351
}
3,220✔
1352

1353
void Connection::receive_download_message(session_ident_type session_ident, const SyncProgress& progress,
1354
                                          std::uint_fast64_t downloadable_bytes, int64_t query_version,
1355
                                          DownloadBatchState batch_state,
1356
                                          const ReceivedChangesets& received_changesets)
1357
{
44,216✔
1358
    Session* sess = find_and_validate_session(session_ident, "DOWNLOAD");
44,216✔
1359
    if (REALM_UNLIKELY(!sess)) {
44,216✔
1360
        return;
×
1361
    }
×
1362

23,074✔
1363
    if (auto status = sess->receive_download_message(progress, downloadable_bytes, batch_state, query_version,
44,216✔
1364
                                                     received_changesets);
44,216✔
1365
        !status.is_ok()) {
44,216✔
UNCOV
1366
        close_due_to_protocol_error(std::move(status));
×
UNCOV
1367
    }
×
1368
}
44,216✔
1369

1370
void Connection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
1371
{
16,554✔
1372
    Session* sess = find_and_validate_session(session_ident, "MARK");
16,554✔
1373
    if (REALM_UNLIKELY(!sess)) {
16,554✔
UNCOV
1374
        return;
×
UNCOV
1375
    }
×
1376

7,740✔
1377
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
16,554✔
UNCOV
1378
        close_due_to_protocol_error(std::move(status)); // Throws
×
1379
}
16,554✔
1380

1381

1382
void Connection::receive_unbound_message(session_ident_type session_ident)
1383
{
4,726✔
1384
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
4,726✔
1385
    if (REALM_UNLIKELY(!sess)) {
4,726✔
1386
        return;
×
UNCOV
1387
    }
×
1388

2,030✔
1389
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
4,726✔
UNCOV
1390
        close_due_to_protocol_error(std::move(status)); // Throws
×
UNCOV
1391
        return;
×
UNCOV
1392
    }
×
1393

2,030✔
1394
    if (sess->m_state == Session::Deactivated) {
4,726✔
1395
        finish_session_deactivation(sess);
4,726✔
1396
    }
4,726✔
1397
}
4,726✔
1398

1399

1400
void Connection::receive_test_command_response(session_ident_type session_ident, request_ident_type request_ident,
1401
                                               std::string_view body)
1402
{
44✔
1403
    Session* sess = find_and_validate_session(session_ident, "TEST_COMMAND");
44✔
1404
    if (REALM_UNLIKELY(!sess)) {
44✔
UNCOV
1405
        return;
×
UNCOV
1406
    }
×
1407

22✔
1408
    if (auto status = sess->receive_test_command_response(request_ident, body); !status.is_ok()) {
44✔
UNCOV
1409
        close_due_to_protocol_error(std::move(status));
×
UNCOV
1410
    }
×
1411
}
44✔
1412

1413

1414
void Connection::receive_server_log_message(session_ident_type session_ident, util::Logger::Level level,
1415
                                            std::string_view message)
1416
{
6,672✔
1417
    std::string prefix;
6,672✔
1418
    if (REALM_LIKELY(!m_appservices_coid.empty())) {
6,672✔
1419
        prefix = util::format("Server[%1]", m_appservices_coid);
6,670✔
1420
    }
6,670✔
1421
    else {
2✔
1422
        prefix = "Server";
2✔
1423
    }
2✔
1424

2,990✔
1425
    if (session_ident != 0) {
6,672✔
1426
        if (auto sess = get_session(session_ident)) {
4,770✔
1427
            sess->logger.log(level, "%1 log: %2", prefix, message);
4,770✔
1428
            return;
4,770✔
1429
        }
4,770✔
1430

UNCOV
1431
        logger.log(level, "%1 log for unknown session %2: %3", prefix, session_ident, message);
×
UNCOV
1432
        return;
×
UNCOV
1433
    }
×
1434

974✔
1435
    logger.log(level, "%1 log: %2", prefix, message);
1,902✔
1436
}
1,902✔
1437

1438

1439
void Connection::receive_appservices_request_id(std::string_view coid)
1440
{
5,110✔
1441
    // Only set once per connection
2,582✔
1442
    if (!coid.empty() && m_appservices_coid.empty()) {
5,110✔
1443
        m_appservices_coid = coid;
2,232✔
1444
        logger.info("Connected to app services with request id: \"%1\"", m_appservices_coid);
2,232✔
1445
    }
2,232✔
1446
}
5,110✔
1447

1448

1449
void Connection::handle_protocol_error(Status status)
UNCOV
1450
{
×
UNCOV
1451
    close_due_to_protocol_error(std::move(status));
×
UNCOV
1452
}
×
1453

1454

1455
// Sessions are guaranteed to be granted the opportunity to send a message in
1456
// the order that they enlist. Note that this is important to ensure
1457
// nonoverlapping communication with the server for consecutive sessions
1458
// associated with the same Realm file.
1459
//
1460
// CAUTION: The specified session may get destroyed before this function
1461
// returns, but only if its Session::send_message() puts it into the Deactivated
1462
// state.
1463
void Connection::enlist_to_send(Session* sess)
1464
{
160,252✔
1465
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
160,252✔
1466
    m_sessions_enlisted_to_send.push_back(sess); // Throws
160,252✔
1467
    if (!m_sending)
160,252✔
1468
        send_next_message(); // Throws
59,164✔
1469
}
160,252✔
1470

1471

1472
std::string Connection::get_active_appservices_connection_id()
1473
{
72✔
1474
    return m_appservices_coid;
72✔
1475
}
72✔
1476

1477
void Session::cancel_resumption_delay()
1478
{
4,164✔
1479
    REALM_ASSERT_EX(m_state == Active, m_state);
4,164✔
1480

2,380✔
1481
    if (!m_suspended)
4,164✔
1482
        return;
3,776✔
1483

204✔
1484
    m_suspended = false;
388✔
1485

204✔
1486
    logger.debug("Resumed"); // Throws
388✔
1487

204✔
1488
    if (unbind_process_complete())
388✔
1489
        initiate_rebind(); // Throws
380✔
1490

204✔
1491
    m_conn.one_more_active_unsuspended_session(); // Throws
388✔
1492

204✔
1493
    on_resumed(); // Throws
388✔
1494
}
388✔
1495

1496

1497
void Session::gather_pending_compensating_writes(util::Span<Changeset> changesets,
1498
                                                 std::vector<ProtocolErrorInfo>* out)
1499
{
20,570✔
1500
    if (m_pending_compensating_write_errors.empty() || changesets.empty()) {
20,570✔
1501
        return;
20,532✔
1502
    }
20,532✔
1503

18✔
1504
#ifdef REALM_DEBUG
38✔
1505
    REALM_ASSERT_DEBUG(
38✔
1506
        std::is_sorted(m_pending_compensating_write_errors.begin(), m_pending_compensating_write_errors.end(),
38✔
1507
                       [](const ProtocolErrorInfo& lhs, const ProtocolErrorInfo& rhs) {
38✔
1508
                           REALM_ASSERT_DEBUG(lhs.compensating_write_server_version.has_value());
38✔
1509
                           REALM_ASSERT_DEBUG(rhs.compensating_write_server_version.has_value());
38✔
1510
                           return *lhs.compensating_write_server_version < *rhs.compensating_write_server_version;
38✔
1511
                       }));
38✔
1512
#endif
38✔
1513

18✔
1514
    while (!m_pending_compensating_write_errors.empty() &&
78✔
1515
           *m_pending_compensating_write_errors.front().compensating_write_server_version <=
60✔
1516
               changesets.back().version) {
40✔
1517
        auto& cur_error = m_pending_compensating_write_errors.front();
40✔
1518
        REALM_ASSERT_3(*cur_error.compensating_write_server_version, >=, changesets.front().version);
40✔
1519
        out->push_back(std::move(cur_error));
40✔
1520
        m_pending_compensating_write_errors.pop_front();
40✔
1521
    }
40✔
1522
}
38✔
1523

1524

1525
void Session::integrate_changesets(ClientReplication& repl, const SyncProgress& progress,
1526
                                   std::uint_fast64_t downloadable_bytes,
1527
                                   const ReceivedChangesets& received_changesets, VersionInfo& version_info,
1528
                                   DownloadBatchState download_batch_state)
1529
{
42,110✔
1530
    auto& history = repl.get_history();
42,110✔
1531
    if (received_changesets.empty()) {
42,110✔
1532
        if (download_batch_state == DownloadBatchState::MoreToCome) {
21,520✔
UNCOV
1533
            throw IntegrationException(ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
1534
                                       "received empty download message that was not the last in batch",
×
UNCOV
1535
                                       ProtocolError::bad_progress);
×
UNCOV
1536
        }
×
1537
        history.set_sync_progress(progress, &downloadable_bytes, version_info); // Throws
21,520✔
1538
        return;
21,520✔
1539
    }
21,520✔
1540

11,022✔
1541
    std::vector<ProtocolErrorInfo> pending_compensating_write_errors;
20,590✔
1542
    auto transact = get_db()->start_read();
20,590✔
1543
    history.integrate_server_changesets(
20,590✔
1544
        progress, &downloadable_bytes, received_changesets, version_info, download_batch_state, logger, transact,
20,590✔
1545
        [&](const TransactionRef&, util::Span<Changeset> changesets) {
20,580✔
1546
            gather_pending_compensating_writes(changesets, &pending_compensating_write_errors);
20,570✔
1547
        }); // Throws
20,570✔
1548
    if (received_changesets.size() == 1) {
20,590✔
1549
        logger.debug("1 remote changeset integrated, producing client version %1",
14,412✔
1550
                     version_info.sync_version.version); // Throws
14,412✔
1551
    }
14,412✔
1552
    else {
6,178✔
1553
        logger.debug("%2 remote changesets integrated, producing client version %1",
6,178✔
1554
                     version_info.sync_version.version, received_changesets.size()); // Throws
6,178✔
1555
    }
6,178✔
1556

11,022✔
1557
    for (const auto& pending_error : pending_compensating_write_errors) {
11,042✔
1558
        logger.info("Reporting compensating write for client version %1 in server version %2: %3",
40✔
1559
                    pending_error.compensating_write_rejected_client_version,
40✔
1560
                    *pending_error.compensating_write_server_version, pending_error.message);
40✔
1561
        try {
40✔
1562
            on_connection_state_changed(
40✔
1563
                m_conn.get_state(),
40✔
1564
                SessionErrorInfo{pending_error,
40✔
1565
                                 protocol_error_to_status(static_cast<ProtocolError>(pending_error.raw_error_code),
40✔
1566
                                                          pending_error.message)});
40✔
1567
        }
40✔
1568
        catch (...) {
20✔
UNCOV
1569
            logger.error("Exception thrown while reporting compensating write: %1", exception_to_status());
×
UNCOV
1570
        }
×
1571
    }
40✔
1572
}
20,590✔
1573

1574

1575
void Session::on_integration_failure(const IntegrationException& error)
1576
{
32✔
1577
    REALM_ASSERT_EX(m_state == Active, m_state);
32✔
1578
    REALM_ASSERT(!m_client_error && !m_error_to_send);
32✔
1579
    logger.error("Failed to integrate downloaded changesets: %1", error.to_status());
32✔
1580

16✔
1581
    m_client_error = util::make_optional<IntegrationException>(error);
32✔
1582
    m_error_to_send = true;
32✔
1583

16✔
1584
    // Surface the error to the user otherwise is lost.
16✔
1585
    on_connection_state_changed(m_conn.get_state(), SessionErrorInfo{error.to_status(), IsFatal{false}});
32✔
1586

16✔
1587
    // Since the deactivation process has not been initiated, the UNBIND
16✔
1588
    // message cannot have been sent unless an ERROR message was received.
16✔
1589
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
32✔
1590
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
32✔
1591
        ensure_enlisted_to_send(); // Throws
32✔
1592
    }
32✔
1593
}
32✔
1594

1595
void Session::on_changesets_integrated(version_type client_version, const SyncProgress& progress)
1596
{
43,488✔
1597
    REALM_ASSERT_EX(m_state == Active, m_state);
43,488✔
1598
    REALM_ASSERT_3(progress.download.server_version, >=, m_download_progress.server_version);
43,488✔
1599
    m_download_progress = progress.download;
43,488✔
1600
    bool upload_progressed = (progress.upload.client_version > m_progress.upload.client_version);
43,488✔
1601
    m_progress = progress;
43,488✔
1602
    if (upload_progressed) {
43,488✔
1603
        if (progress.upload.client_version > m_last_version_selected_for_upload) {
31,958✔
1604
            if (progress.upload.client_version > m_upload_progress.client_version)
13,512✔
1605
                m_upload_progress = progress.upload;
1,318✔
1606
            m_last_version_selected_for_upload = progress.upload.client_version;
13,512✔
1607
        }
13,512✔
1608

16,470✔
1609
        check_for_upload_completion();
31,958✔
1610
    }
31,958✔
1611

22,682✔
1612
    do_recognize_sync_version(client_version); // Allows upload process to resume
43,488✔
1613
    check_for_download_completion();           // Throws
43,488✔
1614

22,682✔
1615
    // If the client migrated from PBS to FLX, create subscriptions when new tables are received from server.
22,682✔
1616
    if (auto migration_store = get_migration_store(); migration_store && m_is_flx_sync_session) {
43,488✔
1617
        auto& flx_subscription_store = *get_flx_subscription_store();
2,418✔
1618
        get_migration_store()->create_subscriptions(flx_subscription_store);
2,418✔
1619
    }
2,418✔
1620

22,682✔
1621
    // Since the deactivation process has not been initiated, the UNBIND
22,682✔
1622
    // message cannot have been sent unless an ERROR message was received.
22,682✔
1623
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
43,488✔
1624
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
43,488✔
1625
        ensure_enlisted_to_send(); // Throws
43,484✔
1626
    }
43,484✔
1627
}
43,488✔
1628

1629

1630
Session::~Session()
1631
{
9,612✔
1632
    //    REALM_ASSERT_EX(m_state == Unactivated || m_state == Deactivated, m_state);
4,632✔
1633
}
9,612✔
1634

1635

1636
std::string Session::make_logger_prefix(session_ident_type ident)
1637
{
9,614✔
1638
    std::ostringstream out;
9,614✔
1639
    out.imbue(std::locale::classic());
9,614✔
1640
    out << "Session[" << ident << "]: "; // Throws
9,614✔
1641
    return out.str();                    // Throws
9,614✔
1642
}
9,614✔
1643

1644

1645
void Session::activate()
1646
{
9,610✔
1647
    REALM_ASSERT_EX(m_state == Unactivated, m_state);
9,610✔
1648

4,632✔
1649
    logger.debug("Activating"); // Throws
9,610✔
1650

4,632✔
1651
    bool has_pending_client_reset = false;
9,610✔
1652
    if (REALM_LIKELY(!get_client().is_dry_run())) {
9,612✔
1653
        // The reason we need a mutable reference from get_client_reset_config() is because we
4,632✔
1654
        // don't want the session to keep a strong reference to the client_reset_config->fresh_copy
4,632✔
1655
        // DB. If it did, then the fresh DB would stay alive for the duration of this sync session
4,632✔
1656
        // and we want to clean it up once the reset is finished. Additionally, the fresh copy will
4,632✔
1657
        // be set to a new copy on every reset so there is no reason to keep a reference to it.
4,632✔
1658
        // The modification to the client reset config happens via std::move(client_reset_config->fresh_copy).
4,632✔
1659
        // If the client reset config were a `const &` then this std::move would create another strong
4,632✔
1660
        // reference which we don't want to happen.
4,632✔
1661
        util::Optional<ClientReset>& client_reset_config = get_client_reset_config();
9,612✔
1662

4,632✔
1663
        bool file_exists = util::File::exists(get_realm_path());
9,612✔
1664

4,632✔
1665
        logger.info("client_reset_config = %1, Realm exists = %2, "
9,612✔
1666
                    "client reset = %3",
9,612✔
1667
                    client_reset_config ? "true" : "false", file_exists ? "true" : "false",
9,604✔
1668
                    (client_reset_config && file_exists) ? "true" : "false"); // Throws
9,612✔
1669
        if (client_reset_config && !m_client_reset_operation) {
9,612✔
1670
            m_client_reset_operation = std::make_unique<_impl::ClientResetOperation>(
336✔
1671
                logger, get_db(), std::move(client_reset_config->fresh_copy), client_reset_config->mode,
336✔
1672
                std::move(client_reset_config->notify_before_client_reset),
336✔
1673
                std::move(client_reset_config->notify_after_client_reset),
336✔
1674
                client_reset_config->recovery_is_allowed); // Throws
336✔
1675
        }
336✔
1676

4,632✔
1677
        if (!m_client_reset_operation) {
9,612✔
1678
            const ClientReplication& repl = access_realm(); // Throws
9,276✔
1679
            repl.get_history().get_status(m_last_version_available, m_client_file_ident, m_progress,
9,276✔
1680
                                          &has_pending_client_reset); // Throws
9,276✔
1681
        }
9,276✔
1682
    }
9,612✔
1683
    logger.debug("client_file_ident = %1, client_file_ident_salt = %2", m_client_file_ident.ident,
9,610✔
1684
                 m_client_file_ident.salt); // Throws
9,610✔
1685
    m_upload_progress = m_progress.upload;
9,610✔
1686
    m_last_version_selected_for_upload = m_upload_progress.client_version;
9,610✔
1687
    m_download_progress = m_progress.download;
9,610✔
1688
    REALM_ASSERT_3(m_last_version_available, >=, m_progress.upload.client_version);
9,610✔
1689

4,632✔
1690
    logger.debug("last_version_available  = %1", m_last_version_available);           // Throws
9,610✔
1691
    logger.debug("progress_download_server_version = %1", m_progress.download.server_version); // Throws
9,610✔
1692
    logger.debug("progress_download_client_version = %1",
9,610✔
1693
                 m_progress.download.last_integrated_client_version);                                      // Throws
9,610✔
1694
    logger.debug("progress_upload_server_version = %1", m_progress.upload.last_integrated_server_version); // Throws
9,610✔
1695
    logger.debug("progress_upload_client_version = %1", m_progress.upload.client_version);                 // Throws
9,610✔
1696

4,632✔
1697
    reset_protocol_state();
9,610✔
1698
    m_state = Active;
9,610✔
1699

4,632✔
1700
    REALM_ASSERT(!m_suspended);
9,610✔
1701
    m_conn.one_more_active_unsuspended_session(); // Throws
9,610✔
1702

4,632✔
1703
    try {
9,610✔
1704
        process_pending_flx_bootstrap();
9,610✔
1705
    }
9,610✔
1706
    catch (const IntegrationException& error) {
4,634✔
1707
        logger.error("Error integrating bootstrap changesets: %1", error.what());
4✔
1708
        m_suspended = true;
4✔
1709
        m_conn.one_less_active_unsuspended_session(); // Throws
4✔
1710
        on_suspended(SessionErrorInfo{Status{error.code(), error.what()}, IsFatal{true}});
4✔
1711
    }
4✔
1712

4,632✔
1713
    if (has_pending_client_reset) {
9,610✔
1714
        handle_pending_client_reset_acknowledgement();
22✔
1715
    }
22✔
1716
}
9,610✔
1717

1718

1719
// The caller (Connection) must discard the session if the session has become
1720
// deactivated upon return.
1721
void Session::initiate_deactivation()
1722
{
9,612✔
1723
    REALM_ASSERT_EX(m_state == Active, m_state);
9,612✔
1724

4,632✔
1725
    logger.debug("Initiating deactivation"); // Throws
9,612✔
1726

4,632✔
1727
    m_state = Deactivating;
9,612✔
1728

4,632✔
1729
    if (!m_suspended)
9,612✔
1730
        m_conn.one_less_active_unsuspended_session(); // Throws
9,090✔
1731

4,632✔
1732
    if (m_enlisted_to_send) {
9,612✔
1733
        REALM_ASSERT(!unbind_process_complete());
4,668✔
1734
        return;
4,668✔
1735
    }
4,668✔
1736

2,284✔
1737
    // Deactivate immediately if the BIND message has not yet been sent and the
2,284✔
1738
    // session is not enlisted to send, or if the unbinding process has already
2,284✔
1739
    // completed.
2,284✔
1740
    if (!m_bind_message_sent || unbind_process_complete()) {
4,944✔
1741
        complete_deactivation(); // Throws
994✔
1742
        // Life cycle state is now Deactivated
396✔
1743
        return;
994✔
1744
    }
994✔
1745

1,888✔
1746
    // Ready to send the UNBIND message, if it has not already been sent
1,888✔
1747
    if (!m_unbind_message_sent) {
3,950✔
1748
        enlist_to_send(); // Throws
3,770✔
1749
        return;
3,770✔
1750
    }
3,770✔
1751
}
3,950✔
1752

1753

1754
void Session::complete_deactivation()
1755
{
9,614✔
1756
    REALM_ASSERT_EX(m_state == Deactivating, m_state);
9,614✔
1757
    m_state = Deactivated;
9,614✔
1758

4,632✔
1759
    logger.debug("Deactivation completed"); // Throws
9,614✔
1760
}
9,614✔
1761

1762

1763
// Called by the associated Connection object when this session is granted an
1764
// opportunity to send a message.
1765
//
1766
// The caller (Connection) must discard the session if the session has become
1767
// deactivated upon return.
1768
void Session::send_message()
1769
{
158,564✔
1770
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
158,564✔
1771
    REALM_ASSERT(m_enlisted_to_send);
158,564✔
1772
    m_enlisted_to_send = false;
158,564✔
1773
    if (m_state == Deactivating || m_error_message_received || m_suspended) {
158,564✔
1774
        // Deactivation has been initiated. If the UNBIND message has not been
4,366✔
1775
        // sent yet, there is no point in sending it. Instead, we can let the
4,366✔
1776
        // deactivation process complete.
4,366✔
1777
        if (!m_bind_message_sent) {
8,924✔
1778
            return complete_deactivation(); // Throws
2,090✔
1779
            // Life cycle state is now Deactivated
1,278✔
1780
        }
2,090✔
1781

3,088✔
1782
        // Session life cycle state is Deactivating or the unbinding process has
3,088✔
1783
        // been initiated by a session specific ERROR message
3,088✔
1784
        if (!m_unbind_message_sent)
6,834✔
1785
            send_unbind_message(); // Throws
6,834✔
1786
        return;
6,834✔
1787
    }
6,834✔
1788

72,120✔
1789
    // Session life cycle state is Active and the unbinding process has
72,120✔
1790
    // not been initiated
72,120✔
1791
    REALM_ASSERT(!m_unbind_message_sent);
149,640✔
1792

72,120✔
1793
    if (!m_bind_message_sent)
149,640✔
1794
        return send_bind_message(); // Throws
9,220✔
1795

67,672✔
1796
    if (!m_ident_message_sent) {
140,420✔
1797
        if (have_client_file_ident())
7,526✔
1798
            send_ident_message(); // Throws
7,526✔
1799
        return;
7,526✔
1800
    }
7,526✔
1801

64,294✔
1802
    const auto has_pending_test_command = std::any_of(m_pending_test_commands.begin(), m_pending_test_commands.end(),
132,894✔
1803
                                                      [](const PendingTestCommand& command) {
64,366✔
1804
                                                          return command.pending;
144✔
1805
                                                      });
144✔
1806
    if (has_pending_test_command) {
132,894✔
1807
        return send_test_command_message();
44✔
1808
    }
44✔
1809

64,272✔
1810
    if (m_error_to_send)
132,850✔
1811
        return send_json_error_message(); // Throws
26✔
1812

64,260✔
1813
    // Stop sending upload, mark and query messages when the client detects an error.
64,260✔
1814
    if (m_client_error) {
132,824✔
1815
        return;
16✔
1816
    }
16✔
1817

64,252✔
1818
    if (m_target_download_mark > m_last_download_mark_sent)
132,808✔
1819
        return send_mark_message(); // Throws
17,124✔
1820

56,218✔
1821
    auto is_upload_allowed = [&]() -> bool {
115,688✔
1822
        if (!m_is_flx_sync_session) {
115,688✔
1823
            return true;
104,704✔
1824
        }
104,704✔
1825

5,678✔
1826
        auto migration_store = get_migration_store();
10,984✔
1827
        if (!migration_store) {
10,984✔
UNCOV
1828
            return true;
×
UNCOV
1829
        }
×
1830

5,678✔
1831
        auto sentinel_query_version = migration_store->get_sentinel_subscription_set_version();
10,984✔
1832
        if (!sentinel_query_version) {
10,984✔
1833
            return true;
10,954✔
1834
        }
10,954✔
1835

14✔
1836
        // Do not allow upload if the last query sent is the sentinel one used by the migration store.
14✔
1837
        return m_last_sent_flx_query_version != *sentinel_query_version;
30✔
1838
    };
30✔
1839

56,218✔
1840
    if (!is_upload_allowed()) {
115,684✔
1841
        return;
16✔
1842
    }
16✔
1843

56,210✔
1844
    auto check_pending_flx_version = [&]() -> bool {
115,672✔
1845
        if (!m_is_flx_sync_session) {
115,672✔
1846
            return false;
104,704✔
1847
        }
104,704✔
1848

5,670✔
1849
        if (!m_allow_upload) {
10,968✔
1850
            return false;
2,182✔
1851
        }
2,182✔
1852

4,572✔
1853
        m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(
8,786✔
1854
            m_last_sent_flx_query_version, m_upload_progress.client_version);
8,786✔
1855

4,572✔
1856
        if (!m_pending_flx_sub_set) {
8,786✔
1857
            return false;
7,310✔
1858
        }
7,310✔
1859

736✔
1860
        return m_upload_progress.client_version >= m_pending_flx_sub_set->snapshot_version;
1,476✔
1861
    };
1,476✔
1862

56,210✔
1863
    if (check_pending_flx_version()) {
115,668✔
1864
        return send_query_change_message(); // throws
834✔
1865
    }
834✔
1866

55,794✔
1867
    if (m_allow_upload && (m_last_version_available > m_upload_progress.client_version)) {
114,834✔
1868
        return send_upload_message(); // Throws
55,734✔
1869
    }
55,734✔
1870
}
114,834✔
1871

1872

1873
void Session::send_bind_message()
1874
{
9,220✔
1875
    REALM_ASSERT_EX(m_state == Active, m_state);
9,220✔
1876

4,448✔
1877
    session_ident_type session_ident = m_ident;
9,220✔
1878
    bool need_client_file_ident = !have_client_file_ident();
9,220✔
1879
    const bool is_subserver = false;
9,220✔
1880

4,448✔
1881

4,448✔
1882
    ClientProtocol& protocol = m_conn.get_client_protocol();
9,220✔
1883
    int protocol_version = m_conn.get_negotiated_protocol_version();
9,220✔
1884
    OutputBuffer& out = m_conn.get_output_buffer();
9,220✔
1885
    // Discard the token since it's ignored by the server.
4,448✔
1886
    std::string empty_access_token;
9,220✔
1887
    if (m_is_flx_sync_session) {
9,220✔
1888
        nlohmann::json bind_json_data;
1,362✔
1889
        if (auto migrated_partition = get_migration_store()->get_migrated_partition()) {
1,362✔
1890
            bind_json_data["migratedPartition"] = *migrated_partition;
60✔
1891
        }
60✔
1892
        bind_json_data["sessionReason"] = static_cast<uint64_t>(get_session_reason());
1,362✔
1893
        if (logger.would_log(util::Logger::Level::debug)) {
1,362✔
1894
            std::string json_data_dump;
1,362✔
1895
            if (!bind_json_data.empty()) {
1,362✔
1896
                json_data_dump = bind_json_data.dump();
1,362✔
1897
            }
1,362✔
1898
            logger.debug(
1,362✔
1899
                "Sending: BIND(session_ident=%1, need_client_file_ident=%2, is_subserver=%3, json_data=\"%4\")",
1,362✔
1900
                session_ident, need_client_file_ident, is_subserver, json_data_dump);
1,362✔
1901
        }
1,362✔
1902
        protocol.make_flx_bind_message(protocol_version, out, session_ident, bind_json_data, empty_access_token,
1,362✔
1903
                                       need_client_file_ident, is_subserver); // Throws
1,362✔
1904
    }
1,362✔
1905
    else {
7,858✔
1906
        std::string server_path = get_virt_path();
7,858✔
1907
        logger.debug("Sending: BIND(session_ident=%1, need_client_file_ident=%2, is_subserver=%3, server_path=%4)",
7,858✔
1908
                     session_ident, need_client_file_ident, is_subserver, server_path);
7,858✔
1909
        protocol.make_pbs_bind_message(protocol_version, out, session_ident, server_path, empty_access_token,
7,858✔
1910
                                       need_client_file_ident, is_subserver); // Throws
7,858✔
1911
    }
7,858✔
1912
    m_conn.initiate_write_message(out, this); // Throws
9,220✔
1913

4,448✔
1914
    m_bind_message_sent = true;
9,220✔
1915

4,448✔
1916
    // Ready to send the IDENT message if the file identifier pair is already
4,448✔
1917
    // available.
4,448✔
1918
    if (!need_client_file_ident)
9,220✔
1919
        enlist_to_send(); // Throws
4,456✔
1920
}
9,220✔
1921

1922

1923
void Session::send_ident_message()
1924
{
7,526✔
1925
    REALM_ASSERT_EX(m_state == Active, m_state);
7,526✔
1926
    REALM_ASSERT(m_bind_message_sent);
7,526✔
1927
    REALM_ASSERT(!m_unbind_message_sent);
7,526✔
1928
    REALM_ASSERT(have_client_file_ident());
7,526✔
1929

3,378✔
1930

3,378✔
1931
    ClientProtocol& protocol = m_conn.get_client_protocol();
7,526✔
1932
    OutputBuffer& out = m_conn.get_output_buffer();
7,526✔
1933
    session_ident_type session_ident = m_ident;
7,526✔
1934

3,378✔
1935
    if (m_is_flx_sync_session) {
7,526✔
1936
        const auto active_query_set = get_flx_subscription_store()->get_active();
962✔
1937
        const auto active_query_body = active_query_set.to_ext_json();
962✔
1938
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
962✔
1939
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
962✔
1940
                     "latest_server_version_salt=%6, query_version=%7, query_size=%8, query=\"%9\")",
962✔
1941
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
962✔
1942
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
962✔
1943
                     m_progress.latest_server_version.salt, active_query_set.version(), active_query_body.size(),
962✔
1944
                     active_query_body); // Throws
962✔
1945
        protocol.make_flx_ident_message(out, session_ident, m_client_file_ident, m_progress,
962✔
1946
                                        active_query_set.version(), active_query_body); // Throws
962✔
1947
        m_last_sent_flx_query_version = active_query_set.version();
962✔
1948
    }
962✔
1949
    else {
6,564✔
1950
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
6,564✔
1951
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
6,564✔
1952
                     "latest_server_version_salt=%6)",
6,564✔
1953
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
6,564✔
1954
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
6,564✔
1955
                     m_progress.latest_server_version.salt);                                  // Throws
6,564✔
1956
        protocol.make_pbs_ident_message(out, session_ident, m_client_file_ident, m_progress); // Throws
6,564✔
1957
    }
6,564✔
1958
    m_conn.initiate_write_message(out, this); // Throws
7,526✔
1959

3,378✔
1960
    m_ident_message_sent = true;
7,526✔
1961

3,378✔
1962
    // Other messages may be waiting to be sent
3,378✔
1963
    enlist_to_send(); // Throws
7,526✔
1964
}
7,526✔
1965

1966
void Session::send_query_change_message()
1967
{
834✔
1968
    REALM_ASSERT_EX(m_state == Active, m_state);
834✔
1969
    REALM_ASSERT(m_ident_message_sent);
834✔
1970
    REALM_ASSERT(!m_unbind_message_sent);
834✔
1971
    REALM_ASSERT(m_pending_flx_sub_set);
834✔
1972
    REALM_ASSERT_3(m_pending_flx_sub_set->query_version, >, m_last_sent_flx_query_version);
834✔
1973

416✔
1974
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
834✔
UNCOV
1975
        return;
×
UNCOV
1976
    }
×
1977

416✔
1978
    auto sub_store = get_flx_subscription_store();
834✔
1979
    auto latest_sub_set = sub_store->get_by_version(m_pending_flx_sub_set->query_version);
834✔
1980
    auto latest_queries = latest_sub_set.to_ext_json();
834✔
1981
    logger.debug("Sending: QUERY(query_version=%1, query_size=%2, query=\"%3\", snapshot_version=%4)",
834✔
1982
                 latest_sub_set.version(), latest_queries.size(), latest_queries, latest_sub_set.snapshot_version());
834✔
1983

416✔
1984
    OutputBuffer& out = m_conn.get_output_buffer();
834✔
1985
    session_ident_type session_ident = get_ident();
834✔
1986
    ClientProtocol& protocol = m_conn.get_client_protocol();
834✔
1987
    protocol.make_query_change_message(out, session_ident, latest_sub_set.version(), latest_queries);
834✔
1988
    m_conn.initiate_write_message(out, this);
834✔
1989

416✔
1990
    m_last_sent_flx_query_version = latest_sub_set.version();
834✔
1991

416✔
1992
    request_download_completion_notification();
834✔
1993
}
834✔
1994

1995
void Session::send_upload_message()
1996
{
55,734✔
1997
    REALM_ASSERT_EX(m_state == Active, m_state);
55,734✔
1998
    REALM_ASSERT(m_ident_message_sent);
55,734✔
1999
    REALM_ASSERT(!m_unbind_message_sent);
55,734✔
2000

28,116✔
2001
    if (REALM_UNLIKELY(get_client().is_dry_run()))
55,734✔
2002
        return;
28,116✔
2003

28,116✔
2004
    version_type target_upload_version = get_db()->get_version_of_latest_snapshot();
55,734✔
2005
    if (m_pending_flx_sub_set) {
55,734✔
2006
        REALM_ASSERT(m_is_flx_sync_session);
642✔
2007
        target_upload_version = m_pending_flx_sub_set->snapshot_version;
642✔
2008
    }
642✔
2009
    if (target_upload_version > m_last_version_available) {
55,734✔
2010
        m_last_version_available = target_upload_version;
558✔
2011
    }
558✔
2012

28,116✔
2013
    const ClientReplication& repl = access_realm(); // Throws
55,734✔
2014

28,116✔
2015
    std::vector<UploadChangeset> uploadable_changesets;
55,734✔
2016
    version_type locked_server_version = 0;
55,734✔
2017
    repl.get_history().find_uploadable_changesets(m_upload_progress, target_upload_version, uploadable_changesets,
55,734✔
2018
                                                  locked_server_version); // Throws
55,734✔
2019

28,116✔
2020
    if (uploadable_changesets.empty()) {
55,734✔
2021
        // Nothing more to upload right now
13,840✔
2022
        check_for_upload_completion(); // Throws
28,702✔
2023
        // If we need to limit upload up to some version other than the last client version available and there are no
13,840✔
2024
        // changes to upload, then there is no need to send an empty message.
13,840✔
2025
        if (m_pending_flx_sub_set) {
28,702✔
2026
            logger.debug("Empty UPLOAD was skipped (progress_client_version=%1, progress_server_version=%2)",
208✔
2027
                         m_upload_progress.client_version, m_upload_progress.last_integrated_server_version);
208✔
2028
            // Other messages may be waiting to be sent
104✔
2029
            return enlist_to_send(); // Throws
208✔
2030
        }
208✔
2031
    }
27,032✔
2032
    else {
27,032✔
2033
        m_last_version_selected_for_upload = uploadable_changesets.back().progress.client_version;
27,032✔
2034
    }
27,032✔
2035

28,116✔
2036
    if (m_pending_flx_sub_set && target_upload_version < m_last_version_available) {
55,630✔
2037
        logger.trace("Limiting UPLOAD message up to version %1 to send QUERY version %2",
434✔
2038
                     m_pending_flx_sub_set->snapshot_version, m_pending_flx_sub_set->query_version);
434✔
2039
    }
434✔
2040

28,012✔
2041
    version_type progress_client_version = m_upload_progress.client_version;
55,526✔
2042
    version_type progress_server_version = m_upload_progress.last_integrated_server_version;
55,526✔
2043

28,012✔
2044
    logger.debug("Sending: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
55,526✔
2045
                 "locked_server_version=%3, num_changesets=%4)",
55,526✔
2046
                 progress_client_version, progress_server_version, locked_server_version,
55,526✔
2047
                 uploadable_changesets.size()); // Throws
55,526✔
2048

28,012✔
2049
    ClientProtocol& protocol = m_conn.get_client_protocol();
55,526✔
2050
    ClientProtocol::UploadMessageBuilder upload_message_builder = protocol.make_upload_message_builder(); // Throws
55,526✔
2051

28,012✔
2052
    for (const UploadChangeset& uc : uploadable_changesets) {
49,690✔
2053
        logger.debug("Fetching changeset for upload (client_version=%1, server_version=%2, "
41,976✔
2054
                     "changeset_size=%3, origin_timestamp=%4, origin_file_ident=%5)",
41,976✔
2055
                     uc.progress.client_version, uc.progress.last_integrated_server_version, uc.changeset.size(),
41,976✔
2056
                     uc.origin_timestamp, uc.origin_file_ident); // Throws
41,976✔
2057
        if (logger.would_log(util::Logger::Level::trace)) {
41,976✔
2058
            BinaryData changeset_data = uc.changeset.get_first_chunk();
×
2059
            if (changeset_data.size() < 1024) {
×
2060
                logger.trace("Changeset: %1",
×
2061
                             _impl::clamped_hex_dump(changeset_data)); // Throws
×
2062
            }
×
2063
            else {
×
2064
                logger.trace("Changeset(comp): %1 %2", changeset_data.size(),
×
2065
                             protocol.compressed_hex_dump(changeset_data));
×
2066
            }
×
2067

UNCOV
2068
#if REALM_DEBUG
×
UNCOV
2069
            ChunkedBinaryInputStream in{changeset_data};
×
UNCOV
2070
            Changeset log;
×
UNCOV
2071
            try {
×
UNCOV
2072
                parse_changeset(in, log);
×
UNCOV
2073
                std::stringstream ss;
×
UNCOV
2074
                log.print(ss);
×
UNCOV
2075
                logger.trace("Changeset (parsed):\n%1", ss.str());
×
UNCOV
2076
            }
×
UNCOV
2077
            catch (const BadChangesetError& err) {
×
UNCOV
2078
                logger.error("Unable to parse changeset: %1", err.what());
×
UNCOV
2079
            }
×
UNCOV
2080
#endif
×
UNCOV
2081
        }
×
2082

20,298✔
2083
#if 0 // Upload log compaction is currently not implemented
2084
        if (!get_client().m_disable_upload_compaction) {
2085
            ChangesetEncoder::Buffer encode_buffer;
2086

2087
            {
2088
                // Upload compaction only takes place within single changesets to
2089
                // avoid another client seeing inconsistent snapshots.
2090
                ChunkedBinaryInputStream stream{uc.changeset};
2091
                Changeset changeset;
2092
                parse_changeset(stream, changeset); // Throws
2093
                // FIXME: What is the point of setting these? How can compaction care about them?
2094
                changeset.version = uc.progress.client_version;
2095
                changeset.last_integrated_remote_version = uc.progress.last_integrated_server_version;
2096
                changeset.origin_timestamp = uc.origin_timestamp;
2097
                changeset.origin_file_ident = uc.origin_file_ident;
2098

2099
                compact_changesets(&changeset, 1);
2100
                encode_changeset(changeset, encode_buffer);
2101

2102
                logger.debug("Upload compaction: original size = %1, compacted size = %2", uc.changeset.size(),
2103
                             encode_buffer.size()); // Throws
2104
            }
2105

2106
            upload_message_builder.add_changeset(
2107
                uc.progress.client_version, uc.progress.last_integrated_server_version, uc.origin_timestamp,
2108
                uc.origin_file_ident, BinaryData{encode_buffer.data(), encode_buffer.size()}); // Throws
2109
        }
2110
        else
2111
#endif
2112
        {
41,976✔
2113
            upload_message_builder.add_changeset(uc.progress.client_version,
41,976✔
2114
                                                 uc.progress.last_integrated_server_version, uc.origin_timestamp,
41,976✔
2115
                                                 uc.origin_file_ident,
41,976✔
2116
                                                 uc.changeset); // Throws
41,976✔
2117
        }
41,976✔
2118
    }
41,976✔
2119

28,012✔
2120
    int protocol_version = m_conn.get_negotiated_protocol_version();
55,526✔
2121
    OutputBuffer& out = m_conn.get_output_buffer();
55,526✔
2122
    session_ident_type session_ident = get_ident();
55,526✔
2123
    upload_message_builder.make_upload_message(protocol_version, out, session_ident, progress_client_version,
55,526✔
2124
                                               progress_server_version,
55,526✔
2125
                                               locked_server_version); // Throws
55,526✔
2126
    m_conn.initiate_write_message(out, this);                          // Throws
55,526✔
2127

28,012✔
2128
    // Other messages may be waiting to be sent
28,012✔
2129
    enlist_to_send(); // Throws
55,526✔
2130
}
55,526✔
2131

2132

2133
void Session::send_mark_message()
2134
{
17,126✔
2135
    REALM_ASSERT_EX(m_state == Active, m_state);
17,126✔
2136
    REALM_ASSERT(m_ident_message_sent);
17,126✔
2137
    REALM_ASSERT(!m_unbind_message_sent);
17,126✔
2138
    REALM_ASSERT_3(m_target_download_mark, >, m_last_download_mark_sent);
17,126✔
2139

8,034✔
2140
    request_ident_type request_ident = m_target_download_mark;
17,126✔
2141
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
17,126✔
2142

8,034✔
2143
    ClientProtocol& protocol = m_conn.get_client_protocol();
17,126✔
2144
    OutputBuffer& out = m_conn.get_output_buffer();
17,126✔
2145
    session_ident_type session_ident = get_ident();
17,126✔
2146
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
17,126✔
2147
    m_conn.initiate_write_message(out, this);                      // Throws
17,126✔
2148

8,034✔
2149
    m_last_download_mark_sent = request_ident;
17,126✔
2150

8,034✔
2151
    // Other messages may be waiting to be sent
8,034✔
2152
    enlist_to_send(); // Throws
17,126✔
2153
}
17,126✔
2154

2155

2156
void Session::send_unbind_message()
2157
{
6,834✔
2158
    REALM_ASSERT_EX(m_state == Deactivating || m_error_message_received || m_suspended, m_state);
6,834✔
2159
    REALM_ASSERT(m_bind_message_sent);
6,834✔
2160
    REALM_ASSERT(!m_unbind_message_sent);
6,834✔
2161

3,088✔
2162
    logger.debug("Sending: UNBIND"); // Throws
6,834✔
2163

3,088✔
2164
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,834✔
2165
    OutputBuffer& out = m_conn.get_output_buffer();
6,834✔
2166
    session_ident_type session_ident = get_ident();
6,834✔
2167
    protocol.make_unbind_message(out, session_ident); // Throws
6,834✔
2168
    m_conn.initiate_write_message(out, this);         // Throws
6,834✔
2169

3,088✔
2170
    m_unbind_message_sent = true;
6,834✔
2171
}
6,834✔
2172

2173

2174
void Session::send_json_error_message()
2175
{
26✔
2176
    REALM_ASSERT_EX(m_state == Active, m_state);
26✔
2177
    REALM_ASSERT(m_ident_message_sent);
26✔
2178
    REALM_ASSERT(!m_unbind_message_sent);
26✔
2179
    REALM_ASSERT(m_error_to_send);
26✔
2180
    REALM_ASSERT(m_client_error);
26✔
2181

12✔
2182
    ClientProtocol& protocol = m_conn.get_client_protocol();
26✔
2183
    OutputBuffer& out = m_conn.get_output_buffer();
26✔
2184
    session_ident_type session_ident = get_ident();
26✔
2185
    auto protocol_error = m_client_error->error_for_server;
26✔
2186

12✔
2187
    auto message = util::format("%1", m_client_error->to_status());
26✔
2188
    logger.info("Sending: ERROR \"%1\" (error_code=%2, session_ident=%3)", message, static_cast<int>(protocol_error),
26✔
2189
                session_ident); // Throws
26✔
2190

12✔
2191
    nlohmann::json error_body_json;
26✔
2192
    error_body_json["message"] = std::move(message);
26✔
2193
    protocol.make_json_error_message(out, session_ident, static_cast<int>(protocol_error),
26✔
2194
                                     error_body_json.dump()); // Throws
26✔
2195
    m_conn.initiate_write_message(out, this);                 // Throws
26✔
2196

12✔
2197
    m_error_to_send = false;
26✔
2198
    enlist_to_send(); // Throws
26✔
2199
}
26✔
2200

2201

2202
void Session::send_test_command_message()
2203
{
44✔
2204
    REALM_ASSERT_EX(m_state == Active, m_state);
44✔
2205

22✔
2206
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
44✔
2207
                           [](const PendingTestCommand& command) {
44✔
2208
                               return command.pending;
44✔
2209
                           });
44✔
2210
    REALM_ASSERT(it != m_pending_test_commands.end());
44✔
2211

22✔
2212
    ClientProtocol& protocol = m_conn.get_client_protocol();
44✔
2213
    OutputBuffer& out = m_conn.get_output_buffer();
44✔
2214
    auto session_ident = get_ident();
44✔
2215

22✔
2216
    logger.info("Sending: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", it->body, session_ident, it->id);
44✔
2217
    protocol.make_test_command_message(out, session_ident, it->id, it->body);
44✔
2218

22✔
2219
    m_conn.initiate_write_message(out, this); // Throws;
44✔
2220
    it->pending = false;
44✔
2221

22✔
2222
    enlist_to_send();
44✔
2223
}
44✔
2224

2225

2226
Status Session::receive_ident_message(SaltedFileIdent client_file_ident)
2227
{
3,220✔
2228
    logger.debug("Received: IDENT(client_file_ident=%1, client_file_ident_salt=%2)", client_file_ident.ident,
3,220✔
2229
                 client_file_ident.salt); // Throws
3,220✔
2230

1,520✔
2231
    // Ignore the message if the deactivation process has been initiated,
1,520✔
2232
    // because in that case, the associated Realm and SessionWrapper must
1,520✔
2233
    // not be accessed any longer.
1,520✔
2234
    if (m_state != Active)
3,220✔
2235
        return Status::OK(); // Success
40✔
2236

1,508✔
2237
    bool legal_at_this_time = (m_bind_message_sent && !have_client_file_ident() && !m_error_message_received &&
3,180✔
2238
                               !m_unbound_message_received);
3,180✔
2239
    if (REALM_UNLIKELY(!legal_at_this_time)) {
3,180✔
UNCOV
2240
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received IDENT message when it was not legal"};
×
UNCOV
2241
    }
×
2242
    if (REALM_UNLIKELY(client_file_ident.ident < 1)) {
3,180✔
UNCOV
2243
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier in IDENT message"};
×
UNCOV
2244
    }
×
2245
    if (REALM_UNLIKELY(client_file_ident.salt == 0)) {
3,180✔
UNCOV
2246
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier salt in IDENT message"};
×
UNCOV
2247
    }
×
2248

1,508✔
2249
    m_client_file_ident = client_file_ident;
3,180✔
2250

1,508✔
2251
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
3,180✔
2252
        // Ready to send the IDENT message
UNCOV
2253
        ensure_enlisted_to_send(); // Throws
×
UNCOV
2254
        return Status::OK();       // Success
×
UNCOV
2255
    }
×
2256

1,508✔
2257
    // access before the client reset (if applicable) because
1,508✔
2258
    // the reset can take a while and the sync session might have died
1,508✔
2259
    // by the time the reset finishes.
1,508✔
2260
    ClientReplication& repl = access_realm(); // Throws
3,180✔
2261

1,508✔
2262
    auto client_reset_if_needed = [&]() -> bool {
3,180✔
2263
        if (!m_client_reset_operation) {
3,180✔
2264
            return false;
2,844✔
2265
        }
2,844✔
2266

168✔
2267
        // ClientResetOperation::finalize() will return true only if the operation actually did
168✔
2268
        // a client reset. It may choose not to do a reset if the local Realm does not exist
168✔
2269
        // at this point (in that case there is nothing to reset). But in any case, we must
168✔
2270
        // clean up m_client_reset_operation at this point as sync should be able to continue from
168✔
2271
        // this point forward.
168✔
2272
        auto client_reset_operation = std::move(m_client_reset_operation);
336✔
2273
        util::UniqueFunction<void(int64_t)> on_flx_subscription_complete = [this](int64_t version) {
220✔
2274
            this->on_flx_sync_version_complete(version);
104✔
2275
        };
104✔
2276
        if (!client_reset_operation->finalize(client_file_ident, get_flx_subscription_store(),
336✔
2277
                                              std::move(on_flx_subscription_complete))) {
168✔
UNCOV
2278
            return false;
×
UNCOV
2279
        }
×
2280

168✔
2281
        // The fresh Realm has been used to reset the state
168✔
2282
        logger.debug("Client reset is completed, path=%1", get_realm_path()); // Throws
336✔
2283

168✔
2284
        SaltedFileIdent client_file_ident;
336✔
2285
        bool has_pending_client_reset = false;
336✔
2286
        repl.get_history().get_status(m_last_version_available, client_file_ident, m_progress,
336✔
2287
                                      &has_pending_client_reset); // Throws
336✔
2288
        REALM_ASSERT_3(m_client_file_ident.ident, ==, client_file_ident.ident);
336✔
2289
        REALM_ASSERT_3(m_client_file_ident.salt, ==, client_file_ident.salt);
336✔
2290
        REALM_ASSERT_EX(m_progress.download.last_integrated_client_version == 0,
336✔
2291
                        m_progress.download.last_integrated_client_version);
336✔
2292
        REALM_ASSERT_EX(m_progress.upload.client_version == 0, m_progress.upload.client_version);
336✔
2293
        REALM_ASSERT_EX(m_progress.upload.last_integrated_server_version == 0,
336✔
2294
                        m_progress.upload.last_integrated_server_version);
336✔
2295
        logger.trace("last_version_available  = %1", m_last_version_available); // Throws
336✔
2296

168✔
2297
        m_upload_progress = m_progress.upload;
336✔
2298
        m_download_progress = m_progress.download;
336✔
2299
        // In recovery mode, there may be new changesets to upload and nothing left to download.
168✔
2300
        // In FLX DiscardLocal mode, there may be new commits due to subscription handling.
168✔
2301
        // For both, we want to allow uploads again without needing external changes to download first.
168✔
2302
        m_allow_upload = true;
336✔
2303
        REALM_ASSERT_EX(m_last_version_selected_for_upload == 0, m_last_version_selected_for_upload);
336✔
2304

168✔
2305
        if (has_pending_client_reset) {
336✔
2306
            handle_pending_client_reset_acknowledgement();
268✔
2307
        }
268✔
2308

168✔
2309
        // If a migration or rollback is in progress, mark it complete when client reset is completed.
168✔
2310
        if (auto migration_store = get_migration_store()) {
336✔
2311
            migration_store->complete_migration_or_rollback();
240✔
2312
        }
240✔
2313

168✔
2314
        return true;
336✔
2315
    };
336✔
2316
    // if a client reset happens, it will take care of setting the file ident
1,508✔
2317
    // and if not, we do it here
1,508✔
2318
    bool did_client_reset = false;
3,180✔
2319
    try {
3,180✔
2320
        did_client_reset = client_reset_if_needed();
3,180✔
2321
    }
3,180✔
2322
    catch (const std::exception& e) {
1,542✔
2323
        auto err_msg = util::format("A fatal error occurred during client reset: '%1'", e.what());
68✔
2324
        logger.error(err_msg.c_str());
68✔
2325
        SessionErrorInfo err_info(Status{ErrorCodes::AutoClientResetFailed, err_msg}, IsFatal{true});
68✔
2326
        suspend(err_info);
68✔
2327
        return Status::OK();
68✔
2328
    }
68✔
2329
    if (!did_client_reset) {
3,112✔
2330
        repl.get_history().set_client_file_ident(client_file_ident,
2,844✔
2331
                                                 m_fix_up_object_ids); // Throws
2,844✔
2332
        m_progress.download.last_integrated_client_version = 0;
2,844✔
2333
        m_progress.upload.client_version = 0;
2,844✔
2334
        m_last_version_selected_for_upload = 0;
2,844✔
2335
    }
2,844✔
2336

1,474✔
2337
    // Ready to send the IDENT message
1,474✔
2338
    ensure_enlisted_to_send(); // Throws
3,112✔
2339
    return Status::OK();       // Success
3,112✔
2340
}
3,112✔
2341

2342
Status Session::receive_download_message(const SyncProgress& progress, std::uint_fast64_t downloadable_bytes,
2343
                                         DownloadBatchState batch_state, int64_t query_version,
2344
                                         const ReceivedChangesets& received_changesets)
2345
{
44,216✔
2346
    REALM_ASSERT_EX(query_version >= 0, query_version);
44,216✔
2347
    // Ignore the message if the deactivation process has been initiated,
23,074✔
2348
    // because in that case, the associated Realm and SessionWrapper must
23,074✔
2349
    // not be accessed any longer.
23,074✔
2350
    if (m_state != Active)
44,216✔
2351
        return Status::OK();
522✔
2352

22,784✔
2353
    if (is_steady_state_download_message(batch_state, query_version)) {
43,694✔
2354
        batch_state = DownloadBatchState::SteadyState;
42,118✔
2355
    }
42,118✔
2356

22,784✔
2357
    logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
43,694✔
2358
                 "latest_server_version=%3, latest_server_version_salt=%4, "
43,694✔
2359
                 "upload_client_version=%5, upload_server_version=%6, downloadable_bytes=%7, "
43,694✔
2360
                 "last_in_batch=%8, query_version=%9, num_changesets=%10, ...)",
43,694✔
2361
                 progress.download.server_version, progress.download.last_integrated_client_version,
43,694✔
2362
                 progress.latest_server_version.version, progress.latest_server_version.salt,
43,694✔
2363
                 progress.upload.client_version, progress.upload.last_integrated_server_version, downloadable_bytes,
43,694✔
2364
                 batch_state != DownloadBatchState::MoreToCome, query_version, received_changesets.size()); // Throws
43,694✔
2365

22,784✔
2366
    // Ignore download messages when the client detects an error. This is to prevent transforming the same bad
22,784✔
2367
    // changeset over and over again.
22,784✔
2368
    if (m_client_error) {
43,694✔
UNCOV
2369
        logger.debug("Ignoring download message because the client detected an integration error");
×
UNCOV
2370
        return Status::OK();
×
UNCOV
2371
    }
×
2372

22,784✔
2373
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
43,694✔
2374
    if (REALM_UNLIKELY(!legal_at_this_time)) {
43,694✔
2375
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received DOWNLOAD message when it was not legal"};
×
UNCOV
2376
    }
×
2377
    if (auto status = check_received_sync_progress(progress); REALM_UNLIKELY(!status.is_ok())) {
43,694✔
UNCOV
2378
        logger.error("Bad sync progress received (%1)", status);
×
UNCOV
2379
        return status;
×
UNCOV
2380
    }
×
2381

22,784✔
2382
    version_type server_version = m_progress.download.server_version;
43,694✔
2383
    version_type last_integrated_client_version = m_progress.download.last_integrated_client_version;
43,694✔
2384
    for (const Transformer::RemoteChangeset& changeset : received_changesets) {
43,472✔
2385
        // Check that per-changeset server version is strictly increasing, except in FLX sync where the server
21,576✔
2386
        // version must be increasing, but can stay the same during bootstraps.
21,576✔
2387
        bool good_server_version = m_is_flx_sync_session ? (changeset.remote_version >= server_version)
22,396✔
2388
                                                         : (changeset.remote_version > server_version);
41,444✔
2389
        // Each server version cannot be greater than the one in the header of the download message.
21,576✔
2390
        good_server_version = good_server_version && (changeset.remote_version <= progress.download.server_version);
42,270✔
2391
        if (!good_server_version) {
42,264✔
UNCOV
2392
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
2393
                    util::format("Bad server version in changeset header (DOWNLOAD) (%1, %2, %3)",
×
UNCOV
2394
                                 changeset.remote_version, server_version, progress.download.server_version)};
×
2395
        }
×
2396
        server_version = changeset.remote_version;
42,264✔
2397
        // Check that per-changeset last integrated client version is "weakly"
21,576✔
2398
        // increasing.
21,576✔
2399
        bool good_client_version =
42,264✔
2400
            (changeset.last_integrated_local_version >= last_integrated_client_version &&
42,264✔
2401
             changeset.last_integrated_local_version <= progress.download.last_integrated_client_version);
42,268✔
2402
        if (!good_client_version) {
42,264✔
UNCOV
2403
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
2404
                    util::format("Bad last integrated client version in changeset header (DOWNLOAD) "
×
UNCOV
2405
                                 "(%1, %2, %3)",
×
UNCOV
2406
                                 changeset.last_integrated_local_version, last_integrated_client_version,
×
UNCOV
2407
                                 progress.download.last_integrated_client_version)};
×
UNCOV
2408
        }
×
2409
        last_integrated_client_version = changeset.last_integrated_local_version;
42,264✔
2410
        // Server shouldn't send our own changes, and zero is not a valid client
21,576✔
2411
        // file identifier.
21,576✔
2412
        bool good_file_ident =
42,264✔
2413
            (changeset.origin_file_ident > 0 && changeset.origin_file_ident != m_client_file_ident.ident);
42,266✔
2414
        if (!good_file_ident) {
42,264✔
UNCOV
2415
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
2416
                    util::format("Bad origin file identifier in changeset header (DOWNLOAD)",
×
UNCOV
2417
                                 changeset.origin_file_ident)};
×
2418
        }
×
2419
    }
42,264✔
2420

22,784✔
2421
    auto hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageReceived, progress, query_version,
43,694✔
2422
                                       batch_state, received_changesets.size());
43,694✔
2423
    if (hook_action == SyncClientHookAction::EarlyReturn) {
43,694✔
2424
        return Status::OK();
12✔
2425
    }
12✔
2426
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
43,682✔
2427

22,778✔
2428
    if (process_flx_bootstrap_message(progress, batch_state, query_version, received_changesets)) {
43,682✔
2429
        clear_resumption_delay_state();
1,566✔
2430
        return Status::OK();
1,566✔
2431
    }
1,566✔
2432

21,994✔
2433
    initiate_integrate_changesets(downloadable_bytes, batch_state, progress, received_changesets); // Throws
42,116✔
2434

21,994✔
2435
    hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
42,116✔
2436
                                  batch_state, received_changesets.size());
42,116✔
2437
    if (hook_action == SyncClientHookAction::EarlyReturn) {
42,116✔
UNCOV
2438
        return Status::OK();
×
UNCOV
2439
    }
×
2440
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
42,116✔
2441

21,994✔
2442
    // When we receive a DOWNLOAD message successfully, we can clear the backoff timer value used to reconnect
21,994✔
2443
    // after a retryable session error.
21,994✔
2444
    clear_resumption_delay_state();
42,116✔
2445
    return Status::OK();
42,116✔
2446
}
42,116✔
2447

2448
Status Session::receive_mark_message(request_ident_type request_ident)
2449
{
16,556✔
2450
    logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
16,556✔
2451

7,742✔
2452
    // Ignore the message if the deactivation process has been initiated,
7,742✔
2453
    // because in that case, the associated Realm and SessionWrapper must
7,742✔
2454
    // not be accessed any longer.
7,742✔
2455
    if (m_state != Active)
16,556✔
2456
        return Status::OK(); // Success
314✔
2457

7,710✔
2458
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
16,242✔
2459
    if (REALM_UNLIKELY(!legal_at_this_time)) {
16,242✔
UNCOV
2460
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received MARK message when it was not legal"};
×
UNCOV
2461
    }
×
2462
    bool good_request_ident =
16,242✔
2463
        (request_ident <= m_last_download_mark_sent && request_ident > m_last_download_mark_received);
16,242✔
2464
    if (REALM_UNLIKELY(!good_request_ident)) {
16,242✔
UNCOV
2465
        return {
×
UNCOV
2466
            ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
2467
            util::format(
×
2468
                "Received MARK message with invalid request identifer (last mark sent: %1 last mark received: %2)",
×
2469
                m_last_download_mark_sent, m_last_download_mark_received)};
×
UNCOV
2470
    }
×
2471

7,710✔
2472
    m_server_version_at_last_download_mark = m_progress.download.server_version;
16,242✔
2473
    m_last_download_mark_received = request_ident;
16,242✔
2474
    check_for_download_completion(); // Throws
16,242✔
2475

7,710✔
2476
    return Status::OK(); // Success
16,242✔
2477
}
16,242✔
2478

2479

2480
// The caller (Connection) must discard the session if the session has become
2481
// deactivated upon return.
2482
Status Session::receive_unbound_message()
2483
{
4,726✔
2484
    logger.debug("Received: UNBOUND");
4,726✔
2485

2,030✔
2486
    bool legal_at_this_time = (m_unbind_message_sent && !m_error_message_received && !m_unbound_message_received);
4,726✔
2487
    if (REALM_UNLIKELY(!legal_at_this_time)) {
4,726✔
UNCOV
2488
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received UNBOUND message when it was not legal"};
×
UNCOV
2489
    }
×
2490

2,030✔
2491
    // The fact that the UNBIND message has been sent, but an ERROR message has
2,030✔
2492
    // not been received, implies that the deactivation process must have been
2,030✔
2493
    // initiated, so this session must be in the Deactivating state or the session
2,030✔
2494
    // has been suspended because of a client side error.
2,030✔
2495
    REALM_ASSERT_EX(m_state == Deactivating || m_suspended, m_state);
4,726!
2496

2,030✔
2497
    m_unbound_message_received = true;
4,726✔
2498

2,030✔
2499
    // Detect completion of the unbinding process
2,030✔
2500
    if (m_unbind_message_send_complete && m_state == Deactivating) {
4,726✔
2501
        // The deactivation process completes when the unbinding process
2,030✔
2502
        // completes.
2,030✔
2503
        complete_deactivation(); // Throws
4,726✔
2504
        // Life cycle state is now Deactivated
2,030✔
2505
    }
4,726✔
2506

2,030✔
2507
    return Status::OK(); // Success
4,726✔
2508
}
4,726✔
2509

2510

2511
Status Session::receive_query_error_message(int error_code, std::string_view message, int64_t query_version)
2512
{
16✔
2513
    logger.info("Received QUERY_ERROR \"%1\" (error_code=%2, query_version=%3)", message, error_code, query_version);
16✔
2514
    // Ignore the message if the deactivation process has been initiated,
8✔
2515
    // because in that case, the associated Realm and SessionWrapper must
8✔
2516
    // not be accessed any longer.
8✔
2517
    if (m_state == Active) {
16✔
2518
        on_flx_sync_error(query_version, message); // throws
16✔
2519
    }
16✔
2520
    return Status::OK();
16✔
2521
}
16✔
2522

2523
// The caller (Connection) must discard the session if the session has become
2524
// deactivated upon return.
2525
Status Session::receive_error_message(const ProtocolErrorInfo& info)
2526
{
892✔
2527
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, error_action=%4)", info.message,
892✔
2528
                info.raw_error_code, info.is_fatal, info.server_requests_action); // Throws
892✔
2529

454✔
2530
    bool legal_at_this_time = (m_bind_message_sent && !m_error_message_received && !m_unbound_message_received);
892✔
2531
    if (REALM_UNLIKELY(!legal_at_this_time)) {
892✔
UNCOV
2532
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received ERROR message when it was not legal"};
×
UNCOV
2533
    }
×
2534

454✔
2535
    auto protocol_error = static_cast<ProtocolError>(info.raw_error_code);
892✔
2536
    auto status = protocol_error_to_status(protocol_error, info.message);
892✔
2537
    if (status != ErrorCodes::UnknownError && REALM_UNLIKELY(!is_session_level_error(protocol_error))) {
892✔
UNCOV
2538
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
2539
                util::format("Received ERROR message for session with non-session-level error code %1",
×
UNCOV
2540
                             info.raw_error_code)};
×
UNCOV
2541
    }
×
2542

454✔
2543
    // Can't process debug hook actions once the Session is undergoing deactivation, since
454✔
2544
    // the SessionWrapper may not be available
454✔
2545
    if (m_state == Active) {
892✔
2546
        auto debug_action = call_debug_hook(SyncClientHookEvent::ErrorMessageReceived, info);
888✔
2547
        if (debug_action == SyncClientHookAction::EarlyReturn) {
888✔
2548
            return Status::OK();
8✔
2549
        }
8✔
2550
    }
884✔
2551

450✔
2552
    // For compensating write errors, we need to defer raising them to the SDK until after the server version
450✔
2553
    // containing the compensating write has appeared in a download message.
450✔
2554
    if (status == ErrorCodes::SyncCompensatingWrite) {
884✔
2555
        // If the client is not active, the compensating writes will not be processed now, but will be
20✔
2556
        // sent again the next time the client connects
20✔
2557
        if (m_state == Active) {
40✔
2558
            REALM_ASSERT(info.compensating_write_server_version.has_value());
40✔
2559
            m_pending_compensating_write_errors.push_back(info);
40✔
2560
        }
40✔
2561
        return Status::OK();
40✔
2562
    }
40✔
2563

430✔
2564
    m_error_message_received = true;
844✔
2565
    suspend(SessionErrorInfo{info, std::move(status)});
844✔
2566
    return Status::OK();
844✔
2567
}
844✔
2568

2569
void Session::suspend(const SessionErrorInfo& info)
2570
{
912✔
2571
    REALM_ASSERT(!m_suspended);
912✔
2572
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
912✔
2573
    logger.debug("Suspended"); // Throws
912✔
2574

464✔
2575
    m_suspended = true;
912✔
2576

464✔
2577
    // Detect completion of the unbinding process
464✔
2578
    if (m_unbind_message_send_complete && m_error_message_received) {
912!
2579
        // The fact that the UNBIND message has been sent, but we are not being suspended because
2580
        // we received an ERROR message implies that the deactivation process must
2581
        // have been initiated, so this session must be in the Deactivating state.
UNCOV
2582
        REALM_ASSERT_EX(m_state == Deactivating, m_state);
×
2583

2584
        // The deactivation process completes when the unbinding process
2585
        // completes.
UNCOV
2586
        complete_deactivation(); // Throws
×
2587
        // Life cycle state is now Deactivated
UNCOV
2588
    }
×
2589

464✔
2590
    // Notify the application of the suspension of the session if the session is
464✔
2591
    // still in the Active state
464✔
2592
    if (m_state == Active) {
912✔
2593
        m_conn.one_less_active_unsuspended_session(); // Throws
908✔
2594
        on_suspended(info);                           // Throws
908✔
2595
    }
908✔
2596

464✔
2597
    if (!info.is_fatal) {
912✔
2598
        begin_resumption_delay(info);
384✔
2599
    }
384✔
2600

464✔
2601
    // Ready to send the UNBIND message, if it has not been sent already
464✔
2602
    if (!m_unbind_message_sent)
912✔
2603
        ensure_enlisted_to_send(); // Throws
908✔
2604
}
912✔
2605

2606
Status Session::receive_test_command_response(request_ident_type ident, std::string_view body)
2607
{
44✔
2608
    logger.info("Received: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", body, m_ident, ident);
44✔
2609
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
44✔
2610
                           [&](const PendingTestCommand& command) {
44✔
2611
                               return command.id == ident;
44✔
2612
                           });
44✔
2613
    if (it == m_pending_test_commands.end()) {
44✔
UNCOV
2614
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
UNCOV
2615
                util::format("Received test command response for a non-existent ident %1", ident)};
×
UNCOV
2616
    }
×
2617

22✔
2618
    it->promise.emplace_value(std::string{body});
44✔
2619
    m_pending_test_commands.erase(it);
44✔
2620

22✔
2621
    return Status::OK();
44✔
2622
}
44✔
2623

2624
void Session::begin_resumption_delay(const ProtocolErrorInfo& error_info)
2625
{
384✔
2626
    REALM_ASSERT(!m_try_again_activation_timer);
384✔
2627

202✔
2628
    m_try_again_delay_info.update(static_cast<sync::ProtocolError>(error_info.raw_error_code),
384✔
2629
                                  error_info.resumption_delay_interval);
384✔
2630
    auto try_again_interval = m_try_again_delay_info.delay_interval();
384✔
2631
    if (ProtocolError(error_info.raw_error_code) == ProtocolError::session_closed) {
384✔
2632
        // FIXME With compensating writes the server sends this error after completing a bootstrap. Doing the
10✔
2633
        // normal backoff behavior would result in waiting up to 5 minutes in between each query change which is
10✔
2634
        // not acceptable latency. So for this error code alone, we hard-code a 1 second retry interval.
10✔
2635
        try_again_interval = std::chrono::milliseconds{1000};
20✔
2636
    }
20✔
2637
    logger.debug("Will attempt to resume session after %1 milliseconds", try_again_interval.count());
384✔
2638
    m_try_again_activation_timer = get_client().create_timer(try_again_interval, [this](Status status) {
384✔
2639
        if (status == ErrorCodes::OperationAborted)
384✔
2640
            return;
4✔
2641
        else if (!status.is_ok())
380✔
UNCOV
2642
            throw Exception(status);
×
2643

200✔
2644
        m_try_again_activation_timer.reset();
380✔
2645
        cancel_resumption_delay();
380✔
2646
    });
380✔
2647
}
384✔
2648

2649
void Session::clear_resumption_delay_state()
2650
{
43,684✔
2651
    if (m_try_again_activation_timer) {
43,684✔
UNCOV
2652
        logger.debug("Clearing resumption delay state after successful download");
×
2653
        m_try_again_delay_info.reset();
×
2654
    }
×
2655
}
43,684✔
2656

2657
Status ClientImpl::Session::check_received_sync_progress(const SyncProgress& progress) noexcept
2658
{
43,694✔
2659
    const SyncProgress& a = m_progress;
43,694✔
2660
    const SyncProgress& b = progress;
43,694✔
2661
    std::string message;
43,694✔
2662
    if (b.latest_server_version.version < a.latest_server_version.version) {
43,694✔
2663
        message = util::format("Latest server version in download messages must be weakly increasing throughout a "
×
2664
                               "session (current: %1, received: %2)",
×
2665
                               a.latest_server_version.version, b.latest_server_version.version);
×
2666
    }
×
2667
    if (b.upload.client_version < a.upload.client_version) {
43,694✔
2668
        message = util::format("Last integrated client version in download messages must be weakly increasing "
×
2669
                               "throughout a session (current: %1, received: %2)",
×
2670
                               a.upload.client_version, b.upload.client_version);
×
2671
    }
×
2672
    if (b.upload.client_version > m_last_version_available) {
43,694✔
UNCOV
2673
        message = util::format("Last integrated client version on server cannot be greater than the latest client "
×
2674
                               "version in existence (current: %1, received: %2)",
×
2675
                               m_last_version_available, b.upload.client_version);
×
2676
    }
×
2677
    if (b.download.server_version < a.download.server_version) {
43,694✔
2678
        message =
×
UNCOV
2679
            util::format("Download cursor must be weakly increasing throughout a session (current: %1, received: %2)",
×
2680
                         a.download.server_version, b.download.server_version);
×
2681
    }
×
2682
    if (b.download.server_version > b.latest_server_version.version) {
43,694✔
2683
        message = util::format(
×
2684
            "Download cursor cannot be greater than the latest server version in existence (cursor: %1, latest: %2)",
×
UNCOV
2685
            b.download.server_version, b.latest_server_version.version);
×
UNCOV
2686
    }
×
2687
    if (b.download.last_integrated_client_version < a.download.last_integrated_client_version) {
43,694✔
UNCOV
2688
        message = util::format(
×
UNCOV
2689
            "Last integrated client version on the server at the position in the server's history of the download "
×
UNCOV
2690
            "cursor must be weakly increasing throughout a session (current: %1, received: %2)",
×
UNCOV
2691
            a.download.last_integrated_client_version, b.download.last_integrated_client_version);
×
UNCOV
2692
    }
×
2693
    if (b.download.last_integrated_client_version > b.upload.client_version) {
43,694✔
UNCOV
2694
        message = util::format("Last integrated client version on the server in the position at the server's history "
×
UNCOV
2695
                               "of the download cursor cannot be greater than the latest client version integrated "
×
UNCOV
2696
                               "on the server (download: %1, upload: %2)",
×
UNCOV
2697
                               b.download.last_integrated_client_version, b.upload.client_version);
×
UNCOV
2698
    }
×
2699
    if (b.download.server_version < b.upload.last_integrated_server_version) {
43,694✔
UNCOV
2700
        message = util::format(
×
UNCOV
2701
            "The server version of the download cursor cannot be less than the server version integrated in the "
×
UNCOV
2702
            "latest client version acknowledged by the server (download: %1, upload: %2)",
×
UNCOV
2703
            b.download.server_version, b.upload.last_integrated_server_version);
×
UNCOV
2704
    }
×
2705

22,784✔
2706
    if (message.empty()) {
43,694✔
2707
        return Status::OK();
43,692✔
2708
    }
43,692✔
2709
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
2✔
2710
}
2✔
2711

2712

2713
void Session::check_for_upload_completion()
2714
{
75,908✔
2715
    REALM_ASSERT_EX(m_state == Active, m_state);
75,908✔
2716
    if (!m_upload_completion_notification_requested) {
75,908✔
2717
        return;
44,168✔
2718
    }
44,168✔
2719

15,114✔
2720
    // during an ongoing client reset operation, we never upload anything
15,114✔
2721
    if (m_client_reset_operation)
31,740✔
2722
        return;
232✔
2723

14,998✔
2724
    // Upload process must have reached end of history
14,998✔
2725
    REALM_ASSERT_3(m_upload_progress.client_version, <=, m_last_version_available);
31,508✔
2726
    bool scan_complete = (m_upload_progress.client_version == m_last_version_available);
31,508✔
2727
    if (!scan_complete)
31,508✔
2728
        return;
5,998✔
2729

12,450✔
2730
    // All uploaded changesets must have been acknowledged by the server
12,450✔
2731
    REALM_ASSERT_3(m_progress.upload.client_version, <=, m_last_version_selected_for_upload);
25,510✔
2732
    bool all_uploads_accepted = (m_progress.upload.client_version == m_last_version_selected_for_upload);
25,510✔
2733
    if (!all_uploads_accepted)
25,510✔
2734
        return;
10,844✔
2735

7,248✔
2736
    m_upload_completion_notification_requested = false;
14,666✔
2737
    on_upload_completion(); // Throws
14,666✔
2738
}
14,666✔
2739

2740

2741
void Session::check_for_download_completion()
2742
{
59,730✔
2743
    REALM_ASSERT_3(m_target_download_mark, >=, m_last_download_mark_received);
59,730✔
2744
    REALM_ASSERT_3(m_last_download_mark_received, >=, m_last_triggering_download_mark);
59,730✔
2745
    if (m_last_download_mark_received == m_last_triggering_download_mark)
59,730✔
2746
        return;
43,280✔
2747
    if (m_last_download_mark_received < m_target_download_mark)
16,450✔
2748
        return;
458✔
2749
    if (m_download_progress.server_version < m_server_version_at_last_download_mark)
15,992✔
UNCOV
2750
        return;
×
2751
    m_last_triggering_download_mark = m_target_download_mark;
15,992✔
2752
    if (REALM_UNLIKELY(!m_allow_upload)) {
15,992✔
2753
        // Activate the upload process now, and enable immediate reactivation
1,984✔
2754
        // after a subsequent fast reconnect.
1,984✔
2755
        m_allow_upload = true;
4,778✔
2756
        ensure_enlisted_to_send(); // Throws
4,778✔
2757
    }
4,778✔
2758
    on_download_completion(); // Throws
15,992✔
2759
}
15,992✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc