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

realm / realm-core / github_pull_request_278228

04 Oct 2023 10:15PM UTC coverage: 91.582% (+0.007%) from 91.575%
github_pull_request_278228

Pull #7029

Evergreen

tgoyne
Use UNITTEST_LOG_LEVEL in objectstore tests

For historical reasons core and sync tests use the UNITTEST_LOG_LEVEL
environment variable to determine the test log level, while object store tests
used a build time setting. This brings them into alignment on using the env
variable, and applies it via setting the default log level on startup in a
single place.
Pull Request #7029: Use UNITTEST_LOG_LEVEL in objectstore tests

94218 of 173442 branches covered (0.0%)

46 of 54 new or added lines in 5 files covered. (85.19%)

51 existing lines in 12 files now uncovered.

230351 of 251523 relevant lines covered (91.58%)

6704577.96 hits per line

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

85.57
/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,832✔
48
    m_backoff_state.reset();
1,832✔
49
    scheduled_reset = false;
1,832✔
50
}
1,832✔
51

52

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

59

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

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

682✔
70
    switch (*m_backoff_state.triggering_error) {
1,266✔
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,170✔
76
            if (m_reconnect_mode == ReconnectMode::testing) {
1,170✔
77
                return std::chrono::milliseconds::max();
946✔
78
            }
946✔
79

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

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

137

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

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

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

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

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

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

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

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

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

232

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

252

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

1,100✔
259
        if (server_slot.connection) {
2,336✔
260
            auto& conn = server_slot.connection;
2,240✔
261
            conn->force_close();
2,240✔
262
        }
2,240✔
263
        else {
96✔
264
            for (auto& conn_pair : server_slot.alt_connections) {
48✔
265
                conn_pair.second->force_close();
×
266
            }
×
267
        }
96✔
268
    }
2,336✔
269
}
8,954✔
270

271

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

7,992✔
284
        std::lock_guard lock(m_drain_mutex);
16,312✔
285
        REALM_ASSERT(m_outstanding_posts);
16,312✔
286
        --m_outstanding_posts;
16,312✔
287
        m_drain_cv.notify_all();
16,312✔
288
    });
16,312✔
289
}
16,310✔
290

291

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

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

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

317

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

338

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

357

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

1,118✔
362
    if (m_reconnect_delay_in_progress) {
2,036✔
363
        if (m_nonzero_reconnect_delay)
1,824✔
364
            logger.detail("Canceling reconnect delay"); // Throws
916✔
365

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

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

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

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

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

1,052✔
412
    m_force_closed = true;
2,240✔
413

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

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

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

1,052✔
435
    for (auto& sess : to_close) {
1,126✔
436
        sess->force_close();
148✔
437
    }
148✔
438

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

442

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

485

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

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

38,290✔
501
    handle_message_received(data);
73,198✔
502
    return bool(m_websocket);
73,198✔
503
}
73,198✔
504

505

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

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

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

344✔
625
    return bool(m_websocket);
702✔
626
}
702✔
627

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

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

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

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

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

669

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

1,652✔
677
    REALM_ASSERT(m_reconnect_delay_in_progress);
3,346✔
678
    m_reconnect_delay_in_progress = false;
3,346✔
679

1,652✔
680
    if (m_num_active_unsuspended_sessions > 0)
3,346✔
681
        initiate_reconnect(); // Throws
3,344✔
682
}
3,346✔
683

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

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

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

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

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

280✔
709
        conn->websocket_error_handler();
574✔
710
    }
574✔
711

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

38,564✔
718
        return conn->websocket_binary_message_received(data);
73,628✔
719
    }
73,628✔
720

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

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

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

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

1,652✔
743
    // Watchdog
1,652✔
744
    initiate_connect_wait(); // Throws
3,346✔
745

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

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

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

781

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

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

798

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

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

814

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

1,596✔
820
    m_state = ConnectionState::connected;
3,230✔
821

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

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

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

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

841

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

858

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

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

1,756✔
891

1,756✔
892
    m_ping_delay_in_progress = true;
3,616✔
893

1,756✔
894
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
3,616✔
895
        if (status == ErrorCodes::OperationAborted)
3,616✔
896
            return;
3,410✔
897
        else if (!status.is_ok())
206✔
898
            throw Exception(status);
×
899

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

905

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

76✔
912
    initiate_pong_timeout(); // Throws
206✔
913

76✔
914
    if (m_state == ConnectionState::connected && !m_sending)
206✔
915
        send_next_message(); // Throws
178✔
916
}
206✔
917

918

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

76✔
925
    m_waiting_for_pong = true;
206✔
926
    m_pong_wait_started_at = monotonic_clock_now();
206✔
927

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

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

939

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

948

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

46,900✔
955
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
93,754✔
956
        if (sentinel->destroyed) {
92,292✔
957
            return;
×
958
        }
×
959
        if (status == ErrorCodes::OperationAborted)
92,292✔
960
            return;
×
961
        else if (!status.is_ok())
92,292✔
962
            throw Exception(status);
×
963

46,000✔
964
        handle_write_message(); // Throws
92,292✔
965
    });                         // Throws
92,292✔
966
    m_sending_session = sess;
93,754✔
967
    m_sending = true;
93,754✔
968
}
93,754✔
969

970

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

982

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

75,666✔
998
        Session& sess = *m_sessions_enlisted_to_send.front();
154,078✔
999
        m_sessions_enlisted_to_send.pop_front();
154,078✔
1000
        sess.send_message(); // Throws
154,078✔
1001

75,666✔
1002
        if (sess.m_state == Session::Deactivated) {
154,078✔
1003
            finish_session_deactivation(&sess);
2,218✔
1004
        }
2,218✔
1005

75,666✔
1006
        // An enlisted session may choose to not send a message. In that case,
75,666✔
1007
        // we should pass the opportunity to the next enlisted session.
75,666✔
1008
        if (m_sending)
154,078✔
1009
            break;
94,078✔
1010
    }
154,078✔
1011
}
150,378✔
1012

1013

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

70✔
1020
    m_send_ping = false;
194✔
1021
    if (m_reconnect_info.scheduled_reset)
194✔
1022
        m_ping_after_scheduled_reset_of_reconnect_info = true;
156✔
1023

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

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

1035

