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

realm / realm-core / daniel.tabacaru_937

27 Sep 2024 06:53AM UTC coverage: 91.124% (+0.02%) from 91.109%
daniel.tabacaru_937

Pull #7983

Evergreen

danieltabacaru
Small refactoring
Pull Request #7983: RCORE-2126 Clear incomplete bootstraps when the connection is established

102826 of 181492 branches covered (56.66%)

49 of 50 new or added lines in 4 files covered. (98.0%)

67 existing lines in 16 files now uncovered.

217244 of 238404 relevant lines covered (91.12%)

5968864.31 hits per line

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

82.79
/src/realm/sync/noinst/client_impl_base.cpp
1
#include <realm/sync/noinst/client_impl_base.hpp>
2

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

23
#include <system_error>
24
#include <sstream>
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,958✔
48
    m_backoff_state.reset();
1,958✔
49
    scheduled_reset = false;
1,958✔
50
}
1,958✔
51

52

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

59

60
std::chrono::milliseconds ClientImpl::ReconnectInfo::delay_interval()
61
{
6,160✔
62
    if (scheduled_reset) {
6,160✔
63
        reset();
8✔
64
    }
8✔
65

66
    if (!m_backoff_state.triggering_error) {
6,160✔
67
        return std::chrono::milliseconds::zero();
4,704✔
68
    }
4,704✔
69

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

80
            REALM_ASSERT(m_reconnect_mode == ReconnectMode::normal);
356✔
81
            return m_backoff_state.delay_interval();
356✔
82
    }
