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

realm / realm-core / github_pull_request_281922

31 Oct 2023 09:13AM UTC coverage: 90.445% (-0.08%) from 90.528%
github_pull_request_281922

Pull #7039

Evergreen

jedelbo
Merge branch 'next-major' into je/global-key
Pull Request #7039: Remove ability to synchronize objects without primary key

95324 of 175822 branches covered (0.0%)

101 of 105 new or added lines in 13 files covered. (96.19%)

238 existing lines in 19 files now uncovered.

232657 of 257235 relevant lines covered (90.45%)

6351359.67 hits per line

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

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

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

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

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

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

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

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

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

52

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

59

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

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

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

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

85

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

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

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

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

4,416✔
192
    if (config.reconnect_mode != ReconnectMode::normal) {
8,970✔
193
        logger.warn("Testing/debugging feature 'nonnormal reconnect mode' enabled - "
768✔
194
                    "never do this in production!");
768✔
195
    }
768✔
196

4,416✔
197
    if (config.dry_run) {
8,970✔
198
        logger.warn("Testing/debugging feature 'dry run' enabled - "
×
199
                    "never do this in production!");
×
200
    }
×
201

4,416✔
202
    REALM_ASSERT_EX(m_socket_provider, "Must provide socket provider in sync Client config");
8,970✔
203

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

4,416✔
211
    if (config.disable_upload_activation_delay) {
8,970✔
212
        logger.warn("Testing/debugging feature 'disable_upload_activation_delay' enabled - "
×
213
                    "never do this in production");
×
214
    }
×
215

4,416✔
216
    if (config.disable_sync_to_disk) {
8,970✔
217
        logger.warn("Testing/debugging feature 'disable_sync_to_disk' enabled - "
×
218
                    "never do this in production");
×
219
    }
×
220

4,416✔
221
    m_actualize_and_finalize = create_trigger([this](Status status) {
14,984✔
222
        if (status == ErrorCodes::OperationAborted)
14,984✔
223
            return;
×
224
        else if (!status.is_ok())
14,984✔
225
            throw Exception(status);
×
226
        actualize_and_finalize_session_wrappers(); // Throws
14,984✔
227
    });
14,984✔
228
}
8,970✔
229

230

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

250

251
void ClientImpl::drain_connections()
252
{
8,970✔
253
    logger.debug("Draining connections during sync client shutdown");
8,970✔
254
    for (auto& server_slot_pair : m_server_slots) {
5,654✔
255
        auto& server_slot = server_slot_pair.second;
2,340✔
256

1,102✔
257
        if (server_slot.connection) {
2,340✔
258
            auto& conn = server_slot.connection;
2,240✔
259
            conn->force_close();
2,240✔
260
        }
2,240✔
261
        else {
100✔
262
            for (auto& conn_pair : server_slot.alt_connections) {
48✔
263
                conn_pair.second->force_close();
2✔
264
            }
2✔
265
        }
100✔
266
    }
2,340✔
267
}
8,970✔
268

269

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

8,008✔
282
        std::lock_guard lock(m_drain_mutex);
16,300✔
283
        REALM_ASSERT(m_outstanding_posts);
16,300✔
284
        --m_outstanding_posts;
16,300✔
285
        m_drain_cv.notify_all();
16,300✔
286
    });
16,300✔
287
}
16,300✔
288

289

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

296
Connection::~Connection()
297
{
2,450✔
298
    if (m_websocket_sentinel) {
2,450✔
299
        m_websocket_sentinel->destroyed = true;
×
300
        m_websocket_sentinel.reset();
×
301
    }
×
302
}
2,450✔
303

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

315

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

336

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

355