1036
void Connection::initiate_write_ping(const OutputBuffer& out)
1037
{
194✔
1038
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
194✔
1039
        if (sentinel->destroyed) {
194✔
1040
            return;
×
1041
        }
×
1042
        if (status == ErrorCodes::OperationAborted)
194✔
1043
            return;
×
1044
        else if (!status.is_ok())
194✔
1045
            throw Exception(status);
×
1046

70✔
1047
        handle_write_ping(); // Throws
194✔
1048
    });                      // Throws
194✔
1049
    m_sending = true;
194✔
1050
}
194✔
1051

1052

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

1061

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

1069

1070
void Connection::initiate_disconnect_wait()
1071
{
4,276✔
1072
    REALM_ASSERT(!m_reconnect_delay_in_progress);
4,276✔
1073

2,024✔
1074
    if (m_disconnect_delay_in_progress) {
4,276✔
1075
        m_reconnect_disconnect_timer.reset();
2,052✔
1076
        m_disconnect_delay_in_progress = false;
2,052✔
1077
    }
2,052✔
1078

2,024✔
1079
    milliseconds_type time = m_client.m_connection_linger_time;
4,276✔
1080

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

1090

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

6✔
1098
    m_disconnect_delay_in_progress = false;
12✔
1099

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

1109

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

1118

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

278✔
1123
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
438✔
1124
}
438✔
1125

1126

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

278✔
1133
    involuntary_disconnect(std::move(error_info), reason); // Throw
572✔
1134
}
572✔
1135

1136

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

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

1150

1151
void Connection::disconnect(const SessionErrorInfo& info)
1152
{
3,346✔
1153
    // Cancel connect timeout watchdog
1,652✔
1154
    m_connect_timer.reset();
3,346✔
1155

1,652✔
1156
    if (m_state == ConnectionState::connected) {
3,346✔
1157
        m_disconnect_time = monotonic_clock_now();
3,230✔
1158
        m_disconnect_has_occurred = true;
3,230✔
1159

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

1,652✔
1176
    change_state_to_disconnected();
3,346✔
1177

1,652✔
1178
    m_ping_delay_in_progress = false;
3,346✔
1179
    m_waiting_for_pong = false;
3,346✔
1180
    m_send_ping = false;
3,346✔
1181
    m_minimize_next_ping_delay = false;
3,346✔
1182
    m_ping_after_scheduled_reset_of_reconnect_info = false;
3,346✔
1183
    m_ping_sent = false;
3,346✔
1184
    m_heartbeat_timer.reset();
3,346✔
1185
    m_previous_ping_rtt = 0;
3,346✔
1186

1,652✔
1187
    m_websocket_sentinel->destroyed = true;
3,346✔
1188
    m_websocket_sentinel.reset();
3,346✔
1189
    m_websocket.reset();
3,346✔
1190
    m_input_body_buffer.reset();
3,346✔
1191
    m_sending_session = nullptr;
3,346✔
1192
    m_sessions_enlisted_to_send.clear();
3,346✔
1193
    m_sending = false;
3,346✔
1194

1,652✔
1195
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
3,346✔
1196
    initiate_reconnect_wait();                                           // Throws
3,346✔
1197
}
3,346✔
1198

1199
bool Connection::is_flx_sync_connection() const noexcept
1200
{
101,678✔
1201
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
101,678✔
1202
}
101,678✔
1203

1204
void Connection::receive_pong(milliseconds_type timestamp)
1205
{
188✔
1206
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
188✔
1207

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

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

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

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

66✔
1237
    m_heartbeat_timer.reset();
188✔
1238
    m_waiting_for_pong = false;
188✔
1239

66✔
1240
    initiate_ping_delay(now); // Throws
188✔
1241

66✔
1242
    if (m_client.m_roundtrip_time_handler)
188✔
1243
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
×
1244
}
188✔
1245

1246
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
1247
{
66,916✔
1248
    if (session_ident == 0) {
66,916✔
1249
        return nullptr;
×
1250
    }
×
1251

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

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

458✔
1284
        if (sess->m_state == Session::Deactivated) {
884✔
1285
            finish_session_deactivation(sess);
×
1286
        }
×
1287
        return;
884✔
1288
    }
884✔
1289

34✔
1290
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
70✔
1291
                info.message, info.raw_error_code, info.is_fatal, session_ident,
70✔
1292
                info.server_requests_action); // Throws
70✔
1293

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

1313

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

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

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

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

1337

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

1,524✔
1345
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
3,242✔
1346
        close_due_to_protocol_error(std::move(status)); // Throws
×
1347
}
3,242✔
1348

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

23,356✔
1359
    if (auto status = sess->receive_download_message(progress, downloadable_bytes, batch_state, query_version,
42,738✔
1360
                                                     received_changesets);
42,738✔
1361
        !status.is_ok()) {
42,738✔
1362
        close_due_to_protocol_error(std::move(status));
×
1363
    }
×
1364
}
42,738✔
1365

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

7,748✔
1373
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
15,900✔
1374
        close_due_to_protocol_error(std::move(status)); // Throws
×
1375
}
15,900✔
1376

1377

1378
void Connection::receive_unbound_message(session_ident_type session_ident)
1379
{
4,092✔
1380
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
4,092✔
1381
    if (REALM_UNLIKELY(!sess)) {
4,092✔
1382
        return;
×
1383
    }
×
1384

2,126✔
1385
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
4,092✔
1386
        close_due_to_protocol_error(std::move(status)); // Throws
×
1387
        return;
×
1388
    }
×
1389

2,126✔
1390
    if (sess->m_state == Session::Deactivated) {
4,092✔
1391
        finish_session_deactivation(sess);
4,092✔
1392
    }
4,092✔
1393
}
4,092✔
1394

1395

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

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

1409

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

2,950✔
1421
    if (session_ident != 0) {
6,026✔
1422
        if (auto sess = get_session(session_ident)) {
4,106✔
1423
            sess->logger.log(level, "%1 log: %2", prefix, message);
4,106✔
1424
            return;
4,106✔
1425
        }
4,106✔
1426

UNCOV
1427
        logger.log(level, "%1 log for unknown session %2: %3", prefix, session_ident, message);
×
UNCOV
1428
        return;
×
UNCOV
1429
    }
×
1430