1,456✔
83
}
1,456✔
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
{
4,398✔
89
    util::Uri uri(url); // Throws
4,398✔
90
    uri.canonicalize(); // Throws
4,398✔
91
    std::string userinfo, address_2, port_2;
4,398✔
92
    bool realm_scheme = (uri.get_scheme() == "realm:" || uri.get_scheme() == "realms:");
4,398✔
93
    bool ws_scheme = (uri.get_scheme() == "ws:" || uri.get_scheme() == "wss:");
4,398✔
94
    bool good = ((realm_scheme || ws_scheme) && uri.get_auth(userinfo, address_2, port_2) && userinfo.empty() &&
4,398✔
95
                 !address_2.empty() && uri.get_query().empty() && uri.get_frag().empty()); // Throws
4,398✔
96
    if (REALM_UNLIKELY(!good))
4,398✔
97
        return false;
×
98
    ProtocolEnvelope protocol_2;
4,398✔
99
    port_type port_3;
4,398✔
100
    if (realm_scheme) {
4,398✔
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 {
4,398✔
111
        REALM_ASSERT(ws_scheme);
4,398✔
112
        if (uri.get_scheme() == "ws:") {
4,398✔
113
            protocol_2 = ProtocolEnvelope::ws;
4,330✔
114
            port_3 = 80;
4,330✔
115
        }
4,330✔
116
        else {
68✔
117
            protocol_2 = ProtocolEnvelope::wss;
68✔
118
            port_3 = 443;
68✔
119
        }
68✔
120
    }
4,398✔
121
    if (!port_2.empty()) {
4,398✔
122
        std::istringstream in(port_2);    // Throws
4,278✔
123
        in.imbue(std::locale::classic()); // Throws
4,278✔
124
        in >> port_3;
4,278✔
125
        if (REALM_UNLIKELY(!in || !in.eof() || port_3 < 1))
4,278✔
126
            return false;
×
127
    }
4,278✔
128
    std::string path_2 = uri.get_path(); // Throws (copy)
4,398✔
129

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

137
ClientImpl::ClientImpl(ClientConfig config)
138
    : logger(std::make_shared<util::CategoryLogger>(util::LogCategory::session, std::move(config.logger)))
4,912✔
139
    , m_reconnect_mode{config.reconnect_mode}
4,912✔
140
    , m_connect_timeout{config.connect_timeout}
4,912✔
141
    , m_connection_linger_time{config.one_connection_per_session ? 0 : config.connection_linger_time}
4,912✔
142
    , m_ping_keepalive_period{config.ping_keepalive_period}
4,912✔
143
    , m_pong_keepalive_timeout{config.pong_keepalive_timeout}
4,912✔
144
    , m_fast_reconnect_limit{config.fast_reconnect_limit}
4,912✔
145
    , m_reconnect_backoff_info{config.reconnect_backoff_info}
4,912✔
146
    , m_disable_upload_activation_delay{config.disable_upload_activation_delay}
4,912✔
147
    , m_dry_run{config.dry_run}
4,912✔
148
    , m_enable_default_port_hack{config.enable_default_port_hack}
4,912✔
149
    , m_fix_up_object_ids{config.fix_up_object_ids}
4,912✔
150
    , m_roundtrip_time_handler{std::move(config.roundtrip_time_handler)}
4,912✔
151
    , m_socket_provider{std::move(config.socket_provider)}
4,912✔
152
    , m_client_protocol{} // Throws
4,912✔
153
    , m_one_connection_per_session{config.one_connection_per_session}
4,912✔
154
    , m_random{}
4,912✔
155
{
9,962✔
156
    // FIXME: Would be better if seeding was up to the application.
157
    util::seed_prng_nondeterministically(m_random); // Throws
9,962✔
158

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

190
    if (config.reconnect_mode != ReconnectMode::normal) {
9,962✔
191
        logger.warn("Testing/debugging feature 'nonnormal reconnect mode' enabled - "
776✔
192
                    "never do this in production!");
776✔
193
    }
776✔
194

195
    if (config.dry_run) {
9,962✔
196
        logger.warn("Testing/debugging feature 'dry run' enabled - "
×
197
                    "never do this in production!");
×
198
    }
×
199

200
    REALM_ASSERT_EX(m_socket_provider, "Must provide socket provider in sync Client config");
9,962✔
201

202
    if (m_one_connection_per_session) {
9,962✔
203
        logger.warn("Testing/debugging feature 'one connection per session' enabled - "
4✔
204
                    "never do this in production");
4✔
205
    }
4✔
206

207
    if (config.disable_upload_activation_delay) {
9,962✔
208
        logger.warn("Testing/debugging feature 'disable_upload_activation_delay' enabled - "
×
209
                    "never do this in production");
×
210
    }
×
211

212
    if (config.disable_sync_to_disk) {
9,962✔
213
        logger.warn("Testing/debugging feature 'disable_sync_to_disk' enabled - "
×
214
                    "never do this in production");
×
215
    }
×
216

217
    m_actualize_and_finalize = create_trigger([this](Status status) {
14,848✔
218
        if (status == ErrorCodes::OperationAborted)
14,848✔
219
            return;
×
220
        else if (!status.is_ok())
14,848✔
221
            throw Exception(status);
×
222
        actualize_and_finalize_session_wrappers(); // Throws
14,848✔
223
    });
14,848✔
224
}
9,962✔
225

226
void ClientImpl::incr_outstanding_posts()
227
{
204,944✔
228
    util::CheckedLockGuard lock(m_drain_mutex);
204,944✔
229
    ++m_outstanding_posts;
204,944✔
230
    m_drained = false;
204,944✔
231
}
204,944✔
232

233
void ClientImpl::decr_outstanding_posts()
234
{
204,946✔
235
    util::CheckedLockGuard lock(m_drain_mutex);
204,946✔
236
    REALM_ASSERT(m_outstanding_posts);
204,946✔
237
    if (--m_outstanding_posts <= 0) {
204,946✔
238
        // Notify must happen with lock held or another thread could destroy
239
        // ClientImpl between when we release the lock and when we call notify
240
        m_drain_cv.notify_all();
18,214✔
241
    }
18,214✔
242
}
204,946✔
243

244
void ClientImpl::post(SyncSocketProvider::FunctionHandler&& handler)
245
{
56,584✔
246
    REALM_ASSERT(m_socket_provider);
56,584✔
247
    incr_outstanding_posts();
56,584✔
248
    m_socket_provider->post([handler = std::move(handler), this](Status status) {
56,590✔
249
        auto decr_guard = util::make_scope_exit([&]() noexcept {
56,590✔
250
            decr_outstanding_posts();
56,590✔
251
        });
56,590✔
252
        handler(status);
56,588✔
253
    });
56,588✔
254
}
56,584✔
255

256
void ClientImpl::post(util::UniqueFunction<void()>&& handler)
257
{
130,250✔
258
    REALM_ASSERT(m_socket_provider);
130,250✔
259
    incr_outstanding_posts();
130,250✔
260
    m_socket_provider->post([handler = std::move(handler), this](Status status) {
130,250✔
261
        auto decr_guard = util::make_scope_exit([&]() noexcept {
130,248✔
262
            decr_outstanding_posts();
130,246✔
263
        });
130,246✔
264
        if (status == ErrorCodes::OperationAborted)
130,246✔
265
            return;
×
266
        if (!status.is_ok())
130,246✔
267
            throw Exception(status);
×
268
        handler();
130,246✔
269
    });
130,246✔
270
}
130,250✔
271

272

273
void ClientImpl::drain_connections()
274
{
9,962✔
275
    logger.debug("Draining connections during sync client shutdown");
9,962✔
276
    for (auto& server_slot_pair : m_server_slots) {
9,962✔
277
        auto& server_slot = server_slot_pair.second;
2,736✔
278

279
        if (server_slot.connection) {
2,736✔
280
            auto& conn = server_slot.connection;
2,516✔
281
            conn->force_close();
2,516✔
282
        }
2,516✔
283
        else {
220✔
284
            for (auto& conn_pair : server_slot.alt_connections) {
220✔
UNCOV
285
                conn_pair.second->force_close();
×
UNCOV
286
            }
×
287
        }
220✔
288
    }
2,736✔
289
}
9,962✔
290

291

292
SyncSocketProvider::SyncTimer ClientImpl::create_timer(std::chrono::milliseconds delay,
293
                                                       SyncSocketProvider::FunctionHandler&& handler)
294
{
18,114✔
295
    REALM_ASSERT(m_socket_provider);
18,114✔
296
    incr_outstanding_posts();
18,114✔
297
    return m_socket_provider->create_timer(delay, [handler = std::move(handler), this](Status status) {
18,118✔
298
        auto decr_guard = util::make_scope_exit([&]() noexcept {
18,116✔
299
            decr_outstanding_posts();
18,114✔
300
        });
18,114✔
301
        handler(status);
18,116✔
302
    });
18,116✔
303
}
18,114✔
304

305

306
ClientImpl::SyncTrigger ClientImpl::create_trigger(SyncSocketProvider::FunctionHandler&& handler)
307
{
12,806✔
308
    REALM_ASSERT(m_socket_provider);
12,806✔
309
    return std::make_unique<Trigger<ClientImpl>>(this, std::move(handler));
12,806✔
310
}
12,806✔
311

312
Connection::~Connection()
313
{
2,840✔
314
    if (m_websocket_sentinel) {
2,840✔
315
        m_websocket_sentinel->destroyed = true;
×
316
        m_websocket_sentinel.reset();
×
317
    }
×
318
}
2,840✔
319

320
void Connection::activate()
321
{
2,844✔
322
    REALM_ASSERT(m_on_idle);
2,844✔
323
    m_activated = true;
2,844✔
324
    if (m_num_active_sessions == 0)
2,844✔
325
        m_on_idle->trigger();
×
326
    // We cannot in general connect immediately, because a prior failure to
327
    // connect may require a delay before reconnecting (see `m_reconnect_info`).
328
    initiate_reconnect_wait(); // Throws
2,844✔
329
}
2,844✔
330

331

332
void Connection::activate_session(std::unique_ptr<Session> sess)
333
{
10,432✔
334
    REALM_ASSERT(sess);
10,432✔
335
    REALM_ASSERT(&sess->m_conn == this);
10,432✔
336
    REALM_ASSERT(!m_force_closed);
10,432✔
337
    Session& sess_2 = *sess;
10,432✔
338
    session_ident_type ident = sess->m_ident;
10,432✔
339
    auto p = m_sessions.emplace(ident, std::move(sess)); // Throws
10,432✔
340
    bool was_inserted = p.second;
10,432✔
341
    REALM_ASSERT(was_inserted);
10,432✔
342
    // Save the session ident to the historical list of session idents
343
    m_session_history.insert(ident);
10,432✔
344
    sess_2.activate(); // Throws
10,432✔
345
    if (m_state == ConnectionState::connected) {
10,432✔
346
        bool fast_reconnect = false;
7,286✔
347
        sess_2.connection_established(fast_reconnect); // Throws
7,286✔
348
    }
7,286✔
349
    ++m_num_active_sessions;
10,432✔
350
}
10,432✔
351

352

353
void Connection::initiate_session_deactivation(Session* sess)
354
{
10,430✔
355
    REALM_ASSERT(sess);
10,430✔
356
    REALM_ASSERT(&sess->m_conn == this);
10,430✔
357
    REALM_ASSERT(m_num_active_sessions);
10,430✔
358
    // Since the client may be waiting for m_num_active_sessions to reach 0
359
    // in stop_and_wait() (on a separate thread), deactivate Session before
360
    // decrementing the num active sessions value.
361
    sess->initiate_deactivation(); // Throws
10,430✔
362
    if (sess->m_state == Session::Deactivated) {
10,430✔
363
        finish_session_deactivation(sess);
950✔
364
    }
950✔
365
    if (REALM_UNLIKELY(--m_num_active_sessions == 0)) {
10,430✔
366
        if (m_activated && m_state == ConnectionState::disconnected)
4,658✔
367
            m_on_idle->trigger();
368✔
368
    }
4,658✔
369
}
10,430✔
370

371

372
void Connection::cancel_reconnect_delay()
373
{
2,182✔
374
    REALM_ASSERT(m_activated);
2,182✔
375

376
    if (m_reconnect_delay_in_progress) {
2,182✔
377
        if (m_nonzero_reconnect_delay)
1,946✔
378
            logger.detail("Canceling reconnect delay"); // Throws
976✔
379

380
        // Cancel the in-progress wait operation by destroying the timer
381
        // object. Destruction is needed in this case, because a new wait
382
        // operation might have to be initiated before the previous one
383
        // completes (its completion handler starts to execute), so the new wait
384
        // operation must be done on a new timer object.
385
        m_reconnect_disconnect_timer.reset();
1,946✔
386
        m_reconnect_delay_in_progress = false;
1,946✔
387
        m_reconnect_info.reset();
1,946✔
388
        initiate_reconnect_wait(); // Throws
1,946✔
389
        return;
1,946✔
390
    }
1,946✔
391

392
    // If we are not disconnected, then we need to make sure the next time we get disconnected
393
    // that we are allowed to re-connect as quickly as possible.
394
    //
395
    // Setting m_reconnect_info.scheduled_reset will cause initiate_reconnect_wait to reset the
396
    // backoff/delay state before calculating the next delay, unless a PONG message is received
397
    // for the urgent PING message we send below.
398
    //
399
    // If we get a PONG message for the urgent PING message sent below, then the connection is
400
    // healthy and we can calculate the next delay normally.
401
    if (m_state != ConnectionState::disconnected) {
236✔
402
        m_reconnect_info.scheduled_reset = true;
236✔
403
        m_ping_after_scheduled_reset_of_reconnect_info = false;
236✔
404

405
        schedule_urgent_ping(); // Throws
236✔
406
        return;
236✔
407
    }
236✔
408
    // Nothing to do in this case. The next reconnect attemp will be made as
409
    // soon as there are any sessions that are both active and unsuspended.
410
}
236✔
411

412
void Connection::finish_session_deactivation(Session* sess)
413
{
8,260✔
414
    REALM_ASSERT(sess->m_state == Session::Deactivated);
8,260✔
415
    auto ident = sess->m_ident;
8,260✔
416
    m_sessions.erase(ident);
8,260✔
417
    m_session_history.erase(ident);
8,260✔
418
}
8,260✔
419

420
void Connection::force_close()
421
{
2,518✔
422
    if (m_force_closed) {
2,518✔
423
        return;
×
424
    }
×
425

426
    m_force_closed = true;
2,518✔
427

428
    if (m_state != ConnectionState::disconnected) {
2,518✔
429
        voluntary_disconnect();
2,488✔
430
    }
2,488✔
431

432
    REALM_ASSERT_EX(m_state == ConnectionState::disconnected, m_state);
2,518✔
433
    if (m_reconnect_delay_in_progress || m_disconnect_delay_in_progress) {
2,518✔
434
        m_reconnect_disconnect_timer.reset();
32✔
435
        m_reconnect_delay_in_progress = false;
32✔
436
        m_disconnect_delay_in_progress = false;
32✔
437
    }
32✔
438

439
    // We must copy any session pointers we want to close to a vector because force_closing
440
    // the session may remove it from m_sessions and invalidate the iterator uses to loop
441
    // through the map. By copying to a separate vector we ensure our iterators remain valid.
442
    std::vector<Session*> to_close;
2,518✔
443
    for (auto& session_pair : m_sessions) {
2,518✔
444
        if (session_pair.second->m_state == Session::State::Active) {
102✔
445
            to_close.push_back(session_pair.second.get());
102✔
446
        }
102✔
447
    }
102✔
448

449
    for (auto& sess : to_close) {
2,518✔
450
        sess->force_close();
102✔
451
    }
102✔
452

453
    logger.debug("Force closed idle connection");
2,518✔
454
}
2,518✔
455

456

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

499

500
bool Connection::websocket_binary_message_received(util::Span<const char> data)
501
{
81,580✔
502
    if (m_force_closed) {
81,580✔
503
        logger.debug("Received binary message after connection was force closed");
×
504
        return false;
×
505
    }
×
506

507
    using sf = SimulatedFailure;
81,580✔
508
    if (sf::check_trigger(sf::sync_client__read_head)) {
81,580✔
509
        close_due_to_client_side_error(
452✔
510
            {ErrorCodes::RuntimeError, "Simulated failure during sync client websocket read"}, IsFatal{false},
452✔
511
            ConnectionTerminationReason::read_or_write_error);
452✔
512
        return bool(m_websocket);
452✔
513
    }
452✔
514

515
    handle_message_received(data);
81,128✔
516
    return bool(m_websocket);
81,128✔
517
}
81,580✔
518

519

520
void Connection::websocket_error_handler()
521
{
726✔
522
    m_websocket_error_received = true;
726✔
523
}
726✔
524

525
bool Connection::websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg)
526
{
842✔
527
    if (m_force_closed) {
842✔
528
        logger.debug("Received websocket close message after connection was force closed");
×
529
        return false;
×
530
    }
×
531
    logger.info("Closing the websocket with error code=%1, message='%2', was_clean=%3", error_code, msg, was_clean);
842✔
532

533
    switch (error_code) {
842✔
534
        case WebSocketError::websocket_ok:
70✔
535
            break;
70✔
536
        case WebSocketError::websocket_resolve_failed:
4✔
537
            [[fallthrough]];
4✔
538
        case WebSocketError::websocket_connection_failed: {
112✔
539
            SessionErrorInfo error_info(
112✔
540
                {ErrorCodes::SyncConnectFailed, util::format("Failed to connect to sync: %1", msg)}, IsFatal{false});
112✔
541
            // If the connection fails/times out and the server has not been contacted yet, refresh the location
542
            // to make sure the websocket URL is correct
543
            if (!m_server_endpoint.is_verified) {
112✔
544
                error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshLocation;
84✔
545
            }
84✔
546
            involuntary_disconnect(std::move(error_info), ConnectionTerminationReason::connect_operation_failed);
112✔
547
            break;
112✔
548
        }
4✔
549
        case WebSocketError::websocket_read_error:
592✔
550
            [[fallthrough]];
592✔
551
        case WebSocketError::websocket_write_error: {
592✔
552
            close_due_to_transient_error({ErrorCodes::ConnectionClosed, msg},
592✔
553
                                         ConnectionTerminationReason::read_or_write_error);
592✔
554
            break;
592✔
555
        }
592✔
556
        case WebSocketError::websocket_going_away:
✔
557
            [[fallthrough]];
×
558
        case WebSocketError::websocket_protocol_error:
✔
559
            [[fallthrough]];
×
560
        case WebSocketError::websocket_unsupported_data:
✔
561
            [[fallthrough]];
×
562
        case WebSocketError::websocket_invalid_payload_data:
✔
563
            [[fallthrough]];
×
564
        case WebSocketError::websocket_policy_violation:
✔
565
            [[fallthrough]];
×
566
        case WebSocketError::websocket_reserved:
✔
567
            [[fallthrough]];
×
568
        case WebSocketError::websocket_no_status_received:
✔
569
            [[fallthrough]];
×
570
        case WebSocketError::websocket_invalid_extension: {
✔
571
            close_due_to_client_side_error({ErrorCodes::SyncProtocolInvariantFailed, msg}, IsFatal{false},
×
572
                                           ConnectionTerminationReason::websocket_protocol_violation); // Throws
×
573
            break;
×
574
        }
×
575
        case WebSocketError::websocket_message_too_big: {
4✔
576
            auto message = util::format(
4✔
577
                "Sync websocket closed because the server received a message that was too large: %1", msg);
4✔
578
            SessionErrorInfo error_info(Status(ErrorCodes::LimitExceeded, std::move(message)), IsFatal{false});
4✔
579
            error_info.server_requests_action = ProtocolErrorInfo::Action::ClientReset;
4✔
580
            involuntary_disconnect(std::move(error_info),
4✔
581
                                   ConnectionTerminationReason::websocket_protocol_violation); // Throws
4✔
582
            break;
4✔
583
        }
×
584
        case WebSocketError::websocket_tls_handshake_failed: {
10✔
585
            close_due_to_client_side_error(
10✔
586
                Status(ErrorCodes::TlsHandshakeFailed, util::format("TLS handshake failed: %1", msg)), IsFatal{false},
10✔
587
                ConnectionTerminationReason::ssl_certificate_rejected); // Throws
10✔
588
            break;
10✔
589
        }
×
590
        case WebSocketError::websocket_fatal_error: {
✔
591
            // Error is fatal if the sync_route has already been verified - if the sync_route has not
592
            // been verified, then use a non-fatal error and try to perform a location update.
593
            SessionErrorInfo error_info(
×
594
                {ErrorCodes::SyncConnectFailed, util::format("Failed to connect to sync: %1", msg)},
×
595
                IsFatal{m_server_endpoint.is_verified});
×
596
            ConnectionTerminationReason reason = ConnectionTerminationReason::http_response_says_fatal_error;
×
597
            // If the connection fails/times out and the server has not been contacted yet, refresh the location
598
            // to make sure the websocket URL is correct
599
            if (!m_server_endpoint.is_verified) {
×
600
                error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshLocation;
×
601
                reason = ConnectionTerminationReason::connect_operation_failed;
×
602
            }
×
603
            involuntary_disconnect(std::move(error_info), reason);
×
604
            break;
×
605
        }
×
606
        case WebSocketError::websocket_forbidden: {
✔
607
            SessionErrorInfo error_info({ErrorCodes::AuthError, msg}, IsFatal{true});
×
608
            error_info.server_requests_action = ProtocolErrorInfo::Action::LogOutUser;
×
609
            involuntary_disconnect(std::move(error_info),
×
610
                                   ConnectionTerminationReason::http_response_says_fatal_error);
×
611
            break;
×
612
        }
×
613
        case WebSocketError::websocket_unauthorized: {
44✔
614
            SessionErrorInfo error_info(
44✔
615
                {ErrorCodes::AuthError,
44✔
616
                 util::format("Websocket was closed because of an authentication issue: %1", msg)},
44✔
617
                IsFatal{false});
44✔
618
            error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshUser;
44✔
619
            involuntary_disconnect(std::move(error_info),
44✔
620
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
44✔
621
            break;
44✔
622
        }
×
623
        case WebSocketError::websocket_moved_permanently: {
10✔
624
            SessionErrorInfo error_info({ErrorCodes::ConnectionClosed, msg}, IsFatal{false});
10✔
625
            error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshLocation;
10✔
626
            involuntary_disconnect(std::move(error_info),
10✔
627
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
10✔
628
            break;
10✔
629
        }
×
630
        case WebSocketError::websocket_abnormal_closure: {
✔
631
            SessionErrorInfo error_info({ErrorCodes::ConnectionClosed, msg}, IsFatal{false});
×
632
            error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshUser;
×
633
            involuntary_disconnect(std::move(error_info),
×
634
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
×
635
            break;
×
636
        }
×
637
        case WebSocketError::websocket_internal_server_error:
✔
638
            [[fallthrough]];
×
639
        case WebSocketError::websocket_retry_error: {
✔
640
            involuntary_disconnect(SessionErrorInfo({ErrorCodes::ConnectionClosed, msg}, IsFatal{false}),
×
641
                                   ConnectionTerminationReason::http_response_says_nonfatal_error);
×
642
            break;
×
643
        }
×
644
    }
842✔
645

646
    return bool(m_websocket);
842✔
647
}
842✔
648

649
// Guarantees that handle_reconnect_wait() is never called from within the
650
// execution of initiate_reconnect_wait() (no callback reentrance).
651
void Connection::initiate_reconnect_wait()
652
{
8,644✔
653
    REALM_ASSERT(m_activated);
8,644✔
654
    REALM_ASSERT(!m_reconnect_delay_in_progress);
8,644✔
655
    REALM_ASSERT(!m_disconnect_delay_in_progress);
8,644✔
656

657
    // If we've been force closed then we don't need/want to reconnect. Just return early here.
658
    if (m_force_closed) {
8,644✔
659
        return;
2,486✔
660
    }
2,486✔
661

662
    m_reconnect_delay_in_progress = true;
6,158✔
663
    auto delay = m_reconnect_info.delay_interval();
6,158✔
664
    if (delay == std::chrono::milliseconds::max()) {
6,158✔
665
        logger.detail("Reconnection delayed indefinitely"); // Throws
1,018✔
666
        // Not actually starting a timer corresponds to an infinite wait
667
        m_nonzero_reconnect_delay = true;
1,018✔
668
        return;
1,018✔
669
    }
1,018✔
670

671
    if (delay == std::chrono::milliseconds::zero()) {
5,140✔
672
        m_nonzero_reconnect_delay = false;
4,782✔
673
    }
4,782✔
674
    else {
358✔
675
        logger.detail("Allowing reconnection in %1 milliseconds", delay.count()); // Throws
358✔
676
        m_nonzero_reconnect_delay = true;
358✔
677
    }
358✔
678

679
    // We create a timer for the reconnect_disconnect timer even if the delay is zero because
680
    // we need it to be cancelable in case the connection is terminated before the timer
681
    // callback is run.
682
    m_reconnect_disconnect_timer = m_client.create_timer(delay, [this](Status status) {
5,142✔
683
        // If the operation is aborted, the connection object may have been
684
        // destroyed.
685
        if (status != ErrorCodes::OperationAborted)
5,142✔
686
            handle_reconnect_wait(status); // Throws
3,858✔
687
    });                                    // Throws
5,142✔
688
}
5,140✔
689

690

691
void Connection::handle_reconnect_wait(Status status)
692
{
3,858✔
693
    if (!status.is_ok()) {
3,858✔
694
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
695
        throw Exception(status);
×
696
    }
×
697

698
    REALM_ASSERT(m_reconnect_delay_in_progress);
3,858✔
699
    m_reconnect_delay_in_progress = false;
3,858✔
700

701
    if (m_num_active_unsuspended_sessions > 0)
3,858✔
702
        initiate_reconnect(); // Throws
3,850✔
703
}
3,858✔
704

705
struct Connection::WebSocketObserverShim : public sync::WebSocketObserver {
706
    explicit WebSocketObserverShim(Connection* conn)
707
        : conn(conn)
1,802✔
708
        , sentinel(conn->m_websocket_sentinel)
1,802✔
709
    {
3,858✔
710
    }
3,858✔
711

712
    Connection* conn;
713
    util::bind_ptr<LifecycleSentinel> sentinel;
714

715
    void websocket_connected_handler(const std::string& protocol) override
716
    {
3,660✔
717
        if (sentinel->destroyed) {
3,660✔
718
            return;
×
719
        }
×
720

721
        return conn->websocket_connected_handler(protocol);
3,660✔
722
    }
3,660✔
723

724
    void websocket_error_handler() override
725
    {
726✔
726
        if (sentinel->destroyed) {
726✔
727
            return;
×
728
        }
×
729

730
        conn->websocket_error_handler();
726✔
731
    }
726✔
732

733
    bool websocket_binary_message_received(util::Span<const char> data) override
734
    {
81,580✔
735
        if (sentinel->destroyed) {
81,580✔
736
            return false;
×
737
        }
×
738

739
        return conn->websocket_binary_message_received(data);
81,580✔
740
    }
81,580✔
741

742
    bool websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg) override
743
    {
842✔
744
        if (sentinel->destroyed) {
842✔
745
            return true;
×
746
        }
×
747

748
        return conn->websocket_closed_handler(was_clean, error_code, msg);
842✔
749
    }
842✔
750
};
751

752
void Connection::initiate_reconnect()
753
{
3,858✔
754
    REALM_ASSERT(m_activated);
3,858✔
755

756
    m_state = ConnectionState::connecting;
3,858✔
757
    report_connection_state_change(ConnectionState::connecting); // Throws
3,858✔
758
    if (m_websocket_sentinel) {
3,858✔
759
        m_websocket_sentinel->destroyed = true;
×
760
    }
×
761
    m_websocket_sentinel = util::make_bind<LifecycleSentinel>();
3,858✔
762
    m_websocket.reset();
3,858✔
763

764
    // Watchdog
765
    initiate_connect_wait(); // Throws
3,858✔
766

767
    std::vector<std::string> sec_websocket_protocol;
3,858✔
768
    {
3,858✔
769
        auto protocol_prefix =
3,858✔
770
            is_flx_sync_connection() ? get_flx_websocket_protocol_prefix() : get_pbs_websocket_protocol_prefix();
3,858✔
771
        int min = get_oldest_supported_protocol_version();
3,858✔
772
        int max = get_current_protocol_version();
3,858✔
773
        REALM_ASSERT_3(min, <=, max);
3,858✔
774
        // List protocol version in descending order to ensure that the server
775
        // selects the highest possible version.
776
        for (int version = max; version >= min; --version) {
54,008✔
777
            sec_websocket_protocol.push_back(util::format("%1%2", protocol_prefix, version)); // Throws
50,150✔
778
        }
50,150✔
779
    }
3,858✔
780

781
    logger.info("Connecting to '%1%2:%3%4'", to_string(m_server_endpoint.envelope), m_server_endpoint.address,
3,858✔
782
                m_server_endpoint.port, m_http_request_path_prefix);
3,858✔
783

784
    m_websocket_error_received = false;
3,858✔
785
    m_websocket =
3,858✔
786
        m_client.m_socket_provider->connect(std::make_unique<WebSocketObserverShim>(this),
3,858✔
787
                                            WebSocketEndpoint{
3,858✔
788
                                                m_server_endpoint.address,
3,858✔
789
                                                m_server_endpoint.port,
3,858✔
790
                                                get_http_request_path(),
3,858✔
791
                                                std::move(sec_websocket_protocol),
3,858✔
792
                                                is_ssl(m_server_endpoint.envelope),
3,858✔
793
                                                /// DEPRECATED - The following will be removed in a future release
794
                                                {m_custom_http_headers.begin(), m_custom_http_headers.end()},
3,858✔
795
                                                m_verify_servers_ssl_certificate,
3,858✔
796
                                                m_ssl_trust_certificate_path,
3,858✔
797
                                                m_ssl_verify_callback,
3,858✔
798
                                                m_proxy_config,
3,858✔
799
                                            });
3,858✔
800
}
3,858✔
801

802

803
void Connection::initiate_connect_wait()
804
{
3,858✔
805
    // Deploy a watchdog to enforce an upper bound on the time it can take to
806
    // fully establish the connection (including SSL and WebSocket
807
    // handshakes). Without such a watchdog, connect operations could take very
808
    // long, or even indefinite time.
809
    milliseconds_type time = m_client.m_connect_timeout;
3,858✔
810

811
    m_connect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
3,858✔
812
        // If the operation is aborted, the connection object may have been
813
        // destroyed.
814
        if (status != ErrorCodes::OperationAborted)
3,858✔
815
            handle_connect_wait(status); // Throws
×
816
    });                                  // Throws
3,858✔
817
}
3,858✔
818

819

820
void Connection::handle_connect_wait(Status status)
821
{
×
822
    if (!status.is_ok()) {
×
823
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
824
        throw Exception(status);
×
825
    }
×
826

827
    REALM_ASSERT_EX(m_state == ConnectionState::connecting, m_state);
×
828
    logger.info("Connect timeout"); // Throws
×
829
    SessionErrorInfo error_info({ErrorCodes::SyncConnectTimeout, "Sync connection was not fully established in time"},
×
830
                                IsFatal{false});
×
831
    // If the connection fails/times out and the server has not been contacted yet, refresh the location
832
    // to make sure the websocket URL is correct
833
    if (!m_server_endpoint.is_verified) {
×
834
        error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshLocation;
×
835
    }
×
836
    involuntary_disconnect(std::move(error_info), ConnectionTerminationReason::sync_connect_timeout); // Throws
×
837
}
×
838

839

840
void Connection::handle_connection_established()
841
{
3,660✔
842
    // Cancel connect timeout watchdog
843
    m_connect_timer.reset();
3,660✔
844

845
    m_state = ConnectionState::connected;
3,660✔
846
    m_server_endpoint.is_verified = true; // sync route is valid since connection is successful
3,660✔
847

848
    milliseconds_type now = monotonic_clock_now();
3,660✔
849
    m_pong_wait_started_at = now; // Initially, no time was spent waiting for a PONG message
3,660✔
850
    initiate_ping_delay(now);     // Throws
3,660✔
851

852
    bool fast_reconnect = false;
3,660✔
853
    if (m_disconnect_has_occurred) {
3,660✔
854
        milliseconds_type time = now - m_disconnect_time;
1,064✔
855
        if (time <= m_client.m_fast_reconnect_limit)
1,064✔
856
            fast_reconnect = true;
1,064✔
857
    }
1,064✔
858

859
    for (auto& p : m_sessions) {
4,820✔
860
        Session& sess = *p.second;
4,820✔
861
        sess.connection_established(fast_reconnect); // Throws
4,820✔
862
    }
4,820✔
863

864
    report_connection_state_change(ConnectionState::connected); // Throws
3,660✔
865
}
3,660✔
866

867

868
void Connection::schedule_urgent_ping()
869
{
236✔
870
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
236✔
871
    if (m_ping_delay_in_progress) {
236✔
872
        m_heartbeat_timer.reset();
128✔
873
        m_ping_delay_in_progress = false;
128✔
874
        m_minimize_next_ping_delay = true;
128✔
875
        milliseconds_type now = monotonic_clock_now();
128✔
876
        initiate_ping_delay(now); // Throws
128✔
877
        return;
128✔
878
    }
128✔
879
    REALM_ASSERT_EX(m_state == ConnectionState::connecting || m_waiting_for_pong, m_state);
108✔
880
    if (!m_send_ping)
108✔
881
        m_minimize_next_ping_delay = true;
108✔
882
}
108✔
883

884

885
void Connection::initiate_ping_delay(milliseconds_type now)
886
{
3,942✔
887
    REALM_ASSERT(!m_ping_delay_in_progress);
3,942✔
888
    REALM_ASSERT(!m_waiting_for_pong);
3,942✔
889
    REALM_ASSERT(!m_send_ping);
3,942✔
890

891
    milliseconds_type delay = 0;
3,942✔
892
    if (!m_minimize_next_ping_delay) {
3,942✔
893
        delay = m_client.m_ping_keepalive_period;
3,800✔
894
        // Make a randomized deduction of up to 10%, or up to 100% if this is
895
        // the first PING message to be sent since the connection was
896
        // established. The purpose of this randomized deduction is to reduce
897
        // the risk of many connections sending PING messages simultaneously to
898
        // the server.
899
        milliseconds_type max_deduction = (m_ping_sent ? delay / 10 : delay);
3,800✔
900
        auto distr = std::uniform_int_distribution<milliseconds_type>(0, max_deduction);
3,800✔
901
        milliseconds_type randomized_deduction = distr(m_client.get_random());
3,800✔
902
        delay -= randomized_deduction;
3,800✔
903
        // Deduct the time spent waiting for PONG
904
        REALM_ASSERT_3(now, >=, m_pong_wait_started_at);
3,800✔
905
        milliseconds_type spent_time = now - m_pong_wait_started_at;
3,800✔
906
        if (spent_time < delay) {
3,800✔
907
            delay -= spent_time;
3,792✔
908
        }
3,792✔
909
        else {
8✔
910
            delay = 0;
8✔
911
        }
8✔
912
    }
3,800✔
913
    else {
142✔
914
        m_minimize_next_ping_delay = false;
142✔
915
    }
142✔
916

917

918
    m_ping_delay_in_progress = true;
3,942✔
919

920
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
3,942✔
921
        if (status == ErrorCodes::OperationAborted)
3,942✔
922
            return;
3,768✔
923
        else if (!status.is_ok())
174✔
924
            throw Exception(status);
×
925

926
        handle_ping_delay();                                    // Throws
174✔
927
    });                                                         // Throws