356
void Connection::cancel_reconnect_delay()
357
{
2,060✔
358
    REALM_ASSERT(m_activated);
2,060✔
359

1,142✔
360
    if (m_reconnect_delay_in_progress) {
2,060✔
361
        if (m_nonzero_reconnect_delay)
1,848✔
362
            logger.detail("Canceling reconnect delay"); // Throws
928✔
363

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

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

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

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

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

1,056✔
410
    m_force_closed = true;
2,242✔
411

1,056✔
412
    if (m_state != ConnectionState::disconnected) {
2,242✔
413
        voluntary_disconnect();
2,158✔
414
    }
2,158✔
415

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

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

1,056✔
433
    for (auto& sess : to_close) {
1,130✔
434
        sess->force_close();
150✔
435
    }
150✔
436

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

440

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

483

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

37,952✔
491
    using sf = SimulatedFailure;
74,112✔
492
    if (sf::check_trigger(sf::sync_client__read_head)) {
74,112✔
493
        close_due_to_client_side_error(
442✔
494
            {ErrorCodes::RuntimeError, "Simulated failure during sync client websocket read"}, IsFatal{false},
442✔
495
            ConnectionTerminationReason::read_or_write_error);
442✔
496
        return bool(m_websocket);
442✔
497
    }
442✔
498

37,698✔
499
    handle_message_received(data);
73,670✔
500
    return bool(m_websocket);
73,670✔
501
}
73,670✔
502

503

504
void Connection::websocket_error_handler()
505
{
570✔
506
    m_websocket_error_received = true;
570✔
507
}
570✔
508

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

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

370✔
623
    return bool(m_websocket);
696✔
624
}
696✔
625

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

3,860✔
634
    // If we've been force closed then we don't need/want to reconnect. Just return early here.
3,860✔
635
    if (m_force_closed) {
7,654✔
636
        return;
2,154✔
637
    }
2,154✔
638

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

2,304✔
648
    if (delay == std::chrono::milliseconds::zero()) {
4,524✔
649
        m_nonzero_reconnect_delay = false;
4,296✔
650
    }
4,296✔
651
    else {
228✔
652
        logger.detail("Allowing reconnection in %1 milliseconds", delay.count()); // Throws
228✔
653
        m_nonzero_reconnect_delay = true;
228✔
654
    }
228✔
655

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

667

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

1,666✔
675
    REALM_ASSERT(m_reconnect_delay_in_progress);
3,354✔
676
    m_reconnect_delay_in_progress = false;
3,354✔
677

1,666✔
678
    if (m_num_active_unsuspended_sessions > 0)
3,354✔
679
        initiate_reconnect(); // Throws
3,354✔
680
}
3,354✔
681

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

689
    Connection* conn;
690
    util::bind_ptr<LifecycleSentinel> sentinel;
691

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

1,604✔
698
        return conn->websocket_connected_handler(protocol);
3,232✔
699
    }
3,232✔
700

701
    void websocket_error_handler() override
702
    {
570✔
703
        if (sentinel->destroyed) {
570✔
704
            return;
×
705
        }
×
706

308✔
707
        conn->websocket_error_handler();
570✔
708
    }
570✔
709

710
    bool websocket_binary_message_received(util::Span<const char> data) override
711
    {
74,112✔
712
        if (sentinel->destroyed) {
74,112✔
713
            return false;
×
714
        }
×
715

37,952✔
716
        return conn->websocket_binary_message_received(data);
74,112✔
717
    }
74,112✔
718

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

370✔
725
        return conn->websocket_closed_handler(was_clean, error_code, msg);
696✔
726
    }
696✔
727
};
728