954✔
1431
    logger.log(level, "%1 log: %2", prefix, message);
1,920✔
1432
}
1,920✔
1433

1434

1435
void Connection::receive_appservices_request_id(std::string_view coid)
1436
{
5,150✔
1437
    // Only set once per connection
2,550✔
1438
    if (!coid.empty() && m_appservices_coid.empty()) {
5,150✔
1439
        m_appservices_coid = coid;
2,240✔
1440
        logger.info("Connected to app services with request id: \"%1\"", m_appservices_coid);
2,240✔
1441
    }
2,240✔
1442
}
5,150✔
1443

1444

1445
void Connection::handle_protocol_error(Status status)
1446
{
×
1447
    close_due_to_protocol_error(std::move(status));
×
1448
}
×
1449

1450

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

1467

1468
std::string Connection::get_active_appservices_connection_id()
1469
{
72✔
1470
    return m_appservices_coid;
72✔
1471
}
72✔
1472

1473
void Session::cancel_resumption_delay()
1474
{
4,218✔
1475
    REALM_ASSERT_EX(m_state == Active, m_state);
4,218✔
1476

2,328✔
1477
    if (!m_suspended)
4,218✔
1478
        return;
3,840✔
1479

208✔
1480
    m_suspended = false;
378✔
1481

208✔
1482
    logger.debug("Resumed"); // Throws
378✔
1483

208✔
1484
    if (unbind_process_complete())
378✔
1485
        initiate_rebind(); // Throws
372✔
1486

208✔
1487
    m_conn.one_more_active_unsuspended_session(); // Throws
378✔
1488

208✔
1489
    on_resumed(); // Throws
378✔
1490
}
378✔
1491

1492

1493
void Session::gather_pending_compensating_writes(util::Span<Changeset> changesets,
1494
                                                 std::vector<ProtocolErrorInfo>* out)