174✔
928
    logger.debug("Will emit a ping in %1 milliseconds", delay); // Throws
3,942✔
929
}
3,942✔
930

931

932
void Connection::handle_ping_delay()
933
{
174✔
934
    REALM_ASSERT(m_ping_delay_in_progress);
174✔
935
    m_ping_delay_in_progress = false;
174✔
936
    m_send_ping = true;
174✔
937

938
    initiate_pong_timeout(); // Throws
174✔
939

940
    if (m_state == ConnectionState::connected && !m_sending)
174✔
941
        send_next_message(); // Throws
120✔
942
}
174✔
943

944

945
void Connection::initiate_pong_timeout()
946
{
174✔
947
    REALM_ASSERT(!m_ping_delay_in_progress);
174✔
948
    REALM_ASSERT(!m_waiting_for_pong);
174✔
949
    REALM_ASSERT(m_send_ping);
174✔
950

951
    m_waiting_for_pong = true;
174✔
952
    m_pong_wait_started_at = monotonic_clock_now();
174✔
953

954
    milliseconds_type time = m_client.m_pong_keepalive_timeout;
174✔
955
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
174✔
956
        if (status == ErrorCodes::OperationAborted)
174✔
957
            return;
162✔
958
        else if (!status.is_ok())
12✔
959
            throw Exception(status);
×
960

961
        handle_pong_timeout(); // Throws
12✔
962
    });                        // Throws
12✔
963
}
174✔
964

965

966
void Connection::handle_pong_timeout()
967
{
12✔
968
    REALM_ASSERT(m_waiting_for_pong);
12✔
969
    logger.debug("Timeout on reception of PONG message"); // Throws
12✔
970
    close_due_to_transient_error({ErrorCodes::ConnectionClosed, "Timed out waiting for PONG response from server"},
12✔
971
                                 ConnectionTerminationReason::pong_timeout);
12✔
972
}
12✔
973

974

975
void Connection::initiate_write_message(const OutputBuffer& out, Session* sess)
976
{
98,860✔
977
    // Stop sending messages if an websocket error was received.
978
    if (m_websocket_error_received)
98,860✔
979
        return;
×
980

981
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
98,860✔
982
        if (sentinel->destroyed) {
98,768✔
983
            return;
1,418✔
984
        }
1,418✔
985
        if (!status.is_ok()) {
97,350✔
986
            if (status != ErrorCodes::Error::OperationAborted) {
×
987
                // Write errors will be handled by the websocket_write_error_handler() callback
988
                logger.error("Connection: write failed %1: %2", status.code_string(), status.reason());
×
989
            }
×
990
            return;
×
991
        }
×
992
        handle_write_message(); // Throws
97,350✔
993
    });                         // Throws
97,350✔
994
    m_sending_session = sess;
98,860✔
995
    m_sending = true;
98,860✔
996
}
98,860✔
997

998

999
void Connection::handle_write_message()
1000
{
97,354✔
1001
    m_sending_session->message_sent(); // Throws
97,354✔
1002
    if (m_sending_session->m_state == Session::Deactivated) {
97,354✔
1003
        finish_session_deactivation(m_sending_session);
126✔
1004
    }
126✔
1005
    m_sending_session = nullptr;
97,354✔
1006
    m_sending = false;
97,354✔
1007
    send_next_message(); // Throws
97,354✔
1008
}
97,354✔
1009

1010

1011
void Connection::send_next_message()
1012
{
174,140✔
1013
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
174,140✔
1014
    REALM_ASSERT(!m_sending_session);
174,140✔
1015
    REALM_ASSERT(!m_sending);
174,140✔
1016
    if (m_send_ping) {
174,140✔
1017
        send_ping(); // Throws
162✔
1018
        return;
162✔
1019
    }
162✔
1020
    while (!m_sessions_enlisted_to_send.empty()) {
251,644✔
1021
        // The state of being connected is not supposed to be able to change
1022
        // across this loop thanks to the "no callback reentrance" guarantee
1023
        // provided by Websocket::async_write_text(), and friends.
1024
        REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
176,902✔
1025

1026
        Session& sess = *m_sessions_enlisted_to_send.front();
176,902✔
1027
        m_sessions_enlisted_to_send.pop_front();
176,902✔
1028
        sess.send_message(); // Throws
176,902✔
1029

1030
        if (sess.m_state == Session::Deactivated) {
176,902✔
1031
            finish_session_deactivation(&sess);
3,030✔
1032
        }
3,030✔
1033

1034
        // An enlisted session may choose to not send a message. In that case,
1035
        // we should pass the opportunity to the next enlisted session.
1036
        if (m_sending)
176,902✔
1037
            break;
99,236✔
1038
    }
176,902✔
1039
}
173,978✔
1040

1041

1042
void Connection::send_ping()
1043
{
162✔
1044
    REALM_ASSERT(!m_ping_delay_in_progress);
162✔
1045
    REALM_ASSERT(m_waiting_for_pong);
162✔
1046
    REALM_ASSERT(m_send_ping);
162✔
1047

1048
    m_send_ping = false;
162✔
1049
    if (m_reconnect_info.scheduled_reset)
162✔
1050
        m_ping_after_scheduled_reset_of_reconnect_info = true;
138✔
1051

1052
    m_last_ping_sent_at = monotonic_clock_now();
162✔
1053
    logger.debug("Sending: PING(timestamp=%1, rtt=%2)", m_last_ping_sent_at,
162✔
1054
                 m_previous_ping_rtt); // Throws
162✔
1055

1056
    ClientProtocol& protocol = get_client_protocol();
162✔
1057
    OutputBuffer& out = get_output_buffer();
162✔
1058
    protocol.make_ping(out, m_last_ping_sent_at, m_previous_ping_rtt); // Throws
162✔
1059
    initiate_write_ping(out);                                          // Throws
162✔
1060
    m_ping_sent = true;
162✔
1061
}
162✔
1062

1063