729
void Connection::initiate_reconnect()
730
{
3,354✔
731
    REALM_ASSERT(m_activated);
3,354✔
732

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

1,666✔
741
    // Watchdog
1,666✔
742
    initiate_connect_wait(); // Throws
3,354✔
743

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

1,666✔
758
    logger.info("Connecting to '%1%2:%3%4'", to_string(m_server_endpoint.envelope), m_server_endpoint.address,
3,354✔
759
                m_server_endpoint.port, m_http_request_path_prefix);
3,354✔
760

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

779

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

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

796

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

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

812

813
void Connection::handle_connection_established()
814
{
3,232✔
815
    // Cancel connect timeout watchdog
1,604✔
816
    m_connect_timer.reset();
3,232✔
817

1,604✔
818
    m_state = ConnectionState::connected;
3,232✔
819

1,604✔
820
    milliseconds_type now = monotonic_clock_now();
3,232✔
821
    m_pong_wait_started_at = now; // Initially, no time was spent waiting for a PONG message
3,232✔
822
    initiate_ping_delay(now);     // Throws
3,232✔
823

1,604✔
824
    bool fast_reconnect = false;
3,232✔
825
    if (m_disconnect_has_occurred) {
3,232✔
826
        milliseconds_type time = now - m_disconnect_time;
984✔
827
        if (time <= m_client.m_fast_reconnect_limit)
984✔
828
            fast_reconnect = true;
984✔
829
    }
984✔
830

1,604✔
831
    for (auto& p : m_sessions) {
4,306✔
832
        Session& sess = *p.second;
4,306✔
833
        sess.connection_established(fast_reconnect); // Throws
4,306✔
834
    }
4,306✔
835

1,604✔
836
    report_connection_state_change(ConnectionState::connected); // Throws
3,232✔
837
}
3,232✔
838

839

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

856

857
void Connection::initiate_ping_delay(milliseconds_type now)
858
{
3,600✔
859
    REALM_ASSERT(!m_ping_delay_in_progress);
3,600✔
860
    REALM_ASSERT(!m_waiting_for_pong);
3,600✔
861
    REALM_ASSERT(!m_send_ping);
3,600✔
862

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

1,746✔
889

1,746✔
890
    m_ping_delay_in_progress = true;
3,600✔
891

1,746✔
892
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
3,600✔
893
        if (status == ErrorCodes::OperationAborted)
3,600✔
894
            return;
3,384✔
895
        else if (!status.is_ok())
216✔
896
            throw Exception(status);
×
897

78✔
898
        handle_ping_delay();                                    // Throws
216✔
899
    });                                                         // Throws
216✔
900
    logger.debug("Will emit a ping in %1 milliseconds", delay); // Throws
3,600✔
901
}
3,600✔
902

903

904
void Connection::handle_ping_delay()
905
{
216✔
906
    REALM_ASSERT(m_ping_delay_in_progress);
216✔
907
    m_ping_delay_in_progress = false;
216✔
908
    m_send_ping = true;
216✔
909

78✔
910
    initiate_pong_timeout(); // Throws
216✔
911

78✔
912
    if (m_state == ConnectionState::connected && !m_sending)
216✔
913
        send_next_message(); // Throws
180✔
914
}
216✔
915

916

917
void Connection::initiate_pong_timeout()
918
{
216✔
919
    REALM_ASSERT(!m_ping_delay_in_progress);
216✔
920
    REALM_ASSERT(!m_waiting_for_pong);
216✔
921
    REALM_ASSERT(m_send_ping);
216✔
922

78✔
923
    m_waiting_for_pong = true;
216✔
924
    m_pong_wait_started_at = monotonic_clock_now();
216✔
925

78✔
926
    milliseconds_type time = m_client.m_pong_keepalive_timeout;
216✔
927
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
216✔
928
        if (status == ErrorCodes::OperationAborted)
216✔
929
            return;
204✔
930
        else if (!status.is_ok())
12✔
931
            throw Exception(status);
×
932

6✔
933
        handle_pong_timeout(); // Throws
12✔
934
    });                        // Throws
12✔
935
}
216✔
936

937

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

946

947
void Connection::initiate_write_message(const OutputBuffer& out, Session* sess)
948
{
93,824✔
949
    // Stop sending messages if an websocket error was received.
46,942✔
950
    if (m_websocket_error_received)
93,824✔
951
        return;
×
952

46,942✔
953
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
93,824✔
954
        if (sentinel->destroyed) {
93,734✔
955
            return;
1,448✔
956
        }
1,448✔
957
        if (!status.is_ok()) {
92,286✔
958
            if (status != ErrorCodes::Error::OperationAborted) {
×
959
                // Write errors will be handled by the websocket_write_error_handler() callback
960
                logger.error("Connection: write failed %1: %2", status.code_string(), status.reason());
×
961
            }
×
962
            return;
×
963
        }
×
964
        handle_write_message(); // Throws
92,286✔
965
    });                         // Throws
92,286✔
966
    m_sending_session = sess;
93,824✔
967
    m_sending = true;
93,824✔
968
}
93,824✔
969