1495
{
20,592✔
1496
    if (m_pending_compensating_write_errors.empty() || changesets.empty()) {
20,592✔
1497
        return;
20,552✔
1498
    }
20,552✔
1499

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

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

1520

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

11,374✔
1537
    std::vector<ProtocolErrorInfo> pending_compensating_write_errors;
20,616✔
1538
    auto transact = get_db()->start_read();
20,616✔
1539
    history.integrate_server_changesets(
20,616✔
1540
        progress, &downloadable_bytes, received_changesets, version_info, download_batch_state, logger, transact,
20,616✔
1541
        [&](const TransactionRef&, util::Span<Changeset> changesets) {
20,604✔
1542
            gather_pending_compensating_writes(changesets, &pending_compensating_write_errors);
20,592✔
1543
        },
20,592✔
1544
        get_transact_reporter()); // Throws
20,616✔
1545
    if (received_changesets.size() == 1) {
20,616✔
1546
        logger.debug("1 remote changeset integrated, producing client version %1",
14,422✔
1547
                     version_info.sync_version.version); // Throws
14,422✔
1548
    }
14,422✔
1549
    else {
6,194✔
1550
        logger.debug("%2 remote changesets integrated, producing client version %1",
6,194✔
1551
                     version_info.sync_version.version, received_changesets.size()); // Throws
6,194✔
1552
    }
6,194✔
1553

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

1571

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

16✔
1578
    m_client_error = util::make_optional<IntegrationException>(error);
32✔
1579
    m_error_to_send = true;
32✔
1580

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

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

1592
void Session::on_changesets_integrated(version_type client_version, const SyncProgress& progress)
1593
{
42,064✔
1594
    REALM_ASSERT_EX(m_state == Active, m_state);
42,064✔
1595
    REALM_ASSERT_3(progress.download.server_version, >=, m_download_progress.server_version);
42,064✔
1596
    m_download_progress = progress.download;
42,064✔
1597
    bool upload_progressed = (progress.upload.client_version > m_progress.upload.client_version);
42,064✔
1598
    m_progress = progress;
42,064✔
1599
    if (upload_progressed) {
42,064✔
1600
        if (progress.upload.client_version > m_last_version_selected_for_upload) {
31,482✔
1601
            if (progress.upload.client_version > m_upload_progress.client_version)
13,348✔
1602
                m_upload_progress = progress.upload;
938✔
1603
            m_last_version_selected_for_upload = progress.upload.client_version;
13,348✔
1604
        }
13,348✔
1605

16,752✔
1606
        check_for_upload_completion();
31,482✔
1607
    }
31,482✔
1608

22,980✔
1609
    do_recognize_sync_version(client_version); // Allows upload process to resume
42,064✔
1610
    check_for_download_completion();           // Throws
42,064✔
1611

22,980✔
1612
    // If the client migrated from PBS to FLX, create subscriptions when new tables are received from server.
22,980✔
1613
    if (auto migration_store = get_migration_store(); migration_store && m_is_flx_sync_session) {
42,064✔
1614
        auto& flx_subscription_store = *get_flx_subscription_store();
2,422✔
1615
        get_migration_store()->create_subscriptions(flx_subscription_store);
2,422✔
1616
    }
2,422✔
1617

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

1626

1627
Session::~Session()
1628
{
9,608✔
1629
    //    REALM_ASSERT_EX(m_state == Unactivated || m_state == Deactivated, m_state);
4,628✔
1630
}
9,608✔
1631

1632

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

1641

1642
void Session::activate()
1643
{
9,608✔
1644
    REALM_ASSERT_EX(m_state == Unactivated, m_state);
9,608✔
1645

4,628✔
1646
    logger.debug("Activating"); // Throws
9,608✔
1647

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

4,628✔
1660
        bool file_exists = util::File::exists(get_realm_path());
9,608✔
1661

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

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

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

4,628✔
1695
    reset_protocol_state();
9,608✔
1696
    m_state = Active;
9,608✔
1697

4,628✔
1698
    REALM_ASSERT(!m_suspended);
9,608✔
1699
    m_conn.one_more_active_unsuspended_session(); // Throws
9,608✔
1700

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

4,628✔
1711
    if (has_pending_client_reset) {
9,608✔
1712
        handle_pending_client_reset_acknowledgement();
20✔
1713
    }
20✔
1714
}
9,606✔
1715

1716

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

4,628✔
1723
    logger.debug("Initiating deactivation"); // Throws
9,608✔
1724

4,628✔
1725
    m_state = Deactivating;
9,608✔
1726

4,628✔
1727
    if (!m_suspended)
9,608✔
1728
        m_conn.one_less_active_unsuspended_session(); // Throws
9,080✔
1729

4,628✔
1730
    if (m_enlisted_to_send) {
9,608✔
1731
        REALM_ASSERT(!unbind_process_complete());
4,446✔
1732
        return;
4,446✔
1733
    }
4,446✔
1734

2,450✔
1735
    // Deactivate immediately if the BIND message has not yet been sent and the
2,450✔
1736
    // session is not enlisted to send, or if the unbinding process has already
2,450✔
1737
    // completed.
2,450✔
1738
    if (!m_bind_message_sent || unbind_process_complete()) {
5,162✔
1739
        complete_deactivation(); // Throws
1,650✔
1740
        // Life cycle state is now Deactivated
470✔
1741
        return;
1,650✔
1742
    }
1,650✔
1743

1,980✔
1744
    // Ready to send the UNBIND message, if it has not already been sent
1,980✔
1745
    if (!m_unbind_message_sent) {
3,512✔
1746
        enlist_to_send(); // Throws
3,342✔
1747
        return;
3,342✔
1748
    }
3,342✔
1749
}
3,512✔
1750

1751

1752
void Session::complete_deactivation()
1753
{
9,606✔
1754
    REALM_ASSERT_EX(m_state == Deactivating, m_state);
9,606✔
1755
    m_state = Deactivated;
9,606✔
1756

4,628✔
1757
    logger.debug("Deactivation completed"); // Throws
9,606✔
1758
}
9,606✔
1759

1760

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

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

71,370✔
1787
    // Session life cycle state is Active and the unbinding process has
71,370✔
1788
    // not been initiated
71,370✔
1789
    REALM_ASSERT(!m_unbind_message_sent);
145,812✔
1790

71,370✔
1791
    if (!m_bind_message_sent)
145,812✔
1792
        return send_bind_message(); // Throws
8,478✔
1793

66,966✔
1794
    if (!m_ident_message_sent) {
137,334✔
1795
        if (have_client_file_ident())
6,926✔
1796
            send_ident_message(); // Throws
6,926✔
1797
        return;
6,926✔
1798
    }
6,926✔
1799

63,604✔
1800
    const auto has_pending_test_command = std::any_of(m_pending_test_commands.begin(), m_pending_test_commands.end(),
130,408✔
1801
                                                      [](const PendingTestCommand& command) {
63,676✔
1802
                                                          return command.pending;
144✔
1803
                                                      });
144✔
1804
    if (has_pending_test_command) {
130,408✔
1805
        return send_test_command_message();
44✔
1806
    }
44✔
1807

63,582✔
1808
    if (m_error_to_send)
130,364✔
1809
        return send_json_error_message(); // Throws
26✔
1810

63,570✔
1811
    // Stop sending upload, mark and query messages when the client detects an error.
63,570✔
1812
    if (m_client_error) {
130,338✔
1813
        return;
16✔
1814
    }
16✔
1815

63,562✔
1816
    if (m_target_download_mark > m_last_download_mark_sent)
130,322✔
1817
        return send_mark_message(); // Throws
16,462✔
1818

55,530✔
1819
    auto is_upload_allowed = [&]() -> bool {
113,870✔
1820
        if (!m_is_flx_sync_session) {
113,870✔
1821
            return true;
104,474✔
1822
        }
104,474✔
1823

4,830✔
1824
        auto migration_store = get_migration_store();
9,396✔
1825
        if (!migration_store) {
9,396✔
1826
            return true;
×
1827
        }
×
1828

4,830✔
1829
        auto sentinel_query_version = migration_store->get_sentinel_subscription_set_version();
9,396✔
1830
        if (!sentinel_query_version) {
9,396✔
1831
            return true;
9,370✔
1832
        }
9,370✔
1833

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

55,530✔
1838
    if (!is_upload_allowed()) {
113,860✔
1839
        return;
12✔
1840
    }
12✔
1841

55,524✔
1842
    auto check_pending_flx_version = [&]() -> bool {
113,858✔
1843
        if (!m_is_flx_sync_session) {
113,858✔
1844
            return false;
104,470✔
1845
        }
104,470✔
1846

4,828✔
1847
        if (!m_allow_upload) {
9,388✔
1848
            return false;
1,584✔
1849
        }
1,584✔
1850

4,032✔
1851
        m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(
7,804✔
1852
            m_last_sent_flx_query_version, m_upload_progress.client_version);
7,804✔
1853

4,032✔
1854
        if (!m_pending_flx_sub_set) {
7,804✔
1855
            return false;
6,204✔
1856
        }
6,204✔
1857

800✔
1858
        return m_upload_progress.client_version >= m_pending_flx_sub_set->snapshot_version;
1,600✔
1859
    };
1,600✔
1860

55,524✔
1861
    if (check_pending_flx_version()) {
113,848✔
1862
        return send_query_change_message(); // throws
838✔
1863
    }
838✔
1864

55,106✔
1865
    REALM_ASSERT_3(m_upload_progress.client_version, <=, m_upload_target_version);
113,010✔
1866
    REALM_ASSERT_3(m_upload_target_version, <=, m_last_version_available);
113,010✔
1867
    if (m_allow_upload && (m_upload_target_version > m_upload_progress.client_version)) {
113,010✔
1868
        return send_upload_message(); // Throws
55,268✔
1869
    }
55,268✔
1870
}
113,010✔
1871

1872

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

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

4,404✔
1881

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

4,404✔
1914
    m_bind_message_sent = true;
8,478✔
1915

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

1922

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

3,362✔
1930

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

3,362✔
1935
    if (m_is_flx_sync_session) {
6,926✔
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,964✔
1950
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
5,964✔
1951
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
5,964✔
1952
                     "latest_server_version_salt=%6)",
5,964✔
1953
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
5,964✔
1954
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
5,964✔
1955
                     m_progress.latest_server_version.salt);                                  // Throws
5,964✔
1956
        protocol.make_pbs_ident_message(out, session_ident, m_client_file_ident, m_progress); // Throws
5,964✔
1957
    }
5,964✔
1958
    m_conn.initiate_write_message(out, this); // Throws