1064
void Connection::initiate_write_ping(const OutputBuffer& out)
1065
{
162✔
1066
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
162✔
1067
        if (sentinel->destroyed) {
162✔
1068
            return;
2✔
1069
        }
2✔
1070
        if (!status.is_ok()) {
160✔
1071
            if (status != ErrorCodes::Error::OperationAborted) {
×
1072
                // Write errors will be handled by the websocket_write_error_handler() callback
1073
                logger.error("Connection: send ping failed %1: %2", status.code_string(), status.reason());
×
1074
            }
×
1075
            return;
×
1076
        }
×
1077
        handle_write_ping(); // Throws
160✔
1078
    });                      // Throws
160✔
1079
    m_sending = true;
162✔
1080
}
162✔
1081

1082

1083
void Connection::handle_write_ping()
1084
{
160✔
1085
    REALM_ASSERT(m_sending);
160✔
1086
    REALM_ASSERT(!m_sending_session);
160✔
1087
    m_sending = false;
160✔
1088
    send_next_message(); // Throws
160✔
1089
}
160✔
1090

1091

1092
void Connection::handle_message_received(util::Span<const char> data)
1093
{
81,132✔
1094
    // parse_message_received() parses the message and calls the proper handler
1095
    // on the Connection object (this).
1096
    get_client_protocol().parse_message_received<Connection>(*this, std::string_view(data.data(), data.size()));
81,132✔
1097
}
81,132✔
1098

1099

1100
void Connection::initiate_disconnect_wait()
1101
{
4,818✔
1102
    REALM_ASSERT(!m_reconnect_delay_in_progress);
4,818✔
1103

1104
    if (m_disconnect_delay_in_progress) {
4,818✔
1105
        m_reconnect_disconnect_timer.reset();
2,232✔
1106
        m_disconnect_delay_in_progress = false;
2,232✔
1107
    }
2,232✔
1108

1109
    milliseconds_type time = m_client.m_connection_linger_time;
4,818✔
1110

1111
    m_reconnect_disconnect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
4,818✔
1112
        // If the operation is aborted, the connection object may have been
1113
        // destroyed.
1114
        if (status != ErrorCodes::OperationAborted)
4,816✔
1115
            handle_disconnect_wait(status); // Throws
12✔
1116
    });                                     // Throws
4,816✔
1117
    m_disconnect_delay_in_progress = true;
4,818✔
1118
}
4,818✔
1119

1120

1121
void Connection::handle_disconnect_wait(Status status)
1122
{
12✔
1123
    if (!status.is_ok()) {
12✔
1124
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
1125
        throw Exception(status);
×
1126
    }
×
1127

1128
    m_disconnect_delay_in_progress = false;
12✔
1129

1130
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
12✔
1131
    if (m_num_active_unsuspended_sessions == 0) {
12✔
1132
        if (m_client.m_connection_linger_time > 0)
12✔
1133
            logger.detail("Linger time expired"); // Throws
×
1134
        voluntary_disconnect();                   // Throws
12✔
1135
        logger.info("Disconnected");              // Throws
12✔
1136
    }
12✔
1137
}
12✔
1138

1139

1140
void Connection::close_due_to_protocol_error(Status status)
1141
{
16✔
1142
    SessionErrorInfo error_info(std::move(status), IsFatal{true});
16✔
1143
    error_info.server_requests_action = ProtocolErrorInfo::Action::ProtocolViolation;
16✔
1144
    involuntary_disconnect(std::move(error_info),
16✔
1145
                           ConnectionTerminationReason::sync_protocol_violation); // Throws
16✔
1146
}
16✔
1147

1148

1149
void Connection::close_due_to_client_side_error(Status status, IsFatal is_fatal, ConnectionTerminationReason reason)
1150
{
462✔
1151
    logger.info("Connection closed due to error: %1", status); // Throws
462✔
1152

1153
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
462✔
1154
}
462✔
1155

1156

1157
void Connection::close_due_to_transient_error(Status status, ConnectionTerminationReason reason)
1158
{
604✔
1159
    logger.info("Connection closed due to transient error: %1", status); // Throws
604✔
1160
    SessionErrorInfo error_info{std::move(status), IsFatal{false}};
604✔
1161
    error_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
604✔
1162

1163
    involuntary_disconnect(std::move(error_info), reason); // Throw
604✔
1164
}
604✔
1165

1166

1167
// Close connection due to error discovered on the server-side, and then
1168
// reported to the client by way of a connection-level ERROR message.
1169
void Connection::close_due_to_server_side_error(ProtocolError error_code, const ProtocolErrorInfo& info)
1170
{
70✔
1171
    logger.info("Connection closed due to error reported by server: %1 (%2)", info.message,
70✔
1172
                int(error_code)); // Throws
70✔
1173

1174
    const auto reason = info.is_fatal ? ConnectionTerminationReason::server_said_do_not_reconnect
70✔
1175
                                      : ConnectionTerminationReason::server_said_try_again_later;
70✔
1176
    involuntary_disconnect(SessionErrorInfo{info, protocol_error_to_status(error_code, info.message)},
70✔
1177
                           reason); // Throws
70✔
1178
}
70✔
1179

1180

1181
void Connection::disconnect(const SessionErrorInfo& info)
1182
{
3,858✔
1183
    // Cancel connect timeout watchdog
1184
    m_connect_timer.reset();
3,858✔
1185

1186
    if (m_state == ConnectionState::connected) {
3,858✔
1187
        m_disconnect_time = monotonic_clock_now();
3,658✔
1188
        m_disconnect_has_occurred = true;
3,658✔
1189

1190
        // Sessions that are in the Deactivating state at this time can be
1191
        // immediately discarded, in part because they are no longer enlisted to
1192
        // send. Such sessions will be taken to the Deactivated state by
1193
        // Session::connection_lost(), and then they will be removed from
1194
        // `m_sessions`.
1195
        auto i = m_sessions.begin(), end = m_sessions.end();
3,658✔
1196
        while (i != end) {
8,038✔
1197
            // Prevent invalidation of the main iterator when erasing elements
1198
            auto j = i++;
4,380✔
1199
            Session& sess = *j->second;
4,380✔
1200
            sess.connection_lost(); // Throws
4,380✔
1201
            if (sess.m_state == Session::Unactivated || sess.m_state == Session::Deactivated)
4,382✔
1202
                m_sessions.erase(j);
2,172✔
1203
        }
4,380✔
1204
    }
3,658✔
1205

1206
    change_state_to_disconnected();
3,858✔
1207

1208
    m_ping_delay_in_progress = false;
3,858✔
1209
    m_waiting_for_pong = false;
3,858✔
1210
    m_send_ping = false;
3,858✔
1211
    m_minimize_next_ping_delay = false;
3,858✔
1212
    m_ping_after_scheduled_reset_of_reconnect_info = false;
3,858✔
1213
    m_ping_sent = false;
3,858✔
1214
    m_heartbeat_timer.reset();
3,858✔
1215
    m_previous_ping_rtt = 0;
3,858✔
1216

1217
    m_websocket_sentinel->destroyed = true;
3,858✔
1218
    m_websocket_sentinel.reset();
3,858✔
1219
    m_websocket.reset();
3,858✔
1220
    m_input_body_buffer.reset();
3,858✔
1221
    m_sending_session = nullptr;
3,858✔
1222
    m_sessions_enlisted_to_send.clear();
3,858✔
1223
    m_sending = false;
3,858✔
1224

1225
    if (!m_appservices_coid.empty()) {
3,858✔
1226
        m_appservices_coid.clear();
3,630✔
1227
        logger.base_logger = make_logger(m_ident, std::nullopt, get_client().logger.base_logger);
3,630✔
1228
        for (auto& [ident, sess] : m_sessions) {
3,630✔
1229
            sess->logger.base_logger = Session::make_logger(ident, logger.base_logger);
2,172✔
1230
        }
2,172✔
1231
    }
3,630✔
1232

1233
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
3,858✔
1234
    initiate_reconnect_wait();                                           // Throws
3,858✔
1235
}
3,858✔
1236

1237
bool Connection::is_flx_sync_connection() const noexcept
1238
{
115,616✔
1239
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
115,616✔
1240
}
115,616✔
1241

1242
void Connection::receive_pong(milliseconds_type timestamp)
1243
{
154✔
1244
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
154✔
1245

1246
    bool legal_at_this_time = (m_waiting_for_pong && !m_send_ping);
154✔
1247
    if (REALM_UNLIKELY(!legal_at_this_time)) {
154✔
1248
        close_due_to_protocol_error(
×
1249
            {ErrorCodes::SyncProtocolInvariantFailed, "Received PONG message when it was not valid"}); // Throws
×
1250
        return;
×
1251
    }
×
1252

1253
    if (REALM_UNLIKELY(timestamp != m_last_ping_sent_at)) {
154✔
1254
        close_due_to_protocol_error(
×
1255
            {ErrorCodes::SyncProtocolInvariantFailed,
×
1256
             util::format("Received PONG message with an invalid timestamp (expected %1, received %2)",
×
1257
                          m_last_ping_sent_at, timestamp)}); // Throws
×
1258
        return;
×
1259
    }
×
1260

1261
    milliseconds_type now = monotonic_clock_now();
154✔
1262
    milliseconds_type round_trip_time = now - timestamp;
154✔
1263
    logger.debug("Round trip time was %1 milliseconds", round_trip_time);
154✔
1264
    m_previous_ping_rtt = round_trip_time;
154✔
1265

1266
    // If this PONG message is a response to a PING mesage that was sent after
1267
    // the last invocation of cancel_reconnect_delay(), then the connection is
1268
    // still good, and we do not have to skip the next reconnect delay.
1269
    if (m_ping_after_scheduled_reset_of_reconnect_info) {
154✔
1270
        REALM_ASSERT(m_reconnect_info.scheduled_reset);
124✔
1271
        m_ping_after_scheduled_reset_of_reconnect_info = false;
124✔
1272
        m_reconnect_info.scheduled_reset = false;
124✔
1273
    }
124✔
1274

1275
    m_heartbeat_timer.reset();
154✔
1276
    m_waiting_for_pong = false;
154✔
1277

1278
    initiate_ping_delay(now); // Throws
154✔
1279

1280
    if (m_client.m_roundtrip_time_handler)
154✔
1281
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
×
1282
}
154✔
1283

1284
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
1285
{
74,882✔
1286
    if (session_ident == 0) {
74,882✔
1287
        return nullptr;
×
1288
    }
×
1289

1290
    auto* sess = get_session(session_ident);
74,882✔
1291
    if (REALM_LIKELY(sess)) {
74,882✔
1292
        return sess;
74,880✔
1293
    }
74,880✔
1294
    // Check the history to see if the message received was for a previous session
1295
    if (auto it = m_session_history.find(session_ident); it == m_session_history.end()) {
2✔
UNCOV
1296
        logger.error("Bad session identifier in %1 message, session_ident = %2", message, session_ident);
×
UNCOV
1297
        close_due_to_protocol_error(
×
UNCOV
1298
            {ErrorCodes::SyncProtocolInvariantFailed,
×
NEW
1299
             util::format("Received message %1 for session ident %2 when that session never existed", message,
×
UNCOV
1300
                          session_ident)});
×
UNCOV
1301
    }
×
1302
    else {
2✔
1303
        logger.error("Received %1 message for closed session, session_ident = %2", message,
2✔
1304
                     session_ident); // Throws
2✔
1305
    }
2✔
1306
    return nullptr;
2✔
1307
}
74,882✔
1308

1309
void Connection::receive_error_message(const ProtocolErrorInfo& info, session_ident_type session_ident)
1310
{
972✔
1311
    Session* sess = nullptr;
972✔
1312
    if (session_ident != 0) {
972✔
1313
        sess = find_and_validate_session(session_ident, "ERROR");
898✔
1314
        if (REALM_UNLIKELY(!sess)) {
898✔
1315
            return;
×
1316
        }
×
1317
        if (auto status = sess->receive_error_message(info); !status.is_ok()) {
898✔
1318
            close_due_to_protocol_error(std::move(status)); // Throws
×
1319
            return;
×
1320
        }
×
1321

1322
        if (sess->m_state == Session::Deactivated) {
898✔
1323
            finish_session_deactivation(sess);
14✔
1324
        }
14✔
1325
        return;
898✔
1326
    }
898✔
1327

1328
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
74✔
1329
                info.message, info.raw_error_code, info.is_fatal, session_ident,
74✔
1330
                info.server_requests_action); // Throws
74✔
1331

1332
    bool known_error_code = bool(get_protocol_error_message(info.raw_error_code));
74✔
1333
    if (REALM_LIKELY(known_error_code)) {
74✔
1334
        ProtocolError error_code = ProtocolError(info.raw_error_code);
70✔
1335
        if (REALM_LIKELY(!is_session_level_error(error_code))) {
70✔
1336
            close_due_to_server_side_error(error_code, info); // Throws
70✔
1337
            return;
70✔
1338
        }
70✔
1339
        close_due_to_protocol_error(
×
1340
            {ErrorCodes::SyncProtocolInvariantFailed,
×
1341
             util::format("Received ERROR message with a non-connection-level error code %1 without a session ident",
×
1342
                          info.raw_error_code)});
×
1343
    }
×
1344
    else {
4✔
1345
        close_due_to_protocol_error(
4✔
1346
            {ErrorCodes::SyncProtocolInvariantFailed,
4✔
1347
             util::format("Received ERROR message with unknown error code %1", info.raw_error_code)});
4✔
1348
    }
4✔
1349
}
74✔
1350

1351

1352
void Connection::receive_query_error_message(int raw_error_code, std::string_view message, int64_t query_version,
1353
                                             session_ident_type session_ident)
1354
{
20✔
1355
    if (session_ident == 0) {
20✔
1356
        return close_due_to_protocol_error(
×
1357
            {ErrorCodes::SyncProtocolInvariantFailed, "Received query error message for session ident 0"});
×
1358
    }
×
1359

1360
    if (!is_flx_sync_connection()) {
20✔
1361
        return close_due_to_protocol_error({ErrorCodes::SyncProtocolInvariantFailed,
×
1362
                                            "Received a FLX query error message on a non-FLX sync connection"});
×
1363
    }
×
1364

1365
    if (Session* sess = find_and_validate_session(session_ident, "QUERY_ERROR")) {
20✔
1366
        sess->receive_query_error_message(raw_error_code, message, query_version);
20✔
1367
    }
20✔
1368
}
20✔
1369

1370

1371
void Connection::receive_ident_message(session_ident_type session_ident, SaltedFileIdent client_file_ident)
1372
{
3,628✔
1373
    Session* sess = find_and_validate_session(session_ident, "IDENT");
3,628✔
1374
    if (REALM_UNLIKELY(!sess)) {
3,628✔
1375
        return;
×
1376
    }
×
1377

1378
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
3,628✔
1379
        close_due_to_protocol_error(std::move(status)); // Throws
×
1380
}
3,628✔
1381