970

971
void Connection::handle_write_message()
972
{
92,284✔
973
    m_sending_session->message_sent(); // Throws
92,284✔
974
    if (m_sending_session->m_state == Session::Deactivated) {
92,284✔
975
        finish_session_deactivation(m_sending_session);
100✔
976
    }
100✔
977
    m_sending_session = nullptr;
92,284✔
978
    m_sending = false;
92,284✔
979
    send_next_message(); // Throws
92,284✔
980
}
92,284✔
981

982

983
void Connection::send_next_message()
984
{
152,792✔
985
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
152,792✔
986
    REALM_ASSERT(!m_sending_session);
152,792✔
987
    REALM_ASSERT(!m_sending);
152,792✔
988
    if (m_send_ping) {
152,792✔
989
        send_ping(); // Throws
204✔
990
        return;
204✔
991
    }
204✔
992
    while (!m_sessions_enlisted_to_send.empty()) {
215,324✔
993
        // The state of being connected is not supposed to be able to change
78,334✔
994
        // across this loop thanks to the "no callback reentrance" guarantee
78,334✔
995
        // provided by Websocket::async_write_text(), and friends.
78,334✔
996
        REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
156,766✔
997

78,334✔
998
        Session& sess = *m_sessions_enlisted_to_send.front();
156,766✔
999
        m_sessions_enlisted_to_send.pop_front();
156,766✔
1000
        sess.send_message(); // Throws
156,766✔
1001

78,334✔
1002
        if (sess.m_state == Session::Deactivated) {
156,766✔
1003
            finish_session_deactivation(&sess);
2,816✔
1004
        }
2,816✔
1005

78,334✔
1006
        // An enlisted session may choose to not send a message. In that case,
78,334✔
1007
        // we should pass the opportunity to the next enlisted session.
78,334✔
1008
        if (m_sending)
156,766✔
1009
            break;
94,030✔
1010
    }
156,766✔
1011
}
152,588✔
1012

1013

1014
void Connection::send_ping()
1015
{
204✔
1016
    REALM_ASSERT(!m_ping_delay_in_progress);
204✔
1017
    REALM_ASSERT(m_waiting_for_pong);
204✔
1018
    REALM_ASSERT(m_send_ping);
204✔
1019

72✔
1020
    m_send_ping = false;
204✔
1021
    if (m_reconnect_info.scheduled_reset)
204✔
1022
        m_ping_after_scheduled_reset_of_reconnect_info = true;
148✔
1023

72✔
1024
    m_last_ping_sent_at = monotonic_clock_now();
204✔
1025
    logger.debug("Sending: PING(timestamp=%1, rtt=%2)", m_last_ping_sent_at,
204✔
1026
                 m_previous_ping_rtt); // Throws
204✔
1027

72✔
1028
    ClientProtocol& protocol = get_client_protocol();
204✔
1029
    OutputBuffer& out = get_output_buffer();
204✔
1030
    protocol.make_ping(out, m_last_ping_sent_at, m_previous_ping_rtt); // Throws
204✔
1031
    initiate_write_ping(out);                                          // Throws
204✔
1032
    m_ping_sent = true;
204✔
1033
}
204✔
1034

1035

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

1054

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

1063

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

1071

1072
void Connection::initiate_disconnect_wait()
1073
{
4,252✔
1074
    REALM_ASSERT(!m_reconnect_delay_in_progress);
4,252✔
1075

2,018✔
1076
    if (m_disconnect_delay_in_progress) {
4,252✔
1077
        m_reconnect_disconnect_timer.reset();
2,036✔
1078
        m_disconnect_delay_in_progress = false;
2,036✔
1079
    }
2,036✔
1080

2,018✔
1081
    milliseconds_type time = m_client.m_connection_linger_time;
4,252✔
1082

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

1092

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

6✔
1100
    m_disconnect_delay_in_progress = false;
12✔
1101

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

1111

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

1120

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

260✔
1125
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
452✔
1126
}
452✔
1127

1128

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

306✔
1135
    involuntary_disconnect(std::move(error_info), reason); // Throw
568✔
1136
}
568✔
1137