6,926✔
1959

3,362✔
1960
    m_ident_message_sent = true;
6,926✔
1961

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

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

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

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

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

418✔
1990
    m_last_sent_flx_query_version = latest_sub_set.version();
838✔
1991

418✔
1992
    request_download_completion_notification();
838✔
1993
}
838✔
1994

1995
void Session::send_upload_message()
1996
{
55,268✔
1997
    REALM_ASSERT_EX(m_state == Active, m_state);
55,268✔
1998
    REALM_ASSERT(m_ident_message_sent);
55,268✔
1999
    REALM_ASSERT(!m_unbind_message_sent);
55,268✔
2000
    REALM_ASSERT_3(m_upload_target_version, >, m_upload_progress.client_version);
55,268✔
2001

27,752✔
2002
    if (REALM_UNLIKELY(get_client().is_dry_run()))
55,268✔
2003
        return;
27,752✔
2004

27,752✔
2005
    auto target_upload_version = m_upload_target_version;
55,268✔
2006
    if (m_is_flx_sync_session) {
55,268✔
2007
        if (!m_pending_flx_sub_set || m_pending_flx_sub_set->snapshot_version < m_upload_progress.client_version) {
3,936✔
2008
            m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(
3,176✔
2009
                m_last_sent_flx_query_version, m_upload_progress.client_version);
3,176✔
2010
        }
3,176✔
2011
        if (m_pending_flx_sub_set && m_pending_flx_sub_set->snapshot_version < m_upload_target_version) {
3,936✔
2012
            target_upload_version = m_pending_flx_sub_set->snapshot_version;
760✔
2013
        }
760✔
2014
    }
3,936✔
2015

27,752✔
2016
    const ClientReplication& repl = access_realm(); // Throws
55,268✔
2017

27,752✔
2018
    std::vector<UploadChangeset> uploadable_changesets;
55,268✔
2019
    version_type locked_server_version = 0;
55,268✔
2020
    repl.get_history().find_uploadable_changesets(m_upload_progress, target_upload_version, uploadable_changesets,
55,268✔
2021
                                                  locked_server_version); // Throws
55,268✔
2022

27,752✔
2023
    if (uploadable_changesets.empty()) {
55,268✔
2024
        // Nothing more to upload right now
13,474✔
2025
        check_for_upload_completion(); // Throws
27,500✔
2026
        // If we need to limit upload up to some version other than the last client version available and there are no
13,474✔
2027
        // changes to upload, then there is no need to send an empty message.
13,474✔
2028
        if (target_upload_version != m_upload_target_version) {
27,500✔
2029
            logger.debug("Empty UPLOAD was skipped (progress_client_version=%1, progress_server_version=%2)",
322✔
2030
                         m_upload_progress.client_version, m_upload_progress.last_integrated_server_version);
322✔
2031
            // Other messages may be waiting to be sent
162✔
2032
            return enlist_to_send(); // Throws
322✔
2033
        }
322✔
2034
    }
27,768✔
2035
    else {
27,768✔
2036
        m_last_version_selected_for_upload = uploadable_changesets.back().progress.client_version;
27,768✔
2037
    }
27,768✔
2038

27,752✔
2039
    if (m_is_flx_sync_session && m_pending_flx_sub_set && target_upload_version != m_upload_target_version) {
55,108✔
2040
        logger.trace("Limiting UPLOAD message up to version %1 to send QUERY version %2",
438✔
2041
                     m_pending_flx_sub_set->snapshot_version, m_pending_flx_sub_set->query_version);
438✔
2042
    }
438✔
2043

27,590✔
2044
    version_type progress_client_version = m_upload_progress.client_version;
54,946✔
2045
    version_type progress_server_version = m_upload_progress.last_integrated_server_version;
54,946✔
2046

27,590✔
2047
    logger.debug("Sending: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
54,946✔
2048
                 "locked_server_version=%3, num_changesets=%4)",
54,946✔
2049
                 progress_client_version, progress_server_version, locked_server_version,
54,946✔
2050
                 uploadable_changesets.size()); // Throws
54,946✔
2051

27,590✔
2052
    ClientProtocol& protocol = m_conn.get_client_protocol();
54,946✔
2053
    ClientProtocol::UploadMessageBuilder upload_message_builder = protocol.make_upload_message_builder(); // Throws
54,946✔
2054

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

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

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

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

2102
                compact_changesets(&changeset, 1);
2103
                encode_changeset(changeset, encode_buffer);
2104

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

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

27,590✔
2123
    int protocol_version = m_conn.get_negotiated_protocol_version();
54,946✔
2124
    OutputBuffer& out = m_conn.get_output_buffer();
54,946✔
2125
    session_ident_type session_ident = get_ident();
54,946✔
2126
    upload_message_builder.make_upload_message(protocol_version, out, session_ident, progress_client_version,
54,946✔
2127
                                               progress_server_version,
54,946✔
2128
                                               locked_server_version); // Throws
54,946✔
2129
    m_conn.initiate_write_message(out, this);                          // Throws
54,946✔
2130

27,590✔
2131
    // Other messages may be waiting to be sent
27,590✔
2132
    enlist_to_send(); // Throws
54,946✔
2133
}
54,946✔
2134

2135

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

8,032✔
2143
    request_ident_type request_ident = m_target_download_mark;
16,462✔
2144
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
16,462✔
2145

8,032✔
2146
    ClientProtocol& protocol = m_conn.get_client_protocol();
16,462✔
2147
    OutputBuffer& out = m_conn.get_output_buffer();
16,462✔
2148
    session_ident_type session_ident = get_ident();
16,462✔
2149
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
16,462✔
2150
    m_conn.initiate_write_message(out, this);                      // Throws
16,462✔
2151

8,032✔
2152
    m_last_download_mark_sent = request_ident;
16,462✔
2153

8,032✔
2154
    // Other messages may be waiting to be sent
8,032✔
2155
    enlist_to_send(); // Throws
16,462✔
2156
}
16,462✔
2157

2158

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

3,062✔
2165
    logger.debug("Sending: UNBIND"); // Throws
6,038✔
2166

3,062✔
2167
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,038✔
2168
    OutputBuffer& out = m_conn.get_output_buffer();
6,038✔
2169
    session_ident_type session_ident = get_ident();