1382
void Connection::receive_download_message(session_ident_type session_ident, const DownloadMessage& message)
1383
{
49,078✔
1384
    Session* sess = find_and_validate_session(session_ident, "DOWNLOAD");
49,078✔
1385
    if (REALM_UNLIKELY(!sess)) {
49,078✔
1386
        return;
×
1387
    }
×
1388

1389
    if (auto status = sess->receive_download_message(message); !status.is_ok()) {
49,078✔
1390
        close_due_to_protocol_error(std::move(status));
×
1391
    }
×
1392
}
49,078✔
1393

1394
void Connection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
1395
{
17,054✔
1396
    Session* sess = find_and_validate_session(session_ident, "MARK");
17,054✔
1397
    if (REALM_UNLIKELY(!sess)) {
17,054✔
1398
        return;
×
1399
    }
×
1400

1401
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
17,054✔
1402
        close_due_to_protocol_error(std::move(status)); // Throws
12✔
1403
}
17,054✔
1404

1405

1406
void Connection::receive_unbound_message(session_ident_type session_ident)
1407
{
4,140✔
1408
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
4,140✔
1409
    if (REALM_UNLIKELY(!sess)) {
4,140✔
UNCOV
1410
        return;
×
UNCOV
1411
    }
×
1412

1413
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
4,140✔
1414
        close_due_to_protocol_error(std::move(status)); // Throws
×
1415
        return;
×
1416
    }
×
1417

1418
    if (sess->m_state == Session::Deactivated) {
4,140✔
1419
        finish_session_deactivation(sess);
4,140✔
1420
    }
4,140✔
1421
}
4,140✔
1422

1423

1424
void Connection::receive_test_command_response(session_ident_type session_ident, request_ident_type request_ident,
1425
                                               std::string_view body)
1426
{
64✔
1427
    Session* sess = find_and_validate_session(session_ident, "TEST_COMMAND");
64✔
1428
    if (REALM_UNLIKELY(!sess)) {
64✔
1429
        return;
×
1430
    }
×
1431

1432
    if (auto status = sess->receive_test_command_response(request_ident, body); !status.is_ok()) {
64✔
1433
        close_due_to_protocol_error(std::move(status));
×
1434
    }
×
1435
}
64✔
1436

1437

1438
void Connection::receive_server_log_message(session_ident_type session_ident, util::Logger::Level level,
1439
                                            std::string_view message)
1440
{
6,026✔
1441
    if (session_ident != 0) {
6,026✔
1442
        if (auto sess = get_session(session_ident)) {
3,996✔
1443
            sess->logger.log(LogCategory::session, level, "Server log: %1", message);
3,982✔
1444
            return;
3,982✔
1445
        }
3,982✔
1446

1447
        logger.log(util::LogCategory::session, level, "Server log for unknown session %1: %2", session_ident,
14✔
1448
                   message);
14✔
1449
        return;
14✔
1450
    }
3,996✔
1451

1452
    logger.log(level, "Server log: %1", message);
2,030✔
1453
}
2,030✔
1454

1455

1456
void Connection::receive_appservices_request_id(std::string_view coid)
1457
{
5,690✔
1458
    if (coid.empty() || !m_appservices_coid.empty()) {
5,690✔
1459
        return;
2,060✔
1460
    }
2,060✔
1461
    m_appservices_coid = coid;
3,630✔
1462
    logger.log(util::LogCategory::session, util::LogCategory::Level::info,
3,630✔
1463
               "Connected to app services with request id: \"%1\". Further log entries for this connection will be "
3,630✔
1464
               "prefixed with \"Connection[%2:%1]\" instead of \"Connection[%2]\"",
3,630✔
1465
               m_appservices_coid, m_ident);
3,630✔
1466
    logger.base_logger = make_logger(m_ident, m_appservices_coid, get_client().logger.base_logger);
3,630✔
1467

1468
    for (auto& [ident, sess] : m_sessions) {
4,780✔
1469
        sess->logger.base_logger = Session::make_logger(ident, logger.base_logger);
4,780✔
1470
    }
4,780✔
1471
}
3,630✔
1472

1473

1474
void Connection::handle_protocol_error(Status status)
1475
{
×
1476
    close_due_to_protocol_error(std::move(status));
×
1477
}
×
1478

1479

1480
// Sessions are guaranteed to be granted the opportunity to send a message in
1481
// the order that they enlist. Note that this is important to ensure
1482
// nonoverlapping communication with the server for consecutive sessions
1483
// associated with the same Realm file.
1484
//
1485
// CAUTION: The specified session may get destroyed before this function
1486
// returns, but only if its Session::send_message() puts it into the Deactivated
1487
// state.
1488
void Connection::enlist_to_send(Session* sess)
1489
{
178,526✔
1490
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
178,526✔
1491
    m_sessions_enlisted_to_send.push_back(sess); // Throws
178,526✔
1492
    if (!m_sending)
178,526✔
1493
        send_next_message(); // Throws
76,508✔
1494
}
178,526✔
1495

1496

1497
std::string Connection::get_active_appservices_connection_id()
1498
{
76✔
1499
    return m_appservices_coid;
76✔
1500
}
76✔
1501

1502
void Session::cancel_resumption_delay()
1503
{
4,264✔
1504
    REALM_ASSERT_EX(m_state == Active, m_state);
4,264✔
1505

1506
    if (!m_suspended)
4,264✔
1507
        return;
4,090✔
1508

1509
    m_suspended = false;
174✔
1510

1511
    logger.debug("Resumed"); // Throws
174✔
1512

1513
    if (unbind_process_complete())
174✔
1514
        initiate_rebind(); // Throws
130✔
1515

1516
    try_process_pending_flx_bootstrap();
174✔
1517

1518
    m_conn.one_more_active_unsuspended_session(); // Throws
174✔
1519
    if (m_try_again_activation_timer) {
174✔
1520
        m_try_again_activation_timer.reset();
8✔
1521
    }
8✔
1522

1523
    on_resumed(); // Throws
174✔
1524
}
174✔
1525

1526

1527
void Session::gather_pending_compensating_writes(util::Span<Changeset> changesets,
1528
                                                 std::vector<ProtocolErrorInfo>* out)
1529
{
22,834✔
1530
    if (m_pending_compensating_write_errors.empty() || changesets.empty()) {
22,834✔
1531
        return;
22,780✔
1532
    }
22,780✔
1533

1534
#ifdef REALM_DEBUG
54✔
1535
    REALM_ASSERT_DEBUG(
54✔
1536
        std::is_sorted(m_pending_compensating_write_errors.begin(), m_pending_compensating_write_errors.end(),
54✔
1537
                       [](const ProtocolErrorInfo& lhs, const ProtocolErrorInfo& rhs) {
54✔
1538
                           REALM_ASSERT_DEBUG(lhs.compensating_write_server_version.has_value());
54✔
1539
                           REALM_ASSERT_DEBUG(rhs.compensating_write_server_version.has_value());
54✔
1540
                           return *lhs.compensating_write_server_version < *rhs.compensating_write_server_version;
54✔
1541
                       }));
54✔
1542
#endif
54✔
1543

1544
    while (!m_pending_compensating_write_errors.empty() &&
110✔
1545
           *m_pending_compensating_write_errors.front().compensating_write_server_version <=
110✔
1546
               changesets.back().version) {
58✔
1547
        auto& cur_error = m_pending_compensating_write_errors.front();
56✔
1548
        REALM_ASSERT_3(*cur_error.compensating_write_server_version, >=, changesets.front().version);
56✔
1549
        out->push_back(std::move(cur_error));
56✔
1550
        m_pending_compensating_write_errors.pop_front();
56✔
1551
    }
56✔
1552
}
54✔
1553

1554

1555
void Session::integrate_changesets(const SyncProgress& progress, std::uint_fast64_t downloadable_bytes,
1556
                                   const ReceivedChangesets& received_changesets, VersionInfo& version_info,
1557
                                   DownloadBatchState download_batch_state)
1558
{
44,534✔
1559
    auto& history = get_history();
44,534✔
1560
    if (received_changesets.empty()) {
44,534✔
1561
        if (download_batch_state == DownloadBatchState::MoreToCome) {
21,688✔
1562
            throw IntegrationException(ErrorCodes::SyncProtocolInvariantFailed,
×
1563
                                       "received empty download message that was not the last in batch",
×
1564
                                       ProtocolError::bad_progress);
×
1565
        }
×
1566
        history.set_sync_progress(progress, downloadable_bytes, version_info); // Throws
21,688✔
1567
        return;
21,688✔
1568
    }
21,688✔
1569

1570
    std::vector<ProtocolErrorInfo> pending_compensating_write_errors;
22,846✔
1571
    auto transact = get_db()->start_read();
22,846✔
1572
    history.integrate_server_changesets(
22,846✔
1573
        progress, downloadable_bytes, received_changesets, version_info, download_batch_state, logger, transact,
22,846✔
1574
        [&](const Transaction&, util::Span<Changeset> changesets) {
22,846✔
1575
            gather_pending_compensating_writes(changesets, &pending_compensating_write_errors);
22,834✔
1576
        }); // Throws
22,834✔
1577
    if (received_changesets.size() == 1) {
22,846✔
1578
        logger.debug("1 remote changeset integrated, producing client version %1",
15,518✔
1579
                     version_info.sync_version.version); // Throws
15,518✔
1580
    }
15,518✔
1581
    else {
7,328✔
1582
        logger.debug("%2 remote changesets integrated, producing client version %1",
7,328✔
1583
                     version_info.sync_version.version, received_changesets.size()); // Throws
7,328✔
1584
    }
7,328✔
1585

1586
    for (const auto& pending_error : pending_compensating_write_errors) {
22,846✔
1587
        logger.info("Reporting compensating write for client version %1 in server version %2: %3",
56✔
1588
                    pending_error.compensating_write_rejected_client_version,
56✔
1589
                    *pending_error.compensating_write_server_version, pending_error.message);
56✔
1590
        try {
56✔
1591
            on_connection_state_changed(
56✔
1592
                m_conn.get_state(),
56✔
1593
                SessionErrorInfo{pending_error,
56✔
1594
                                 protocol_error_to_status(static_cast<ProtocolError>(pending_error.raw_error_code),
56✔
1595
                                                          pending_error.message)});
56✔
1596
        }
56✔
1597
        catch (...) {
56✔
1598
            logger.error("Exception thrown while reporting compensating write: %1", exception_to_status());
×
1599
        }
×
1600
    }
56✔
1601
}
22,846✔
1602

1603

1604
void Session::on_integration_failure(const IntegrationException& error)
1605
{
40✔
1606
    REALM_ASSERT_EX(m_state == Active, m_state);
40✔
1607
    REALM_ASSERT(!m_client_error && !m_error_to_send);
40✔
1608
    logger.error("Failed to integrate downloaded changesets: %1", error.to_status());
40✔
1609

1610
    m_client_error = util::make_optional<IntegrationException>(error);
40✔
1611
    m_error_to_send = true;
40✔
1612
    SessionErrorInfo error_info{error.to_status(), IsFatal{false}};
40✔
1613
    error_info.server_requests_action = ProtocolErrorInfo::Action::Warning;
40✔
1614
    // Surface the error to the user otherwise is lost.
1615
    on_connection_state_changed(m_conn.get_state(), std::move(error_info));
40✔
1616

1617
    // Since the deactivation process has not been initiated, the UNBIND
1618
    // message cannot have been sent unless an ERROR message was received.
1619
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
40✔
1620
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
40✔
1621
        ensure_enlisted_to_send(); // Throws
36✔
1622
    }
36✔
1623
}
40✔
1624

1625
void Session::on_changesets_integrated(version_type client_version, const SyncProgress& progress)
1626
{
46,932✔
1627
    REALM_ASSERT_EX(m_state == Active, m_state);
46,932✔
1628
    REALM_ASSERT_3(progress.download.server_version, >=, m_download_progress.server_version);
46,932✔
1629

1630
    m_download_progress = progress.download;
46,932✔
1631
    m_progress = progress;
46,932✔
1632

1633
    if (progress.upload.client_version > m_upload_progress.client_version)
46,932✔
1634
        m_upload_progress = progress.upload;
602✔
1635

1636
    do_recognize_sync_version(client_version); // Allows upload process to resume
46,932✔
1637

1638
    check_for_download_completion(); // Throws
46,932✔
1639

1640
    // If the client migrated from PBS to FLX, create subscriptions when new tables are received from server.
1641
    if (auto migration_store = get_migration_store(); migration_store && m_is_flx_sync_session) {
46,932✔
1642
        auto& flx_subscription_store = *get_flx_subscription_store();
3,946✔
1643
        get_migration_store()->create_subscriptions(flx_subscription_store);
3,946✔
1644
    }
3,946✔
1645

1646
    // Since the deactivation process has not been initiated, the UNBIND
1647
    // message cannot have been sent unless an ERROR message was received.
1648
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
46,932✔
1649
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
46,932✔
1650
        ensure_enlisted_to_send(); // Throws
46,924✔
1651
    }
46,924✔
1652
}
46,932✔
1653

1654

1655
Session::~Session()
1656
{
10,430✔
1657
    //    REALM_ASSERT_EX(m_state == Unactivated || m_state == Deactivated, m_state);
1658
}
10,430✔
1659

1660

1661
std::shared_ptr<util::Logger> Session::make_logger(session_ident_type ident,
1662
                                                   std::shared_ptr<util::Logger> base_logger)
1663
{
17,384✔
1664
    auto prefix = util::format("Session[%1]: ", ident);
17,384✔
1665
    return std::make_shared<util::PrefixLogger>(util::LogCategory::session, std::move(prefix),
17,384✔
1666
                                                std::move(base_logger));
17,384✔
1667
}
17,384✔
1668