1138

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

34✔
1146
    const auto reason = info.is_fatal ? ConnectionTerminationReason::server_said_do_not_reconnect
44✔
1147
                                      : ConnectionTerminationReason::server_said_try_again_later;
58✔
1148
    involuntary_disconnect(SessionErrorInfo{info, protocol_error_to_status(error_code, info.message)},
68✔
1149
                           reason); // Throws
68✔
1150
}
68✔
1151

1152

1153
void Connection::disconnect(const SessionErrorInfo& info)
1154
{
3,354✔
1155
    // Cancel connect timeout watchdog
1,666✔
1156
    m_connect_timer.reset();
3,354✔
1157

1,666✔
1158
    if (m_state == ConnectionState::connected) {
3,354✔
1159
        m_disconnect_time = monotonic_clock_now();
3,230✔
1160
        m_disconnect_has_occurred = true;
3,230✔
1161

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

1,666✔
1178
    change_state_to_disconnected();
3,354✔
1179

1,666✔
1180
    m_ping_delay_in_progress = false;
3,354✔
1181
    m_waiting_for_pong = false;
3,354✔
1182
    m_send_ping = false;
3,354✔
1183
    m_minimize_next_ping_delay = false;
3,354✔
1184
    m_ping_after_scheduled_reset_of_reconnect_info = false;
3,354✔
1185
    m_ping_sent = false;
3,354✔
1186
    m_heartbeat_timer.reset();
3,354✔
1187
    m_previous_ping_rtt = 0;
3,354✔
1188

1,666✔
1189
    m_websocket_sentinel->destroyed = true;
3,354✔
1190
    m_websocket_sentinel.reset();
3,354✔
1191
    m_websocket.reset();
3,354✔
1192
    m_input_body_buffer.reset();
3,354✔
1193
    m_sending_session = nullptr;
3,354✔
1194
    m_sessions_enlisted_to_send.clear();
3,354✔
1195
    m_sending = false;
3,354✔
1196

1,666✔
1197
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
3,354✔
1198
    initiate_reconnect_wait();                                           // Throws
3,354✔
1199
}
3,354✔
1200

1201
bool Connection::is_flx_sync_connection() const noexcept
1202
{
103,702✔
1203
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
103,702✔
1204
}
103,702✔
1205

1206
void Connection::receive_pong(milliseconds_type timestamp)
1207
{
192✔
1208
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
192✔
1209

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

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

66✔
1225
    milliseconds_type now = monotonic_clock_now();
192✔
1226
    milliseconds_type round_trip_time = now - timestamp;
192✔
1227
    logger.debug("Round trip time was %1 milliseconds", round_trip_time);
192✔
1228
    m_previous_ping_rtt = round_trip_time;
192✔
1229

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

66✔
1239
    m_heartbeat_timer.reset();
192✔
1240
    m_waiting_for_pong = false;
192✔
1241

66✔
1242
    initiate_ping_delay(now); // Throws
192✔
1243

66✔
1244
    if (m_client.m_roundtrip_time_handler)
192✔
1245
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
×
1246
}
192✔
1247

1248
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
1249
{
67,576✔
1250
    if (session_ident == 0) {
67,576✔
1251
        return nullptr;
×
1252
    }
×
1253

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

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

448✔
1286
        if (sess->m_state == Session::Deactivated) {
866✔
1287
            finish_session_deactivation(sess);
×
1288
        }
×
1289
        return;
866✔
1290
    }
866✔
1291

36✔
1292
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
72✔
1293
                info.message, info.raw_error_code, info.is_fatal, session_ident,
72✔
1294
                info.server_requests_action); // Throws
72✔
1295

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

1315

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

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

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

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

1339

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

1,506✔
1347
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
3,294✔
1348
        close_due_to_protocol_error(std::move(status)); // Throws
×
1349
}
3,294✔
1350

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

23,214✔
1361
    if (auto status = sess->receive_download_message(progress, downloadable_bytes, batch_state, query_version,
43,750✔
1362
                                                     received_changesets);
43,750✔
1363
        !status.is_ok()) {
43,750✔
1364
        close_due_to_protocol_error(std::move(status));
×
1365
    }