6,038✔
2170
    protocol.make_unbind_message(out, session_ident); // Throws
6,038✔
2171
    m_conn.initiate_write_message(out, this);         // Throws
6,038✔
2172

3,062✔
2173
    m_unbind_message_sent = true;
6,038✔
2174
}
6,038✔
2175

2176

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

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

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

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

12✔
2200
    m_error_to_send = false;
26✔
2201
    enlist_to_send(); // Throws
26✔
2202
}
26✔
2203

2204

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

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

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

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

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

22✔
2225
    enlist_to_send();
44✔
2226
}
44✔
2227

2228

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

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

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

1,504✔
2252
    m_client_file_ident = client_file_ident;
3,176✔
2253

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

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

1,504✔
2265
    auto client_reset_if_needed = [&]() -> bool {
3,176✔
2266
        if (!m_client_reset_operation) {
3,176✔
2267
            return false;
2,840✔
2268
        }
2,840✔
2269

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

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

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

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

168✔
2311
        get_transact_reporter()->report_sync_transact(client_reset_old_version, client_reset_new_version);
336✔
2312

168✔
2313
        if (has_pending_client_reset) {
336✔
2314
            handle_pending_client_reset_acknowledgement();
268✔
2315
        }
268✔
2316

168✔
2317
        // If a migration or rollback is in progress, mark it complete when client reset is completed.
168✔
2318
        if (auto migration_store = get_migration_store()) {
336✔
2319
            migration_store->complete_migration_or_rollback();
240✔
2320
        }
240✔
2321

168✔
2322
        return true;
336✔
2323
    };
336✔
2324
    // if a client reset happens, it will take care of setting the file ident
1,504✔
2325
    // and if not, we do it here
1,504✔
2326
    bool did_client_reset = false;
3,176✔
2327
    try {
3,176✔
2328
        did_client_reset = client_reset_if_needed();
3,176✔
2329
    }
3,176✔
2330
    catch (const std::exception& e) {
1,538✔
2331
        auto err_msg = util::format("A fatal error occurred during client reset: '%1'", e.what());
68✔
2332
        logger.error(err_msg.c_str());
68✔
2333
        SessionErrorInfo err_info(Status{ErrorCodes::AutoClientResetFailed, err_msg}, IsFatal{true});
68✔
2334
        suspend(err_info);
68✔
2335
        return Status::OK();
68✔
2336
    }
68✔
2337
    if (!did_client_reset) {
3,108✔
2338
        repl.get_history().set_client_file_ident(client_file_ident,
2,840✔
2339
                                                 m_fix_up_object_ids); // Throws
2,840✔
2340
        m_progress.download.last_integrated_client_version = 0;
2,840✔
2341
        m_progress.upload.client_version = 0;
2,840✔
2342
        m_last_version_selected_for_upload = 0;
2,840✔
2343
    }
2,840✔
2344

1,470✔
2345
    // Ready to send the IDENT message
1,470✔
2346
    ensure_enlisted_to_send(); // Throws
3,108✔
2347
    return Status::OK();       // Success
3,108✔
2348
}
3,108✔
2349

2350
Status Session::receive_download_message(const SyncProgress& progress, std::uint_fast64_t downloadable_bytes,
2351
                                         DownloadBatchState batch_state, int64_t query_version,
2352
                                         const ReceivedChangesets& received_changesets)
2353
{
42,736✔
2354
    REALM_ASSERT_EX(query_version >= 0, query_version);
42,736✔
2355
    // Ignore the message if the deactivation process has been initiated,
23,356✔
2356
    // because in that case, the associated Realm and SessionWrapper must
23,356✔
2357
    // not be accessed any longer.
23,356✔
2358
    if (m_state != Active)
42,736✔
2359
        return Status::OK();
468✔
2360

23,082✔
2361
    if (is_steady_state_download_message(batch_state, query_version)) {
42,268✔
2362
        batch_state = DownloadBatchState::SteadyState;
40,698✔
2363
    }
40,698✔
2364

23,082✔
2365
    logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
42,268✔
2366
                 "latest_server_version=%3, latest_server_version_salt=%4, "
42,268✔
2367
                 "upload_client_version=%5, upload_server_version=%6, downloadable_bytes=%7, "
42,268✔
2368
                 "last_in_batch=%8, query_version=%9, num_changesets=%10, ...)",
42,268✔
2369
                 progress.download.server_version, progress.download.last_integrated_client_version,
42,268✔
2370
                 progress.latest_server_version.version, progress.latest_server_version.salt,
42,268✔
2371
                 progress.upload.client_version, progress.upload.last_integrated_server_version, downloadable_bytes,
42,268✔
2372
                 batch_state != DownloadBatchState::MoreToCome, query_version, received_changesets.size()); // Throws
42,268✔
2373

23,082✔
2374
    // Ignore download messages when the client detects an error. This is to prevent transforming the same bad
23,082✔
2375
    // changeset over and over again.
23,082✔
2376
    if (m_client_error) {
42,268✔
2377
        logger.debug("Ignoring download message because the client detected an integration error");
×
2378
        return Status::OK();
×
2379
    }
×
2380

23,082✔
2381
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
42,270✔
2382
    if (REALM_UNLIKELY(!legal_at_this_time)) {
42,268✔
2383
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received DOWNLOAD message when it was not legal"};
×
2384
    }
×
2385
    if (auto status = check_received_sync_progress(progress); REALM_UNLIKELY(!status.is_ok())) {
42,268✔
2386
        logger.error("Bad sync progress received (%1)", status);
×
2387
        return status;
×
2388
    }
×
2389

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

23,082✔
2429
    auto hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageReceived, progress, query_version,
42,268✔
2430
                                       batch_state, received_changesets.size());
42,268✔
2431
    if (hook_action == SyncClientHookAction::EarlyReturn) {
42,268✔
2432
        return Status::OK();
12✔
2433
    }
12✔
2434
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
42,256✔
2435

23,076✔
2436
    if (process_flx_bootstrap_message(progress, batch_state, query_version, received_changesets)) {
42,256✔
2437
        clear_resumption_delay_state();
1,566✔
2438
        return Status::OK();
1,566✔
2439
    }
1,566✔
2440

22,292✔
2441
    initiate_integrate_changesets(downloadable_bytes, batch_state, progress, received_changesets); // Throws