1669
void Session::activate()
1670
{
10,428✔
1671
    REALM_ASSERT_EX(m_state == Unactivated, m_state);
10,428✔
1672

1673
    logger.debug("Activating"); // Throws
10,428✔
1674

1675
    if (REALM_LIKELY(!get_client().is_dry_run())) {
10,432✔
1676
        bool file_exists = util::File::exists(get_realm_path());
10,432✔
1677

1678
        logger.info("client_reset_config = %1, Realm exists = %2, upload messages allowed = %3",
10,432✔
1679
                    get_client_reset_config().has_value(), file_exists, upload_messages_allowed() ? "yes" : "no");
10,432✔
1680
        get_history().get_status(m_last_version_available, m_client_file_ident, m_progress); // Throws
10,432✔
1681
    }
10,432✔
1682
    logger.debug("client_file_ident = %1, client_file_ident_salt = %2", m_client_file_ident.ident,
10,428✔
1683
                 m_client_file_ident.salt); // Throws
10,428✔
1684
    m_upload_progress = m_progress.upload;
10,428✔
1685
    m_download_progress = m_progress.download;
10,428✔
1686
    REALM_ASSERT_3(m_last_version_available, >=, m_progress.upload.client_version);
10,428✔
1687
    init_progress_handler();
10,428✔
1688

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

1696
    reset_protocol_state();
10,428✔
1697
    m_state = Active;
10,428✔
1698

1699
    call_debug_hook(SyncClientHookEvent::SessionActivating);
10,428✔
1700

1701
    REALM_ASSERT(!m_suspended);
10,428✔
1702
    m_conn.one_more_active_unsuspended_session(); // Throws
10,428✔
1703

1704
    try_process_pending_flx_bootstrap();
10,428✔
1705

1706
    // Checks if there is a pending client reset
1707
    handle_pending_client_reset_acknowledgement();
10,428✔
1708
}
10,428✔
1709

1710

1711
// The caller (Connection) must discard the session if the session has become
1712
// deactivated upon return.
1713
void Session::initiate_deactivation()
1714
{
10,432✔
1715
    REALM_ASSERT_EX(m_state == Active, m_state);
10,432✔
1716

1717
    logger.debug("Initiating deactivation"); // Throws
10,432✔
1718

1719
    m_state = Deactivating;
10,432✔
1720

1721
    if (!m_suspended)
10,432✔
1722
        m_conn.one_less_active_unsuspended_session(); // Throws
9,772✔
1723

1724
    if (m_enlisted_to_send) {
10,432✔
1725
        REALM_ASSERT(!unbind_process_complete());
5,428✔
1726
        return;
5,428✔
1727
    }
5,428✔
1728

1729
    // Deactivate immediately if the BIND message has not yet been sent and the
1730
    // session is not enlisted to send, or if the unbinding process has already
1731
    // completed.
1732
    if (!m_bind_message_sent || unbind_process_complete()) {
5,004✔
1733
        complete_deactivation(); // Throws
950✔
1734
        // Life cycle state is now Deactivated
1735
        return;
950✔
1736
    }
950✔
1737

1738
    // Ready to send the UNBIND message, if it has not already been sent
1739
    if (!m_unbind_message_sent) {
4,054✔
1740
        enlist_to_send(); // Throws
3,848✔
1741
        return;
3,848✔
1742
    }
3,848✔
1743
}
4,054✔
1744

1745

1746
void Session::complete_deactivation()
1747
{
10,428✔
1748
    REALM_ASSERT_EX(m_state == Deactivating, m_state);
10,428✔
1749
    m_state = Deactivated;
10,428✔
1750

1751
    logger.debug("Deactivation completed"); // Throws
10,428✔
1752
}
10,428✔
1753

1754

1755
// Called by the associated Connection object when this session is granted an
1756
// opportunity to send a message.
1757
//
1758
// The caller (Connection) must discard the session if the session has become
1759
// deactivated upon return.
1760
void Session::send_message()
1761
{
176,906✔
1762
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
176,906✔
1763
    REALM_ASSERT(m_enlisted_to_send);
176,906✔
1764
    m_enlisted_to_send = false;
176,906✔
1765
    if (m_state == Deactivating || m_error_message_received || m_suspended) {
176,906✔
1766
        // Deactivation has been initiated. If the UNBIND message has not been
1767
        // sent yet, there is no point in sending it. Instead, we can let the
1768
        // deactivation process complete.
1769
        if (!m_bind_message_sent) {
9,700✔
1770
            return complete_deactivation(); // Throws
3,030✔
1771
            // Life cycle state is now Deactivated
1772
        }
3,030✔
1773

1774
        // Session life cycle state is Deactivating or the unbinding process has
1775
        // been initiated by a session specific ERROR message
1776
        if (!m_unbind_message_sent)
6,670✔
1777
            send_unbind_message(); // Throws
6,670✔
1778
        return;
6,670✔
1779
    }
9,700✔
1780

1781
    // Session life cycle state is Active and the unbinding process has
1782
    // not been initiated
1783
    REALM_ASSERT(!m_unbind_message_sent);
167,206✔
1784

1785
    if (!m_bind_message_sent)
167,206✔
1786
        return send_bind_message(); // Throws
9,158✔
1787

1788
    // Pending test commands can be sent any time after the BIND message is sent
1789
    const auto has_pending_test_command = std::any_of(m_pending_test_commands.begin(), m_pending_test_commands.end(),
158,048✔
1790
                                                      [](const PendingTestCommand& command) {
158,048✔
1791
                                                          return command.pending;
154✔
1792
                                                      });
154✔
1793
    if (has_pending_test_command) {
158,048✔
1794
        return send_test_command_message();
64✔
1795
    }
64✔
1796

1797
    if (!m_ident_message_sent) {
157,984✔
1798
        if (have_client_file_ident())
7,828✔
1799
            send_ident_message(); // Throws
7,828✔
1800
        return;
7,828✔
1801
    }
7,828✔
1802

1803
    if (m_error_to_send)
150,156✔
1804
        return send_json_error_message(); // Throws
30✔
1805

1806
    // Stop sending upload, mark and query messages when the client detects an error.
1807
    if (m_client_error) {
150,126✔
1808
        return;
12✔
1809
    }
12✔
1810

1811
    if (m_target_download_mark > m_last_download_mark_sent)
150,114✔
1812
        return send_mark_message(); // Throws
17,920✔
1813

1814
    auto is_upload_allowed = [&]() -> bool {
132,200✔
1815
        if (!m_is_flx_sync_session) {
132,200✔
1816
            return true;
111,052✔
1817
        }
111,052✔
1818

1819
        auto migration_store = get_migration_store();
21,148✔
1820
        if (!migration_store) {
21,148✔
1821
            return true;
×
1822
        }
×
1823

1824
        auto sentinel_query_version = migration_store->get_sentinel_subscription_set_version();
21,148✔
1825
        if (!sentinel_query_version) {
21,148✔
1826
            return true;
21,120✔
1827
        }
21,120✔
1828

1829
        // Do not allow upload if the last query sent is the sentinel one used by the migration store.
1830
        return m_last_sent_flx_query_version != *sentinel_query_version;
28✔
1831
    };
21,148✔
1832

1833
    if (!is_upload_allowed()) {
132,194✔
1834
        return;
16✔
1835
    }
16✔
1836

1837
    auto check_pending_flx_version = [&]() -> bool {
132,184✔
1838
        if (!m_is_flx_sync_session) {
132,182✔
1839
            return false;
111,052✔
1840
        }
111,052✔
1841

1842
        if (m_delay_uploads) {
21,130✔
1843
            return false;
2,976✔
1844
        }
2,976✔
1845

1846
        m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(m_last_sent_flx_query_version);
18,154✔
1847

1848
        if (!m_pending_flx_sub_set) {
18,154✔
1849
            return false;
15,670✔
1850
        }
15,670✔
1851

1852
        // Send QUERY messages when the upload progress client version reaches the snapshot version
1853
        // of a pending subscription
1854
        return m_upload_progress.client_version >= m_pending_flx_sub_set->snapshot_version;
2,484✔
1855
    };
18,154✔
1856

1857
    if (check_pending_flx_version()) {
132,178✔
1858
        return send_query_change_message(); // throws
1,384✔
1859
    }
1,384✔
1860

1861
    if (!m_delay_uploads && (m_last_version_available > m_upload_progress.client_version)) {
130,794✔
1862
        return send_upload_message(); // Throws
61,916✔
1863
    }
61,916✔
1864
}
130,794✔
1865

1866

1867
void Session::send_bind_message()
1868
{
9,158✔
1869
    REALM_ASSERT_EX(m_state == Active, m_state);
9,158✔
1870

1871
    session_ident_type session_ident = m_ident;
9,158✔
1872
    // Request an ident if we don't already have one and there isn't a pending client reset diff
1873
    // The file ident can be 0 when a client reset is being performed if a brand new local realm
1874
    // has been opened (or using Async open) and a FLX/PBS migration occurs when first connecting
1875
    // to the server.
1876
    bool need_client_file_ident = !have_client_file_ident() && !get_client_reset_config();
9,158✔
1877
    const bool is_subserver = false;
9,158✔
1878

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

1914
    m_bind_message_sent = true;
9,158✔
1915
    call_debug_hook(SyncClientHookEvent::BindMessageSent);
9,158✔
1916

1917
    // If there is a pending client reset diff, process that when the BIND message has
1918
    // been sent successfully and wait before sending the IDENT message. Otherwise,
1919
    // ready to send the IDENT message if the file identifier pair is already available.
1920
    if (!need_client_file_ident)
9,158✔
1921
        enlist_to_send(); // Throws
5,320✔
1922
}
9,158✔
1923

1924

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

1932
    ClientProtocol& protocol = m_conn.get_client_protocol();
7,828✔
1933
    OutputBuffer& out = m_conn.get_output_buffer();
7,828✔
1934
    session_ident_type session_ident = m_ident;
7,828✔
1935

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

1961
    m_ident_message_sent = true;
7,828✔
1962
    call_debug_hook(SyncClientHookEvent::IdentMessageSent);
7,828✔
1963

1964
    // Other messages may be waiting to be sent
1965
    enlist_to_send(); // Throws
7,828✔
1966
}
7,828✔
1967

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

1976
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
1,384✔
1977
        return;
×
1978
    }
×
1979

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

1986
    OutputBuffer& out = m_conn.get_output_buffer();
1,384✔
1987
    session_ident_type session_ident = get_ident();
1,384✔
1988
    ClientProtocol& protocol = m_conn.get_client_protocol();
1,384✔
1989
    protocol.make_query_change_message(out, session_ident, latest_sub_set.version(), latest_queries);
1,384✔
1990
    m_conn.initiate_write_message(out, this);
1,384✔
1991

1992
    m_last_sent_flx_query_version = latest_sub_set.version();
1,384✔
1993

1994
    request_download_completion_notification();
1,384✔
1995
}
1,384✔
1996

1997
void Session::send_upload_message()
1998
{
61,914✔
1999
    REALM_ASSERT_EX(m_state == Active, m_state);
61,914✔
2000
    REALM_ASSERT(m_ident_message_sent);
61,914✔
2001
    REALM_ASSERT(!m_unbind_message_sent);
61,914✔
2002

2003
    if (REALM_UNLIKELY(get_client().is_dry_run()))
61,914✔
2004
        return;
×
2005

2006
    version_type target_upload_version = m_last_version_available;
61,914✔
2007
    if (m_pending_flx_sub_set) {
61,914✔
2008
        REALM_ASSERT(m_is_flx_sync_session);
1,102✔
2009
        target_upload_version = m_pending_flx_sub_set->snapshot_version;
1,102✔
2010
    }
1,102✔
2011

2012
    bool server_version_to_ack =
61,914✔
2013
        m_upload_progress.last_integrated_server_version < m_download_progress.server_version;
61,914✔
2014

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

2020
    if (uploadable_changesets.empty()) {
61,914✔
2021
        // Nothing more to upload right now if:
2022
        //  1. We need to limit upload up to some version other than the last client version
2023
        //     available and there are no changes to upload
2024
        //  2. There are no changes to upload and no server version(s) to acknowledge
2025
        if (m_pending_flx_sub_set || !server_version_to_ack) {
32,042✔
2026
            logger.trace("Empty UPLOAD was skipped (progress_client_version=%1, progress_server_version=%2)",
5,502✔
2027
                         m_upload_progress.client_version, m_upload_progress.last_integrated_server_version);
5,502✔
2028
            // Other messages may be waiting to be sent
2029
            return enlist_to_send(); // Throws
5,502✔
2030
        }
5,502✔
2031
    }
32,042✔
2032

2033
    if (m_pending_flx_sub_set && target_upload_version < m_last_version_available) {
56,412✔
2034
        logger.trace("Limiting UPLOAD message up to version %1 to send QUERY version %2",
756✔
2035
                     m_pending_flx_sub_set->snapshot_version, m_pending_flx_sub_set->query_version);
756✔
2036
    }
756✔
2037

2038
    version_type progress_client_version = m_upload_progress.client_version;
56,412✔
2039
    version_type progress_server_version = m_upload_progress.last_integrated_server_version;
56,412✔
2040

2041
    if (!upload_messages_allowed()) {
56,412✔
2042
        logger.trace("UPLOAD not allowed (progress_client_version=%1, progress_server_version=%2, "
606✔
2043
                     "locked_server_version=%3, num_changesets=%4)",
606✔
2044
                     progress_client_version, progress_server_version, locked_server_version,
606✔
2045
                     uploadable_changesets.size()); // Throws
606✔
2046
        // Other messages may be waiting to be sent
2047
        return enlist_to_send(); // Throws
606✔
2048
    }
606✔
2049

2050
    logger.debug("Sending: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
55,806✔
2051
                 "locked_server_version=%3, num_changesets=%4)",
55,806✔
2052
                 progress_client_version, progress_server_version, locked_server_version,
55,806✔
2053
                 uploadable_changesets.size()); // Throws
55,806✔
2054

2055
    ClientProtocol& protocol = m_conn.get_client_protocol();
55,806✔
2056
    ClientProtocol::UploadMessageBuilder upload_message_builder = protocol.make_upload_message_builder(); // Throws
55,806✔
2057

2058
    for (const UploadChangeset& uc : uploadable_changesets) {
55,806✔
2059
        logger.debug(util::LogCategory::changeset,
43,282✔
2060
                     "Fetching changeset for upload (client_version=%1, server_version=%2, "
43,282✔
2061
                     "changeset_size=%3, origin_timestamp=%4, origin_file_ident=%5)",
43,282✔
2062
                     uc.progress.client_version, uc.progress.last_integrated_server_version, uc.changeset.size(),
43,282✔
2063
                     uc.origin_timestamp, uc.origin_file_ident); // Throws
43,282✔
2064
        if (logger.would_log(util::Logger::Level::trace)) {
43,282✔
2065
            BinaryData changeset_data = uc.changeset.get_first_chunk();
×
2066
            if (changeset_data.size() < 1024) {
×
2067
                logger.trace(util::LogCategory::changeset, "Changeset: %1",
×
2068
                             _impl::clamped_hex_dump(changeset_data)); // Throws
×
2069
            }
×
2070
            else {
×
2071
                logger.trace(util::LogCategory::changeset, "Changeset(comp): %1 %2", changeset_data.size(),
×
2072
                             protocol.compressed_hex_dump(changeset_data));
×
2073
            }
×
2074

2075
#if REALM_DEBUG
×
2076
            ChunkedBinaryInputStream in{changeset_data};
×
2077
            Changeset log;
×
2078
            try {
×
2079
                parse_changeset(in, log);
×
2080
                std::stringstream ss;
×
2081
                log.print(ss);
×
2082
                logger.trace(util::LogCategory::changeset, "Changeset (parsed):\n%1", ss.str());
×
2083
            }
×
2084
            catch (const BadChangesetError& err) {
×
2085
                logger.error(util::LogCategory::changeset, "Unable to parse changeset: %1", err.what());
×
2086
            }
×
2087
#endif
×
2088
        }
×
2089

2090
        {
43,282✔
2091
            upload_message_builder.add_changeset(uc.progress.client_version,
43,282✔
2092
                                                 uc.progress.last_integrated_server_version, uc.origin_timestamp,
43,282✔
2093
                                                 uc.origin_file_ident,
43,282✔
2094
                                                 uc.changeset); // Throws
43,282✔
2095
        }
43,282✔
2096
    }
43,282✔
2097

2098
    int protocol_version = m_conn.get_negotiated_protocol_version();
55,806✔
2099
    OutputBuffer& out = m_conn.get_output_buffer();
55,806✔
2100
    session_ident_type session_ident = get_ident();
55,806✔
2101
    upload_message_builder.make_upload_message(protocol_version, out, session_ident, progress_client_version,
55,806✔
2102
                                               progress_server_version,
55,806✔
2103
                                               locked_server_version); // Throws
55,806✔
2104
    m_conn.initiate_write_message(out, this);                          // Throws
55,806✔
2105

2106
    call_debug_hook(SyncClientHookEvent::UploadMessageSent);
55,806✔
2107

2108
    // Other messages may be waiting to be sent
2109
    enlist_to_send(); // Throws
55,806✔
2110
}
55,806✔
2111