×
1366
}
43,750✔
1367

1368
void Connection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
1369
{
15,658✔
1370
    Session* sess = find_and_validate_session(session_ident, "MARK");
15,658✔
1371
    if (REALM_UNLIKELY(!sess)) {
15,658✔
1372
        return;
×
1373
    }
×
1374

7,742✔
1375
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
15,658✔
1376
        close_due_to_protocol_error(std::move(status)); // Throws
×
1377
}
15,658✔
1378

1379

1380
void Connection::receive_unbound_message(session_ident_type session_ident)
1381
{
3,950✔
1382
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
3,950✔
1383
    if (REALM_UNLIKELY(!sess)) {
3,950✔
1384
        return;
×
1385
    }
×
1386

1,712✔
1387
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
3,950✔
1388
        close_due_to_protocol_error(std::move(status)); // Throws
×
1389
        return;
×
1390
    }
×
1391

1,712✔
1392
    if (sess->m_state == Session::Deactivated) {
3,950✔
1393
        finish_session_deactivation(sess);
3,950✔
1394
    }
3,950✔
1395
}
3,950✔
1396

1397

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

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

1411

1412
void Connection::receive_server_log_message(session_ident_type session_ident, util::Logger::Level level,
1413
                                            std::string_view message)
1414
{
5,828✔
1415
    std::string prefix;
5,828✔
1416
    if (REALM_LIKELY(!m_appservices_coid.empty())) {
5,828✔
1417
        prefix = util::format("Server[%1]", m_appservices_coid);
5,828✔
1418
    }
5,828✔
UNCOV
1419
    else {
×
UNCOV
1420
        prefix = "Server";
×
UNCOV
1421
    }
×
1422

2,944✔
1423
    if (session_ident != 0) {
5,828✔
1424
        if (auto sess = get_session(session_ident)) {
3,898✔
1425
            sess->logger.log(LogCategory::session, level, "%1 log: %2", prefix, message);
3,898✔
1426
            return;
3,898✔
1427
        }
3,898✔
1428

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

970✔
1434
    logger.log(level, "%1 log: %2", prefix, message);
1,930✔
1435
}
1,930✔
1436

1437

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

1448

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

1454

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

1471

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

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

2,366✔
1481
    if (!m_suspended)
4,250✔
1482
        return;
3,888✔
1483

198✔
1484
    m_suspended = false;
362✔
1485

198✔
1486
    logger.debug("Resumed"); // Throws
362✔
1487

198✔
1488
    if (unbind_process_complete())
362✔
1489
        initiate_rebind(); // Throws
356✔
1490

198✔
1491
    m_conn.one_more_active_unsuspended_session(); // Throws
362✔
1492

198✔
1493
    on_resumed(); // Throws
362✔
1494
}
362✔
1495

1496

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

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

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

1524

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

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

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

1574

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

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

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

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

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

16,496✔
1609
        check_for_upload_completion();
31,568✔
1610
    }
31,568✔
1611

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

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

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

1629

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

1635

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

1644

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

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

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

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

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

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

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

4,628✔
1697
    reset_protocol_state();
9,604✔
1698
    m_state = Active;
9,604✔
1699

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

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

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

1718

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

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

4,628✔
1727
    m_state = Deactivating;
9,604✔
1728

4,628✔
1729
    if (!m_suspended)
9,604✔
1730
        m_conn.one_less_active_unsuspended_session(); // Throws
9,080✔
1731

4,628✔
1732
    if (m_enlisted_to_send) {
9,604✔
1733
        REALM_ASSERT(!unbind_process_complete());
5,048✔
1734
        return;
5,048✔
1735
    }
5,048✔
1736

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

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

1753

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

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

1762

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

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

74,026✔
1789
    // Session life cycle state is Active and the unbinding process has
74,026✔
1790
    // not been initiated
74,026✔
1791
    REALM_ASSERT(!m_unbind_message_sent);
147,860✔
1792

74,026✔
1793
    if (!m_bind_message_sent)
147,860✔
1794
        return send_bind_message(); // Throws
8,536✔
1795