40,690✔
2442

22,292✔
2443
    hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
40,690✔
2444
                                  batch_state, received_changesets.size());
40,690✔
2445
    if (hook_action == SyncClientHookAction::EarlyReturn) {
40,690✔
2446
        return Status::OK();
×
2447
    }
×
2448
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
40,690✔
2449

22,292✔
2450
    // When we receive a DOWNLOAD message successfully, we can clear the backoff timer value used to reconnect
22,292✔
2451
    // after a retryable session error.
22,292✔
2452
    clear_resumption_delay_state();
40,690✔
2453
    return Status::OK();
40,690✔
2454
}
40,690✔
2455

2456
Status Session::receive_mark_message(request_ident_type request_ident)
2457
{
15,900✔
2458
    logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
15,900✔
2459

7,748✔
2460
    // Ignore the message if the deactivation process has been initiated,
7,748✔
2461
    // because in that case, the associated Realm and SessionWrapper must
7,748✔
2462
    // not be accessed any longer.
7,748✔
2463
    if (m_state != Active)
15,900✔
2464
        return Status::OK(); // Success
42✔
2465

7,718✔
2466
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
15,858✔
2467
    if (REALM_UNLIKELY(!legal_at_this_time)) {
15,858✔
2468
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received MARK message when it was not legal"};
×
2469
    }
×
2470
    bool good_request_ident =
15,858✔
2471
        (request_ident <= m_last_download_mark_sent && request_ident > m_last_download_mark_received);
15,858✔
2472
    if (REALM_UNLIKELY(!good_request_ident)) {
15,858✔
2473
        return {
×
2474
            ErrorCodes::SyncProtocolInvariantFailed,
×
2475
            util::format(
×
2476
                "Received MARK message with invalid request identifer (last mark sent: %1 last mark received: %2)",
×
2477
                m_last_download_mark_sent, m_last_download_mark_received)};
×
2478
    }
×
2479

7,718✔
2480
    m_server_version_at_last_download_mark = m_progress.download.server_version;
15,858✔
2481
    m_last_download_mark_received = request_ident;
15,858✔
2482
    check_for_download_completion(); // Throws
15,858✔
2483

7,718✔
2484
    return Status::OK(); // Success
15,858✔
2485
}
15,858✔
2486

2487

2488
// The caller (Connection) must discard the session if the session has become
2489
// deactivated upon return.
2490
Status Session::receive_unbound_message()
2491
{
4,092✔
2492
    logger.debug("Received: UNBOUND");
4,092✔
2493

2,126✔
2494
    bool legal_at_this_time = (m_unbind_message_sent && !m_error_message_received && !m_unbound_message_received);
4,092✔
2495
    if (REALM_UNLIKELY(!legal_at_this_time)) {
4,092✔
2496
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received UNBOUND message when it was not legal"};
×
2497
    }
×
2498

2,126✔
2499
    // The fact that the UNBIND message has been sent, but an ERROR message has
2,126✔
2500
    // not been received, implies that the deactivation process must have been
2,126✔
2501
    // initiated, so this session must be in the Deactivating state or the session
2,126✔
2502
    // has been suspended because of a client side error.
2,126✔
2503
    REALM_ASSERT_EX(m_state == Deactivating || m_suspended, m_state);
4,092!
2504

2,126✔
2505
    m_unbound_message_received = true;
4,092✔
2506

2,126✔
2507
    // Detect completion of the unbinding process
2,126✔
2508
    if (m_unbind_message_send_complete && m_state == Deactivating) {
4,092✔
2509
        // The deactivation process completes when the unbinding process
2,126✔
2510
        // completes.
2,126✔
2511
        complete_deactivation(); // Throws
4,092✔
2512
        // Life cycle state is now Deactivated
2,126✔
2513
    }
4,092✔
2514

2,126✔
2515
    return Status::OK(); // Success
4,092✔
2516
}
4,092✔
2517

2518

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

2531
// The caller (Connection) must discard the session if the session has become
2532
// deactivated upon return.
2533
Status Session::receive_error_message(const ProtocolErrorInfo& info)
2534
{
884✔
2535
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, error_action=%4)", info.message,
884✔
2536
                info.raw_error_code, info.is_fatal, info.server_requests_action); // Throws
884✔
2537

458✔
2538
    bool legal_at_this_time = (m_bind_message_sent && !m_error_message_received && !m_unbound_message_received);
884✔
2539
    if (REALM_UNLIKELY(!legal_at_this_time)) {
884✔
2540
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received ERROR message when it was not legal"};
×
2541
    }
×
2542

458✔
2543
    auto protocol_error = static_cast<ProtocolError>(info.raw_error_code);
884✔
2544
    auto status = protocol_error_to_status(protocol_error, info.message);
884✔
2545
    if (status != ErrorCodes::UnknownError && REALM_UNLIKELY(!is_session_level_error(protocol_error))) {
884✔
2546
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
2547
                util::format("Received ERROR message for session with non-session-level error code %1",
×
2548
                             info.raw_error_code)};
×
2549
    }
×
2550

458✔
2551
    // Can't process debug hook actions once the Session is undergoing deactivation, since
458✔
2552
    // the SessionWrapper may not be available
458✔
2553
    if (m_state == Active) {
884✔
2554
        auto debug_action = call_debug_hook(SyncClientHookEvent::ErrorMessageReceived, info);
882✔
2555
        if (debug_action == SyncClientHookAction::EarlyReturn) {
882✔
2556
            return Status::OK();
8✔
2557
        }
8✔
2558
    }
876✔
2559

454✔
2560
    // For compensating write errors, we need to defer raising them to the SDK until after the server version
454✔
2561
    // containing the compensating write has appeared in a download message.
454✔
2562
    if (status == ErrorCodes::SyncCompensatingWrite) {
876✔
2563
        // If the client is not active, the compensating writes will not be processed now, but will be
20✔
2564
        // sent again the next time the client connects
20✔
2565
        if (m_state == Active) {
40✔
2566
            REALM_ASSERT(info.compensating_write_server_version.has_value());
40✔
2567
            m_pending_compensating_write_errors.push_back(info);
40✔
2568
        }
40✔
2569
        return Status::OK();
40✔
2570
    }
40✔
2571