2112

2113
void Session::send_mark_message()
2114
{
17,920✔
2115
    REALM_ASSERT_EX(m_state == Active, m_state);
17,920✔
2116
    REALM_ASSERT(m_ident_message_sent);
17,920✔
2117
    REALM_ASSERT(!m_unbind_message_sent);
17,920✔
2118
    REALM_ASSERT_3(m_target_download_mark, >, m_last_download_mark_sent);
17,920✔
2119

2120
    request_ident_type request_ident = m_target_download_mark;
17,920✔
2121
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
17,920✔
2122

2123
    ClientProtocol& protocol = m_conn.get_client_protocol();
17,920✔
2124
    OutputBuffer& out = m_conn.get_output_buffer();
17,920✔
2125
    session_ident_type session_ident = get_ident();
17,920✔
2126
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
17,920✔
2127
    m_conn.initiate_write_message(out, this);                      // Throws
17,920✔
2128

2129
    m_last_download_mark_sent = request_ident;
17,920✔
2130

2131
    // Other messages may be waiting to be sent
2132
    enlist_to_send(); // Throws
17,920✔
2133
}
17,920✔
2134

2135

2136
void Session::send_unbind_message()
2137
{
6,670✔
2138
    REALM_ASSERT_EX(m_state == Deactivating || m_error_message_received || m_suspended, m_state);
6,670✔
2139
    REALM_ASSERT(m_bind_message_sent);
6,670✔
2140
    REALM_ASSERT(!m_unbind_message_sent);
6,670✔
2141

2142
    logger.debug("Sending: UNBIND"); // Throws
6,670✔
2143

2144
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,670✔
2145
    OutputBuffer& out = m_conn.get_output_buffer();
6,670✔
2146
    session_ident_type session_ident = get_ident();
6,670✔
2147
    protocol.make_unbind_message(out, session_ident); // Throws
6,670✔
2148
    m_conn.initiate_write_message(out, this);         // Throws
6,670✔
2149

2150
    m_unbind_message_sent = true;
6,670✔
2151
}
6,670✔
2152

2153

2154
void Session::send_json_error_message()
2155
{
30✔
2156
    REALM_ASSERT_EX(m_state == Active, m_state);
30✔
2157
    REALM_ASSERT(m_ident_message_sent);
30✔
2158
    REALM_ASSERT(!m_unbind_message_sent);
30✔
2159
    REALM_ASSERT(m_error_to_send);
30✔
2160
    REALM_ASSERT(m_client_error);
30✔
2161

2162
    ClientProtocol& protocol = m_conn.get_client_protocol();
30✔
2163
    OutputBuffer& out = m_conn.get_output_buffer();
30✔
2164
    session_ident_type session_ident = get_ident();
30✔
2165
    auto protocol_error = m_client_error->error_for_server;
30✔
2166

2167
    auto message = util::format("%1", m_client_error->to_status());
30✔
2168
    logger.info("Sending: ERROR \"%1\" (error_code=%2, session_ident=%3)", message, static_cast<int>(protocol_error),
30✔
2169
                session_ident); // Throws
30✔
2170

2171
    nlohmann::json error_body_json;
30✔
2172
    error_body_json["message"] = std::move(message);
30✔
2173
    protocol.make_json_error_message(out, session_ident, static_cast<int>(protocol_error),
30✔
2174
                                     error_body_json.dump()); // Throws
30✔
2175
    m_conn.initiate_write_message(out, this);                 // Throws
30✔
2176

2177
    m_error_to_send = false;
30✔
2178
    enlist_to_send(); // Throws
30✔
2179
}
30✔
2180

2181

2182
void Session::send_test_command_message()
2183
{
64✔
2184
    REALM_ASSERT_EX(m_state == Active, m_state);
64✔
2185

2186
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
64✔
2187
                           [](const PendingTestCommand& command) {
68✔
2188
                               return command.pending;
68✔
2189
                           });
68✔
2190
    REALM_ASSERT(it != m_pending_test_commands.end());
64✔
2191

2192
    ClientProtocol& protocol = m_conn.get_client_protocol();
64✔
2193
    OutputBuffer& out = m_conn.get_output_buffer();
64✔
2194
    auto session_ident = get_ident();
64✔
2195

2196
    logger.info("Sending: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", it->body, session_ident, it->id);
64✔
2197
    protocol.make_test_command_message(out, session_ident, it->id, it->body);
64✔
2198

2199
    m_conn.initiate_write_message(out, this); // Throws;
64✔
2200
    it->pending = false;
64✔
2201

2202
    enlist_to_send();
64✔
2203
}
64✔
2204

2205
bool Session::client_reset_if_needed()
2206
{
424✔
2207
    // Even if we end up not actually performing a client reset, consume the
2208
    // config to ensure that the resources it holds are released
2209
    auto client_reset_config = std::exchange(get_client_reset_config(), std::nullopt);
424✔
2210
    if (!client_reset_config) {
424✔
2211
        return false;
×
2212
    }
×
2213

2214
    // Save a copy of the status and action in case an error/exception occurs
2215
    Status cr_status = client_reset_config->error;
424✔
2216
    ProtocolErrorInfo::Action cr_action = client_reset_config->action;
424✔
2217

2218
    try {
424✔
2219
        // The file ident from the fresh realm will be copied over to the local realm
2220
        bool did_reset = client_reset::perform_client_reset(logger, *get_db(), std::move(*client_reset_config),
424✔
2221
                                                            get_flx_subscription_store());
424✔
2222

2223
        call_debug_hook(SyncClientHookEvent::ClientResetMergeComplete);
424✔
2224
        if (!did_reset) {
424✔
2225
            return false;
×
2226
        }
×
2227
    }
424✔
2228
    catch (const std::exception& e) {
424✔
2229
        auto err_msg = util::format("A fatal error occurred during '%1' client reset diff for %2: '%3'", cr_action,
80✔
2230
                                    cr_status, e.what());
80✔
2231
        logger.error(err_msg.c_str());
80✔
2232
        SessionErrorInfo err_info(Status{ErrorCodes::AutoClientResetFailed, err_msg}, IsFatal{true});
80✔
2233
        suspend(err_info);
80✔
2234
        return false;
80✔
2235
    }
80✔
2236

2237
    // The fresh Realm has been used to reset the state
2238
    logger.debug("Client reset is completed, path = %1", get_realm_path()); // Throws
344✔
2239

2240
    // Update the version, file ident and progress info after the client reset diff is done
2241
    get_history().get_status(m_last_version_available, m_client_file_ident, m_progress); // Throws
344✔
2242
    // Print the version/progress information before performing the asserts
2243
    logger.debug("client_file_ident = %1, client_file_ident_salt = %2", m_client_file_ident.ident,
344✔
2244
                 m_client_file_ident.salt);                                // Throws
344✔
2245
    logger.debug("last_version_available = %1", m_last_version_available); // Throws
344✔
2246
    logger.debug("upload_progress_client_version = %1, upload_progress_server_version = %2",
344✔
2247
                 m_progress.upload.client_version,
344✔
2248
                 m_progress.upload.last_integrated_server_version); // Throws
344✔
2249
    logger.debug("download_progress_client_version = %1, download_progress_server_version = %2",
344✔
2250
                 m_progress.download.last_integrated_client_version,
344✔
2251
                 m_progress.download.server_version); // Throws
344✔
2252

2253
    REALM_ASSERT_EX(m_progress.download.last_integrated_client_version == 0,
344✔
2254
                    m_progress.download.last_integrated_client_version);
344✔
2255
    REALM_ASSERT_EX(m_progress.upload.client_version == 0, m_progress.upload.client_version);
344✔
2256

2257
    m_upload_progress = m_progress.upload;
344✔
2258
    m_download_progress = m_progress.download;
344✔
2259
    init_progress_handler();
344✔
2260
    // In recovery mode, there may be new changesets to upload and nothing left to download.
2261
    // In FLX DiscardLocal mode, there may be new commits due to subscription handling.
2262
    // For both, we want to allow uploads again without needing external changes to download first.
2263
    m_delay_uploads = false;
344✔
2264

2265
    // Checks if there is a pending client reset
2266
    handle_pending_client_reset_acknowledgement();
344✔
2267

2268
    // If a migration or rollback is in progress, mark it complete when client reset is completed.
2269
    if (auto migration_store = get_migration_store()) {
344✔
2270
        migration_store->complete_migration_or_rollback();
316✔
2271
    }
316✔
2272

2273
    return true;
344✔
2274
}
424✔
2275

2276
Status Session::receive_ident_message(SaltedFileIdent client_file_ident)
2277
{
3,628✔
2278
    logger.debug("Received: IDENT(client_file_ident=%1, client_file_ident_salt=%2)", client_file_ident.ident,
3,628✔
2279
                 client_file_ident.salt); // Throws
3,628✔
2280

2281
    // Ignore the message if the deactivation process has been initiated,
2282
    // because in that case, the associated Realm and SessionWrapper must
2283
    // not be accessed any longer.
2284
    if (m_state != Active)
3,628✔
2285
        return Status::OK(); // Success
78✔
2286

2287
    bool legal_at_this_time = (m_bind_message_sent && !have_client_file_ident() && !m_error_message_received &&
3,550✔
2288
                               !m_unbound_message_received);
3,550✔
2289
    if (REALM_UNLIKELY(!legal_at_this_time)) {
3,550✔
2290
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received IDENT message when it was not legal"};
×
2291
    }
×
2292
    if (REALM_UNLIKELY(client_file_ident.ident < 1)) {
3,550✔
2293
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier in IDENT message"};
×
2294
    }
×
2295
    if (REALM_UNLIKELY(client_file_ident.salt == 0)) {
3,550✔
2296
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier salt in IDENT message"};
×
2297
    }
×
2298

2299
    m_client_file_ident = client_file_ident;
3,550✔
2300

2301
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
3,550✔
2302
        // Ready to send the IDENT message
2303
        ensure_enlisted_to_send(); // Throws
×
2304
        return Status::OK();       // Success
×
2305
    }
×
2306

2307
    get_history().set_client_file_ident(client_file_ident,
3,550✔
2308
                                        m_fix_up_object_ids); // Throws
3,550✔
2309
    m_progress.download.last_integrated_client_version = 0;
3,550✔
2310
    m_progress.upload.client_version = 0;
3,550✔
2311

2312
    // Ready to send the IDENT message
2313
    ensure_enlisted_to_send(); // Throws
3,550✔
2314
    return Status::OK();       // Success
3,550✔
2315
}
3,550✔
2316

2317
Status Session::receive_download_message(const DownloadMessage& message)
2318
{
49,078✔
2319
    // Ignore the message if the deactivation process has been initiated,
2320
    // because in that case, the associated Realm and SessionWrapper must
2321
    // not be accessed any longer.
2322
    if (m_state != Active)
49,078✔
2323
        return Status::OK();
504✔
2324

2325
    bool is_flx = m_conn.is_flx_sync_connection();
48,574✔
2326
    int64_t query_version = is_flx ? *message.query_version : 0;
48,574✔
2327

2328
    if (!is_flx || query_version > 0)
48,574✔
2329
        enable_progress_notifications();
46,612✔
2330

2331
    auto&& progress = message.progress;
48,574✔
2332
    if (is_flx) {
48,574✔
2333
        logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
5,560✔
2334
                     "latest_server_version=%3, latest_server_version_salt=%4, "
5,560✔
2335
                     "upload_client_version=%5, upload_server_version=%6, progress_estimate=%7, "
5,560✔
2336
                     "batch_state=%8, query_version=%9, num_changesets=%10, ...)",
5,560✔
2337
                     progress.download.server_version, progress.download.last_integrated_client_version,
5,560✔
2338
                     progress.latest_server_version.version, progress.latest_server_version.salt,
5,560✔
2339
                     progress.upload.client_version, progress.upload.last_integrated_server_version,
5,560✔
2340
                     message.downloadable.as_estimate(), message.batch_state, query_version,
5,560✔
2341
                     message.changesets.size()); // Throws
5,560✔
2342
    }
5,560✔
2343
    else {
43,014✔
2344
        logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
43,014✔
2345
                     "latest_server_version=%3, latest_server_version_salt=%4, "
43,014✔
2346
                     "upload_client_version=%5, upload_server_version=%6, "
43,014✔
2347
                     "downloadable_bytes=%7, num_changesets=%8, ...)",
43,014✔
2348
                     progress.download.server_version, progress.download.last_integrated_client_version,
43,014✔
2349
                     progress.latest_server_version.version, progress.latest_server_version.salt,
43,014✔
2350
                     progress.upload.client_version, progress.upload.last_integrated_server_version,
43,014✔
2351
                     message.downloadable.as_bytes(), message.changesets.size()); // Throws
43,014✔
2352
    }
43,014✔
2353

2354
    // Ignore download messages when the client detects an error. This is to prevent transforming the same bad
2355
    // changeset over and over again.
2356
    if (m_client_error) {
48,574✔
2357
        logger.debug("Ignoring download message because the client detected an integration error");
×
2358
        return Status::OK();
×
2359
    }
×
2360

2361
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
48,574✔
2362
    if (REALM_UNLIKELY(!legal_at_this_time)) {
48,574✔
2363
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received DOWNLOAD message when it was not legal"};
×
2364
    }
×
2365
    if (auto status = check_received_sync_progress(progress); REALM_UNLIKELY(!status.is_ok())) {
48,574✔
2366
        logger.error("Bad sync progress received (%1)", status);
×
2367
        return status;
×
2368
    }
×
2369

2370
    version_type server_version = m_progress.download.server_version;
48,574✔
2371
    version_type last_integrated_client_version = m_progress.download.last_integrated_client_version;
48,574✔
2372
    for (const RemoteChangeset& changeset : message.changesets) {
50,672✔
2373
        // Check that per-changeset server version is strictly increasing, except in FLX sync where the server
2374
        // version must be increasing, but can stay the same during bootstraps.
2375
        bool good_server_version = m_is_flx_sync_session ? (changeset.remote_version >= server_version)
47,930✔
2376
                                                         : (changeset.remote_version > server_version);
47,930✔
2377
        // Each server version cannot be greater than the one in the header of the download message.
2378
        good_server_version = good_server_version && (changeset.remote_version <= progress.download.server_version);
47,930✔
2379
        if (!good_server_version) {
47,930✔
2380
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
2381
                    util::format("Bad server version in changeset header (DOWNLOAD) (%1, %2, %3)",
×
2382
                                 changeset.remote_version, server_version, progress.download.server_version)};
×
2383
        }
×
2384
        server_version = changeset.remote_version;
47,930✔
2385

2386
        // Check that per-changeset last integrated client version is "weakly"
2387
        // increasing.
2388
        bool good_client_version =
47,930✔
2389
            (changeset.last_integrated_local_version >= last_integrated_client_version &&
47,930✔
2390
             changeset.last_integrated_local_version <= progress.download.last_integrated_client_version);
47,930✔
2391
        if (!good_client_version) {
47,930✔
2392
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
2393
                    util::format("Bad last integrated client version in changeset header (DOWNLOAD) "
×
2394
                                 "(%1, %2, %3)",
×
2395
                                 changeset.last_integrated_local_version, last_integrated_client_version,
×
2396
                                 progress.download.last_integrated_client_version)};
×
2397
        }
×
2398
        last_integrated_client_version = changeset.last_integrated_local_version;
47,930✔
2399
        // Server shouldn't send our own changes, and zero is not a valid client
2400
        // file identifier.
2401
        bool good_file_ident =
47,930✔
2402
            (changeset.origin_file_ident > 0 && changeset.origin_file_ident != m_client_file_ident.ident);
47,932✔
2403
        if (!good_file_ident) {
47,930✔
2404
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
2405
                    util::format("Bad origin file identifier in changeset header (DOWNLOAD)",
×
2406
                                 changeset.origin_file_ident)};
×
2407
        }
×
2408
    }
47,930✔
2409

2410
    auto hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageReceived, progress, query_version,
48,574✔
2411
                                       message.batch_state, message.changesets.size());
48,574✔
2412
    if (hook_action == SyncClientHookAction::EarlyReturn) {
48,574✔
2413
        return Status::OK();
24✔
2414
    }
24✔
2415
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
48,550✔
2416

2417
    if (process_flx_bootstrap_message(message)) {
48,550✔
2418
        clear_resumption_delay_state();
4,002✔
2419
        return Status::OK();
4,002✔
2420
    }
4,002✔
2421

2422
    initiate_integrate_changesets(message.downloadable.as_bytes(), message.batch_state, progress,
44,548✔
2423
                                  message.changesets); // Throws
44,548✔
2424

2425
    hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
44,548✔
2426
                                  message.batch_state, message.changesets.size());
44,548✔
2427
    if (hook_action == SyncClientHookAction::EarlyReturn) {
44,548✔
2428
        return Status::OK();
×
2429
    }
×
2430
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
44,548✔
2431

2432
    // When we receive a DOWNLOAD message successfully, we can clear the backoff timer value used to reconnect
2433
    // after a retryable session error.
2434
    clear_resumption_delay_state();
44,548✔
2435
    return Status::OK();
44,548✔
2436
}
44,548✔
2437

2438
Status Session::receive_mark_message(request_ident_type request_ident)
2439
{
17,054✔
2440
    logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
17,054✔
2441

2442
    // Ignore the message if the deactivation process has been initiated,
2443
    // because in that case, the associated Realm and SessionWrapper must
2444
    // not be accessed any longer.
2445
    if (m_state != Active)
17,054✔
2446
        return Status::OK(); // Success
60✔
2447

2448
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
16,994✔
2449
    if (REALM_UNLIKELY(!legal_at_this_time)) {
16,994✔
2450
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received MARK message when it was not legal"};
12✔
2451
    }
12✔
2452
    bool good_request_ident =
16,982✔
2453
        (request_ident <= m_last_download_mark_sent && request_ident > m_last_download_mark_received);
16,982✔
2454
    if (REALM_UNLIKELY(!good_request_ident)) {
16,982✔
2455
        return {
×
2456
            ErrorCodes::SyncProtocolInvariantFailed,
×
2457
            util::format(
×
2458
                "Received MARK message with invalid request identifer (last mark sent: %1 last mark received: %2)",
×
2459
                m_last_download_mark_sent, m_last_download_mark_received)};
×
2460
    }
×
2461

2462
    m_server_version_at_last_download_mark = m_progress.download.server_version;
16,982✔
2463
    m_last_download_mark_received = request_ident;
16,982✔
2464
    check_for_download_completion(); // Throws
16,982✔
2465

2466
    return Status::OK(); // Success
16,982✔
2467
}
16,982✔
2468

2469

2470
// The caller (Connection) must discard the session if the session has become
2471
// deactivated upon return.
2472
Status Session::receive_unbound_message()
2473
{
4,140✔
2474
    logger.debug("Received: UNBOUND");
4,140✔
2475

2476
    bool legal_at_this_time = (m_unbind_message_sent && !m_error_message_received && !m_unbound_message_received);
4,140✔
2477
    if (REALM_UNLIKELY(!legal_at_this_time)) {
4,140✔
2478
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received UNBOUND message when it was not legal"};
×
2479
    }
×
2480

2481
    // The fact that the UNBIND message has been sent, but an ERROR message has
2482
    // not been received, implies that the deactivation process must have been
2483
    // initiated, so this session must be in the Deactivating state or the session
2484
    // has been suspended because of a client side error.
2485
    REALM_ASSERT_EX(m_state == Deactivating || m_suspended, m_state);
4,140!
2486

2487
    m_unbound_message_received = true;
4,140✔
2488

2489
    // Detect completion of the unbinding process
2490
    if (m_unbind_message_send_complete && m_state == Deactivating) {
4,140✔
2491
        // The deactivation process completes when the unbinding process
2492
        // completes.
2493
        complete_deactivation(); // Throws
4,140✔
2494
        // Life cycle state is now Deactivated
2495
    }
4,140✔
2496

2497
    return Status::OK(); // Success
4,140✔
2498
}
4,140✔
2499

2500

2501
void Session::receive_query_error_message(int error_code, std::string_view message, int64_t query_version)
2502
{
20✔
2503
    logger.info("Received QUERY_ERROR \"%1\" (error_code=%2, query_version=%3)", message, error_code, query_version);
20✔
2504
    on_flx_sync_error(query_version, message); // throws
20✔
2505
}
20✔
2506

2507
// The caller (Connection) must discard the session if the session has become
2508
// deactivated upon return.
2509
Status Session::receive_error_message(const ProtocolErrorInfo& info)
2510
{
910✔
2511
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, error_action=%4)", info.message,
910✔
2512
                info.raw_error_code, info.is_fatal, info.server_requests_action); // Throws
910✔
2513

2514
    bool legal_at_this_time = (m_bind_message_sent && !m_error_message_received && !m_unbound_message_received);
910✔
2515
    if (REALM_UNLIKELY(!legal_at_this_time)) {
910✔
2516
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received ERROR message when it was not legal"};
×
2517
    }
×
2518

2519
    auto protocol_error = static_cast<ProtocolError>(info.raw_error_code);
910✔
2520
    auto status = protocol_error_to_status(protocol_error, info.message);
910✔
2521
    if (status != ErrorCodes::UnknownError && REALM_UNLIKELY(!is_session_level_error(protocol_error))) {
910✔
2522
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
2523
                util::format("Received ERROR message for session with non-session-level error code %1",
×
2524
                             info.raw_error_code)};
×
2525
    }
×
2526

2527
    // Can't process debug hook actions once the Session is undergoing deactivation, since
2528
    // the SessionWrapper may not be available
2529
    if (m_state == Active) {
910✔
2530
        auto debug_action = call_debug_hook(SyncClientHookEvent::ErrorMessageReceived, &info);
896✔
2531
        if (debug_action == SyncClientHookAction::EarlyReturn) {
896✔
2532
            return Status::OK();
12✔
2533
        }
12✔
2534
    }
896✔
2535

2536
    // For compensating write errors, we need to defer raising them to the SDK until after the server version
2537
    // containing the compensating write has appeared in a download message.
2538
    if (status == ErrorCodes::SyncCompensatingWrite) {
898✔
2539
        // If the client is not active, the compensating writes will not be processed now, but will be
2540
        // sent again the next time the client connects
2541
        if (m_state == Active) {
60✔
2542
            REALM_ASSERT(info.compensating_write_server_version.has_value());
60✔
2543
            m_pending_compensating_write_errors.push_back(info);
60✔
2544
        }
60✔
2545
        return Status::OK();
60✔
2546
    }
60✔
2547

2548
    if (protocol_error == ProtocolError::schema_version_changed) {
838✔
2549
        // Enable upload immediately if the session is still active.
2550
        if (m_state == Active) {
70✔
2551
            auto wt = get_db()->start_write();
70✔
2552
            _impl::sync_schema_migration::track_sync_schema_migration(*wt, *info.previous_schema_version);
70✔
2553
            wt->commit();
70✔
2554
            // Notify SyncSession a schema migration is required.
2555
            on_connection_state_changed(m_conn.get_state(), SessionErrorInfo{info});
70✔
2556
        }
70✔
2557
        // Keep the session active to upload any unsynced changes.
2558
        return Status::OK();
70✔
2559
    }
70✔
2560

2561
    m_error_message_received = true;
768✔
2562
    suspend(SessionErrorInfo{info, std::move(status)});
768✔
2563
    return Status::OK();
768✔
2564
}
838✔
2565

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

2572
    m_suspended = true;
848✔
2573

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

2581
        // The deactivation process completes when the unbinding process
2582
        // completes.
2583
        complete_deactivation(); // Throws
14✔
2584
        // Life cycle state is now Deactivated
2585
    }
14✔
2586

2587
    // Notify the application of the suspension of the session if the session is
2588
    // still in the Active state
2589
    if (m_state == Active) {
848✔
2590
        call_debug_hook(SyncClientHookEvent::SessionSuspended, &info);
834✔
2591
        m_conn.one_less_active_unsuspended_session(); // Throws
834✔
2592
        on_suspended(info);                           // Throws
834✔
2593
    }
834✔
2594

2595
    if (!info.is_fatal) {
848✔
2596
        begin_resumption_delay(info);
184✔
2597
    }
184✔
2598

2599
    // Ready to send the UNBIND message, if it has not been sent already
2600
    if (!m_unbind_message_sent)
848✔
2601
        ensure_enlisted_to_send(); // Throws
834✔
2602
}
848✔
2603

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

2616
    it->promise.emplace_value(std::string{body});
64✔
2617
    m_pending_test_commands.erase(it);
64✔
2618

2619
    return Status::OK();
64✔
2620
}
64✔
2621

2622
void Session::begin_resumption_delay(const ProtocolErrorInfo& error_info)
2623
{
184✔
2624
    REALM_ASSERT(!m_try_again_activation_timer);
184✔
2625

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

2642
        m_try_again_activation_timer.reset();
154✔
2643
        cancel_resumption_delay();
154✔
2644
    });
154✔
2645
}
184✔
2646

2647
void Session::clear_resumption_delay_state()
2648
{
48,548✔
2649
    if (m_try_again_activation_timer) {
48,548✔
2650
        logger.debug("Clearing resumption delay state after successful download");
×
2651
        m_try_again_delay_info.reset();
×
2652
    }
×
2653
}
48,548✔
2654

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

2704
    if (message.empty()) {
48,568✔
2705
        return Status::OK();
48,566✔
2706
    }
48,566✔
2707
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
2✔
2708
}
48,568✔
2709

2710

2711
void Session::check_for_download_completion()
2712
{
63,910✔
2713
    REALM_ASSERT_3(m_target_download_mark, >=, m_last_download_mark_received);
63,910✔
2714
    REALM_ASSERT_3(m_last_download_mark_received, >=, m_last_triggering_download_mark);
63,910✔
2715
    if (m_last_download_mark_received == m_last_triggering_download_mark)
63,910✔
2716
        return;
46,686✔
2717
    if (m_last_download_mark_received < m_target_download_mark)
17,224✔
2718
        return;
366✔
2719
    if (m_download_progress.server_version < m_server_version_at_last_download_mark)
16,858✔
2720
        return;
×
2721
    m_last_triggering_download_mark = m_target_download_mark;
16,858✔
2722
    if (REALM_UNLIKELY(m_delay_uploads)) {
16,858✔
2723
        // Activate the upload process now, and enable immediate reactivation
2724
        // after a subsequent fast reconnect.
2725
        m_delay_uploads = false;
4,772✔
2726
        ensure_enlisted_to_send(); // Throws
4,772✔
2727
    }
4,772✔
2728
    on_download_completion(); // Throws
16,858✔
2729
}
16,858✔
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

© 2025 Coveralls, Inc