69,822✔
1796
    if (!m_ident_message_sent) {
139,324✔
1797
        if (have_client_file_ident())
6,702✔
1798
            send_ident_message(); // Throws
6,702✔
1799
        return;
6,702✔
1800
    }
6,702✔
1801

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

66,426✔
1810
    if (m_error_to_send)
132,578✔
1811
        return send_json_error_message(); // Throws
30✔
1812

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

66,404✔
1818
    if (m_target_download_mark > m_last_download_mark_sent)
132,532✔
1819
        return send_mark_message(); // Throws
16,224✔
1820

58,378✔
1821
    auto is_upload_allowed = [&]() -> bool {
116,316✔
1822
        if (!m_is_flx_sync_session) {
116,316✔
1823
            return true;
105,362✔
1824
        }
105,362✔
1825

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

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

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

58,378✔
1840
    if (!is_upload_allowed()) {
116,308✔
1841
        return;
16✔
1842
    }
16✔
1843

58,370✔
1844
    auto check_pending_flx_version = [&]() -> bool {
116,302✔
1845
        if (!m_is_flx_sync_session) {
116,302✔
1846
            return false;
105,360✔
1847
        }
105,360✔
1848

5,646✔
1849
        if (!m_allow_upload) {
10,942✔
1850
            return false;
2,170✔
1851
        }
2,170✔
1852

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

4,552✔
1856
        if (!m_pending_flx_sub_set) {
8,772✔
1857
            return false;
7,294✔
1858
        }
7,294✔
1859

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

58,370✔
1863
    if (check_pending_flx_version()) {
116,292✔
1864
        return send_query_change_message(); // throws
834✔
1865
    }
834✔
1866

57,954✔
1867
    if (m_allow_upload && (m_last_version_available > m_upload_progress.client_version)) {
115,458✔
1868
        return send_upload_message(); // Throws
55,574✔
1869
    }
55,574✔
1870
}
115,458✔
1871

1872

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

4,204✔
1877
    session_ident_type session_ident = m_ident;
8,536✔
1878
    bool need_client_file_ident = !have_client_file_ident();
8,536✔
1879
    const bool is_subserver = false;
8,536✔
1880

4,204✔
1881

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

4,204✔
1914
    m_bind_message_sent = true;
8,536✔
1915

4,204✔
1916
    // Ready to send the IDENT message if the file identifier pair is already
4,204✔
1917
    // available.
4,204✔
1918
    if (!need_client_file_ident)
8,536✔
1919
        enlist_to_send(); // Throws
3,630✔
1920
}
8,536✔
1921

1922

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

3,374✔
1930

3,374✔
1931
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,702✔
1932
    OutputBuffer& out = m_conn.get_output_buffer();
6,702✔
1933
    session_ident_type session_ident = m_ident;
6,702✔
1934

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

3,374✔
1960
    m_ident_message_sent = true;
6,702✔
1961

3,374✔
1962
    // Other messages may be waiting to be sent
3,374✔
1963
    enlist_to_send(); // Throws
6,702✔
1964
}
6,702✔
1965

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

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

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

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

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

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

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

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

28,150✔
2004
    version_type target_upload_version = get_db()->get_version_of_latest_snapshot();
55,574✔
2005
    if (m_pending_flx_sub_set) {
55,574✔
2006
        REALM_ASSERT(m_is_flx_sync_session);
644✔
2007
        target_upload_version = m_pending_flx_sub_set->snapshot_version;
644✔
2008
    }
644✔
2009
    if (target_upload_version > m_last_version_available) {
55,574✔
2010
        m_last_version_available = target_upload_version;
428✔
2011
    }
428✔
2012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

28,046✔
2129
    // Other messages may be waiting to be sent
28,046✔
2130
    enlist_to_send(); // Throws
55,366✔
2131
}
55,366✔
2132

2133

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

8,026✔
2141
    request_ident_type request_ident = m_target_download_mark;
16,224✔
2142
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
16,224✔
2143

8,026✔
2144
    ClientProtocol& protocol = m_conn.get_client_protocol();
16,224✔
2145
    OutputBuffer& out = m_conn.get_output_buffer();
16,224✔
2146
    session_ident_type session_ident = get_ident();
16,224✔
2147
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
16,224✔
2148
    m_conn.initiate_write_message(out, this);                      // Throws
16,224✔
2149

8,026✔
2150
    m_last_download_mark_sent = request_ident;
16,224✔
2151

8,026✔
2152
    // Other messages may be waiting to be sent
8,026✔
2153
    enlist_to_send(); // Throws
16,224✔
2154
}
16,224✔
2155

2156

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

2,842✔
2163
    logger.debug("Sending: UNBIND"); // Throws
6,090✔
2164

2,842✔
2165
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,090✔
2166
    OutputBuffer& out = m_conn.get_output_buffer();
6,090✔
2167
    session_ident_type session_ident = get_ident();
6,090✔
2168
    protocol.make_unbind_message(out, session_ident); // Throws
6,090✔
2169
    m_conn.initiate_write_message(out, this);         // Throws
6,090✔
2170

2,842✔
2171
    m_unbind_message_sent = true;
6,090✔
2172
}
6,090✔
2173

2174

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

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

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

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

14✔
2198
    m_error_to_send = false;
30✔
2199
    enlist_to_send(); // Throws
30✔
2200
}
30✔
2201

2202

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

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

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

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

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

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

2226

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

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

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

1,500✔
2250
    m_client_file_ident = client_file_ident;
3,166✔
2251

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

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

1,500✔
2263
    auto client_reset_if_needed = [&]() -> bool {
3,166✔
2264
        if (!m_client_reset_operation) {
3,166✔
2265
            return false;
2,830✔
2266
        }
2,830✔
2267

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

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

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

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

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

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

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

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

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

22,938✔
2353
    if (is_steady_state_download_message(batch_state, query_version)) {
43,282✔
2354
        batch_state = DownloadBatchState::SteadyState;
41,708✔
2355
    }
41,708✔
2356

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

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

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

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

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

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

22,148✔
2433
    initiate_integrate_changesets(downloadable_bytes, batch_state, progress, received_changesets); // Throws
41,704✔
2434

22,148✔
2435
    hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
41,704✔
2436
                                  batch_state, received_changesets.size());
41,704✔
2437
    if (hook_action == SyncClientHookAction::EarlyReturn) {
41,704✔
2438
        return Status::OK();
×
2439
    }
×
2440
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
41,704✔
2441

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

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

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

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

7,708✔
2472
    m_server_version_at_last_download_mark = m_progress.download.server_version;
15,616✔
2473
    m_last_download_mark_received = request_ident;
15,616✔
2474
    check_for_download_completion(); // Throws
15,616✔
2475

7,708✔
2476
    return Status::OK(); // Success
15,616✔
2477
}
15,616✔
2478

2479

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

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

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

1,712✔
2497
    m_unbound_message_received = true;
3,950✔
2498

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

1,712✔
2507
    return Status::OK(); // Success
3,950✔
2508
}
3,950✔
2509

2510

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

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

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

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

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

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

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

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

458✔
2575
    m_suspended = true;
886✔
2576

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

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

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

458✔
2597
    if (!info.is_fatal) {
886✔
2598
        begin_resumption_delay(info);
358✔
2599
    }
358✔
2600

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

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

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

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

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

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

194✔
2644
        m_try_again_activation_timer.reset();
354✔
2645
        cancel_resumption_delay();
354✔
2646
    });
354✔
2647
}
358✔
2648

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

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

22,940✔
2706
    if (message.empty()) {
43,286✔
2707
        return Status::OK();
43,286✔
2708
    }
43,286✔
2709
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
2,147,483,647✔
2710
}
2,147,483,647✔
2711

2712

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

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

15,050✔
2724
    // Upload process must have reached end of history
15,050✔
2725
    REALM_ASSERT_3(m_upload_progress.client_version, <=, m_last_version_available);
30,506✔
2726
    bool scan_complete = (m_upload_progress.client_version == m_last_version_available);
30,506✔
2727
    if (!scan_complete)
30,506✔
2728
        return;
4,874✔
2729

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

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

2740

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

© 2026 Coveralls, Inc