434✔
2572
    m_error_message_received = true;
836✔
2573
    suspend(SessionErrorInfo{info, std::move(status)});
836✔
2574
    return Status::OK();
836✔
2575
}
836✔
2576

2577
void Session::suspend(const SessionErrorInfo& info)
2578
{
904✔
2579
    REALM_ASSERT(!m_suspended);
904✔
2580
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
904!
2581
    logger.debug("Suspended"); // Throws
904✔
2582

468✔
2583
    m_suspended = true;
904✔
2584

468✔
2585
    // Detect completion of the unbinding process
468✔
2586
    if (m_unbind_message_send_complete && m_error_message_received) {
904!
2587
        // The fact that the UNBIND message has been sent, but we are not being suspended because
2588
        // we received an ERROR message implies that the deactivation process must
2589
        // have been initiated, so this session must be in the Deactivating state.
2590
        REALM_ASSERT_EX(m_state == Deactivating, m_state);
×
2591

2592
        // The deactivation process completes when the unbinding process
2593
        // completes.
2594
        complete_deactivation(); // Throws
×
2595
        // Life cycle state is now Deactivated
2596
    }
×
2597

468✔
2598
    // Notify the application of the suspension of the session if the session is
468✔
2599
    // still in the Active state
468✔
2600
    if (m_state == Active) {
904✔
2601
        m_conn.one_less_active_unsuspended_session(); // Throws
902✔
2602
        on_suspended(info);                           // Throws
902✔
2603
    }
902✔
2604

468✔
2605
    if (!info.is_fatal) {
904✔
2606
        begin_resumption_delay(info);
374✔
2607
    }
374✔
2608

468✔
2609
    // Ready to send the UNBIND message, if it has not been sent already
468✔
2610
    if (!m_unbind_message_sent)
904✔
2611
        ensure_enlisted_to_send(); // Throws
902✔
2612
}
904✔
2613

2614
Status Session::receive_test_command_response(request_ident_type ident, std::string_view body)
2615
{
44✔
2616
    logger.info("Received: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", body, m_ident, ident);
44✔
2617
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
44✔
2618
                           [&](const PendingTestCommand& command) {
44✔
2619
                               return command.id == ident;
44✔
2620
                           });
44✔
2621
    if (it == m_pending_test_commands.end()) {
44✔
2622
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
2623
                util::format("Received test command response for a non-existent ident %1", ident)};
×
2624
    }
×
2625

22✔
2626
    it->promise.emplace_value(std::string{body});
44✔
2627
    m_pending_test_commands.erase(it);
44✔
2628

22✔
2629
    return Status::OK();
44✔
2630
}
44✔
2631

2632
void Session::begin_resumption_delay(const ProtocolErrorInfo& error_info)
2633
{
374✔
2634
    REALM_ASSERT(!m_try_again_activation_timer);
374✔
2635

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

204✔
2652
        m_try_again_activation_timer.reset();
370✔
2653
        cancel_resumption_delay();
370✔
2654
    });
370✔
2655
}
374✔
2656

2657
void Session::clear_resumption_delay_state()
2658
{
42,260✔
2659
    if (m_try_again_activation_timer) {
42,260✔
2660
        logger.debug("Clearing resumption delay state after successful download");
×
2661
        m_try_again_delay_info.reset();
×
2662
    }
×
2663
}
42,260✔
2664

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

23,080✔
2714
    if (message.empty()) {
42,270✔
2715
        return Status::OK();
42,270✔
2716
    }
42,270✔
2717
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
2,147,483,647✔
2718
}
2,147,483,647✔
2719

2720

2721
void Session::check_for_upload_completion()
2722
{
74,192✔
2723
    REALM_ASSERT_EX(m_state == Active, m_state);
74,192✔
2724
    if (!m_upload_completion_notification_requested) {
74,192✔
2725
        return;
43,278✔
2726
    }
43,278✔
2727

15,104✔
2728
    // during an ongoing client reset operation, we never upload anything
15,104✔
2729
    if (m_client_reset_operation)
30,914✔
2730
        return;
232✔
2731

14,988✔
2732
    // Upload process must have reached end of history
14,988✔
2733
    REALM_ASSERT_3(m_upload_progress.client_version, <=, m_last_version_available);
30,682✔
2734
    bool scan_complete = (m_upload_progress.client_version == m_last_version_available);
30,682✔
2735
    if (!scan_complete)
30,682✔
2736
        return;
5,054✔
2737

12,516✔
2738
    // All uploaded changesets must have been acknowledged by the server
12,516✔
2739
    REALM_ASSERT_3(m_progress.upload.client_version, <=, m_last_version_selected_for_upload);
25,628✔
2740
    bool all_uploads_accepted = (m_progress.upload.client_version == m_last_version_selected_for_upload);
25,628✔
2741
    if (!all_uploads_accepted)
25,628✔
2742
        return;
11,000✔
2743

7,232✔
2744
    m_upload_completion_notification_requested = false;
14,628✔
2745
    on_upload_completion(); // Throws
14,628✔
2746
}
14,628✔
2747

2748

2749
void Session::check_for_download_completion()
2750
{
57,922✔
2751
    REALM_ASSERT_3(m_target_download_mark, >=, m_last_download_mark_received);
57,922✔
2752
    REALM_ASSERT_3(m_last_download_mark_received, >=, m_last_triggering_download_mark);
57,922✔
2753
    if (m_last_download_mark_received == m_last_triggering_download_mark)
57,922✔
2754
        return;
41,860✔
2755
    if (m_last_download_mark_received < m_target_download_mark)
16,062✔
2756
        return;
442✔
2757
    if (m_download_progress.server_version < m_server_version_at_last_download_mark)
15,620✔
2758
        return;
×
2759
    m_last_triggering_download_mark = m_target_download_mark;
15,620✔
2760
    if (REALM_UNLIKELY(!m_allow_upload)) {
15,620✔
2761
        // Activate the upload process now, and enable immediate reactivation
1,990✔
2762
        // after a subsequent fast reconnect.
1,990✔
2763
        m_allow_upload = true;
4,396✔
2764
        ensure_enlisted_to_send(); // Throws
4,396✔
2765
    }
4,396✔
2766
    on_download_completion(); // Throws
15,620✔
2767
}
15,620✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc