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

realm / realm-core / jonathan.reams_3237

21 May 2024 01:18PM UTC coverage: 90.836% (+0.01%) from 90.823%
jonathan.reams_3237

push

Evergreen

web-flow
Upload also the realm file when the fuzzer fails (#7700)

* upload realm file if fuzzer reports a crash

* better comment and delete realm file once fuzzer has finished

* fix upload file name

101830 of 180184 branches covered (56.51%)

214950 of 236635 relevant lines covered (90.84%)

5628660.52 hits per line

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

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

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

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

26
#include <system_error>
27
#include <sstream>
28

29
// NOTE: The protocol specification is in `/doc/protocol.md`
30

31
using namespace realm;
32
using namespace _impl;
33
using namespace realm::util;
34
using namespace realm::sync;
35
using namespace realm::sync::websocket;
36

37
// clang-format off
38
using Connection      = ClientImpl::Connection;
39
using Session         = ClientImpl::Session;
40
using UploadChangeset = ClientHistory::UploadChangeset;
41

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

49
void ClientImpl::ReconnectInfo::reset() noexcept
50
{
1,944✔
51
    m_backoff_state.reset();
1,944✔
52
    scheduled_reset = false;
1,944✔
53
}
1,944✔
54

55

56
void ClientImpl::ReconnectInfo::update(ConnectionTerminationReason new_reason,
57
                                       std::optional<ResumptionDelayInfo> new_delay_info)
58
{
3,752✔
59
    m_backoff_state.update(new_reason, new_delay_info);
3,752✔
60
}
3,752✔
61

62

63
std::chrono::milliseconds ClientImpl::ReconnectInfo::delay_interval()
64
{
6,048✔
65
    if (scheduled_reset) {
6,048✔
66
        reset();
4✔
67
    }
4✔
68

69
    if (!m_backoff_state.triggering_error) {
6,048✔
70
        return std::chrono::milliseconds::zero();
4,630✔
71
    }
4,630✔
72

73
    switch (*m_backoff_state.triggering_error) {
1,418✔
74
        case ConnectionTerminationReason::closed_voluntarily:
80✔
75
            return std::chrono::milliseconds::zero();
80✔
76
        case ConnectionTerminationReason::server_said_do_not_reconnect:
18✔
77
            return std::chrono::milliseconds::max();
18✔
78
        default:
1,320✔
79
            if (m_reconnect_mode == ReconnectMode::testing) {
1,320✔
80
                return std::chrono::milliseconds::max();
998✔
81
            }
998✔
82

83
            REALM_ASSERT(m_reconnect_mode == ReconnectMode::normal);
322✔
84
            return m_backoff_state.delay_interval();
322✔
85
    }
1,418✔
86
}
1,418✔
87

88

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

133
    protocol = protocol_2;
4,014✔
134
    address = std::move(address_2);
4,014✔
135
    port = port_3;
4,014✔
136
    path = std::move(path_2);
4,014✔
137
    return true;
4,014✔
138
}
4,014✔
139

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

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

197
    if (config.reconnect_mode != ReconnectMode::normal) {
9,926✔
198
        logger.warn("Testing/debugging feature 'nonnormal reconnect mode' enabled - "
780✔
199
                    "never do this in production!");
780✔
200
    }
780✔
201

202
    if (config.dry_run) {
9,926✔
203
        logger.warn("Testing/debugging feature 'dry run' enabled - "
×
204
                    "never do this in production!");
×
205
    }
×
206

207
    REALM_ASSERT_EX(m_socket_provider, "Must provide socket provider in sync Client config");
9,926✔
208

209
    if (m_one_connection_per_session) {
9,926✔
210
        logger.warn("Testing/debugging feature 'one connection per session' enabled - "
4✔
211
                    "never do this in production");
4✔
212
    }
4✔
213

214
    if (config.disable_upload_activation_delay) {
9,926✔
215
        logger.warn("Testing/debugging feature 'disable_upload_activation_delay' enabled - "
×
216
                    "never do this in production");
×
217
    }
×
218

219
    if (config.disable_sync_to_disk) {
9,926✔
220
        logger.warn("Testing/debugging feature 'disable_sync_to_disk' enabled - "
×
221
                    "never do this in production");
×
222
    }
×
223

224
    m_actualize_and_finalize = create_trigger([this](Status status) {
15,200✔
225
        if (status == ErrorCodes::OperationAborted)
15,200✔
226
            return;
×
227
        else if (!status.is_ok())
15,200✔
228
            throw Exception(status);
×
229
        actualize_and_finalize_session_wrappers(); // Throws
15,200✔
230
    });
15,200✔
231
}
9,926✔
232

233

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

253

254
void ClientImpl::drain_connections()
255
{
9,914✔
256
    logger.debug("Draining connections during sync client shutdown");
9,914✔
257
    for (auto& server_slot_pair : m_server_slots) {
9,914✔
258
        auto& server_slot = server_slot_pair.second;
2,664✔
259

260
        if (server_slot.connection) {
2,664✔
261
            auto& conn = server_slot.connection;
2,444✔
262
            conn->force_close();
2,444✔
263
        }
2,444✔
264
        else {
220✔
265
            for (auto& conn_pair : server_slot.alt_connections) {
220✔
266
                conn_pair.second->force_close();
×
267
            }
×
268
        }
220✔
269
    }
2,664✔
270
}
9,914✔
271

272

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

285
        std::lock_guard lock(m_drain_mutex);
17,322✔
286
        REALM_ASSERT(m_outstanding_posts);
17,322✔
287
        --m_outstanding_posts;
17,322✔
288
        m_drain_cv.notify_all();
17,322✔
289
    });
17,322✔
290
}
17,334✔
291

292

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

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

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

10,286✔
318

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

10,274✔
339

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

2,156✔
358

1,936✔
359
void Connection::cancel_reconnect_delay()
964✔
360
{
361
    REALM_ASSERT(m_activated);
362

363
    if (m_reconnect_delay_in_progress) {
364
        if (m_nonzero_reconnect_delay)
365
            logger.detail("Canceling reconnect delay"); // Throws
366

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

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

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

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

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

413
    m_force_closed = true;
2,444✔
414

2,444✔
415
    if (m_state != ConnectionState::disconnected) {
36✔
416
        voluntary_disconnect();
36✔
417
    }
36✔
418

36✔
419
    REALM_ASSERT_EX(m_state == ConnectionState::disconnected, m_state);
420
    if (m_reconnect_delay_in_progress || m_disconnect_delay_in_progress) {
421
        m_reconnect_disconnect_timer.reset();
422
        m_reconnect_delay_in_progress = false;
423
        m_disconnect_delay_in_progress = false;
2,444✔
424
    }
2,444✔
425

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

2,444✔
436
    for (auto& sess : to_close) {
437
        sess->force_close();
438
    }
439

3,546✔
440
    logger.debug("Force closed idle connection");
3,546✔
441
}
3,546✔
442

3,546✔
443

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

×
486

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

430✔
494
    using sf = SimulatedFailure;
430✔
495
    if (sf::check_trigger(sf::sync_client__read_head)) {
496
        close_due_to_client_side_error(
79,482✔
497
            {ErrorCodes::RuntimeError, "Simulated failure during sync client websocket read"}, IsFatal{false},
79,482✔
498
            ConnectionTerminationReason::read_or_write_error);
79,912✔
499
        return bool(m_websocket);
500
    }
501

502
    handle_message_received(data);
672✔
503
    return bool(m_websocket);
672✔
504
}
672✔
505

506

507
void Connection::websocket_error_handler()
776✔
508
{
776✔
509
    m_websocket_error_received = true;
×
510
}
×
511

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

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

642
    return bool(m_websocket);
643
}
8,456✔
644

8,456✔
645
// Guarantees that handle_reconnect_wait() is never called from within the
8,456✔
646
// execution of initiate_reconnect_wait() (no callback reentrance).
8,456✔
647
void Connection::initiate_reconnect_wait()
648
{
649
    REALM_ASSERT(m_activated);
8,456✔
650
    REALM_ASSERT(!m_reconnect_delay_in_progress);
2,408✔
651
    REALM_ASSERT(!m_disconnect_delay_in_progress);
2,408✔
652

653
    // If we've been force closed then we don't need/want to reconnect. Just return early here.
6,048✔
654
    if (m_force_closed) {
6,048✔
655
        return;
6,048✔
656
    }
1,016✔
657

658
    m_reconnect_delay_in_progress = true;
1,016✔
659
    auto delay = m_reconnect_info.delay_interval();
1,016✔
660
    if (delay == std::chrono::milliseconds::max()) {
1,016✔
661
        logger.detail("Reconnection delayed indefinitely"); // Throws
662
        // Not actually starting a timer corresponds to an infinite wait
5,032✔
663
        m_nonzero_reconnect_delay = true;
4,710✔
664
        return;
4,710✔
665
    }
322✔
666

322✔
667
    if (delay == std::chrono::milliseconds::zero()) {
322✔
668
        m_nonzero_reconnect_delay = false;
322✔
669
    }
670
    else {
671
        logger.detail("Allowing reconnection in %1 milliseconds", delay.count()); // Throws
672
        m_nonzero_reconnect_delay = true;
673
    }
5,034✔
674

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

×
686

×
687
void Connection::handle_reconnect_wait(Status status)
×
688
{
689
    if (!status.is_ok()) {
3,752✔
690
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
3,752✔
691
        throw Exception(status);
692
    }
3,752✔
693

3,746✔
694
    REALM_ASSERT(m_reconnect_delay_in_progress);
3,752✔
695
    m_reconnect_delay_in_progress = false;
696

697
    if (m_num_active_unsuspended_sessions > 0)
698
        initiate_reconnect(); // Throws
1,760✔
699
}
3,750✔
700

3,750✔
701
struct Connection::WebSocketObserverShim : public sync::WebSocketObserver {
702
    explicit WebSocketObserverShim(Connection* conn)
703
        : conn(conn)
704
        , sentinel(conn->m_websocket_sentinel)
705
    {
3,546✔
706
    }
3,546✔
707

3,546✔
708
    Connection* conn;
709
    util::bind_ptr<LifecycleSentinel> sentinel;
710

672✔
711
    void websocket_connected_handler(const std::string& protocol) override
672✔
712
    {
672✔
713
        if (sentinel->destroyed) {
714
            return;
715
        }
79,912✔
716

79,912✔
717
        return conn->websocket_connected_handler(protocol);
79,912✔
718
    }
719

720
    void websocket_error_handler() override
776✔
721
    {
776✔
722
        if (sentinel->destroyed) {
776✔
723
            return;
724
        }
725

726
        conn->websocket_error_handler();
3,750✔
727
    }
3,750✔
728

729
    bool websocket_binary_message_received(util::Span<const char> data) override
3,750✔
730
    {
3,750✔
731
        if (sentinel->destroyed) {
3,750✔
732
            return false;
733
        }
734

3,750✔
735
        return conn->websocket_binary_message_received(data);
736
    }
3,750✔
737

3,750✔
738
    bool websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg) override
3,750✔
739
    {
3,750✔
740
        if (sentinel->destroyed) {
3,750✔
741
            return true;
3,750✔
742
        }
3,750✔
743

744
        return conn->websocket_closed_handler(was_clean, error_code, msg);
745
    }
48,756✔
746
};
45,006✔
747

45,006✔
748
void Connection::initiate_reconnect()
3,750✔
749
{
750
    REALM_ASSERT(m_activated);
3,750✔
751

3,750✔
752
    m_state = ConnectionState::connecting;
753
    report_connection_state_change(ConnectionState::connecting); // Throws
3,750✔
754
    if (m_websocket_sentinel) {
3,750✔
755
        m_websocket_sentinel->destroyed = true;
3,750✔
756
    }
3,750✔
757
    m_websocket_sentinel = util::make_bind<LifecycleSentinel>();
3,750✔
758
    m_websocket.reset();
3,750✔
759

3,750✔
760
    // Watchdog
3,750✔
761
    initiate_connect_wait(); // Throws
3,750✔
762

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

777
    logger.info("Connecting to '%1%2:%3%4'", to_string(m_server_endpoint.envelope), m_server_endpoint.address,
778
                m_server_endpoint.port, m_http_request_path_prefix);
3,750✔
779

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

×
798

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

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

3,546✔
815

3,546✔
816
void Connection::handle_connect_wait(Status status)
817
{
3,546✔
818
    if (!status.is_ok()) {
3,546✔
819
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
3,546✔
820
        throw Exception(status);
821
    }
3,546✔
822

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

3,546✔
835

836
void Connection::handle_connection_established()
837
{
838
    // Cancel connect timeout watchdog
220✔
839
    m_connect_timer.reset();
220✔
840

220✔
841
    m_state = ConnectionState::connected;
106✔
842
    m_server_endpoint.is_verified = true; // sync route is valid since connection is successful
106✔
843

106✔
844
    milliseconds_type now = monotonic_clock_now();
106✔
845
    m_pong_wait_started_at = now; // Initially, no time was spent waiting for a PONG message
106✔
846
    initiate_ping_delay(now);     // Throws
106✔
847

106✔
848
    bool fast_reconnect = false;
114✔
849
    if (m_disconnect_has_occurred) {
114✔
850
        milliseconds_type time = now - m_disconnect_time;
114✔
851
        if (time <= m_client.m_fast_reconnect_limit)
114✔
852
            fast_reconnect = true;
853
    }
854

855
    for (auto& p : m_sessions) {
3,778✔
856
        Session& sess = *p.second;
3,778✔
857
        sess.connection_established(fast_reconnect); // Throws
3,778✔
858
    }
3,778✔
859

860
    report_connection_state_change(ConnectionState::connected); // Throws
3,778✔
861
}
3,778✔
862

3,662✔
863

864
void Connection::schedule_urgent_ping()
865
{
866
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
867
    if (m_ping_delay_in_progress) {
868
        m_heartbeat_timer.reset();
3,662✔
869
        m_ping_delay_in_progress = false;
3,662✔
870
        m_minimize_next_ping_delay = true;
3,662✔
871
        milliseconds_type now = monotonic_clock_now();
3,662✔
872
        initiate_ping_delay(now); // Throws
873
        return;
3,662✔
874
    }
3,662✔
875
    REALM_ASSERT_EX(m_state == ConnectionState::connecting || m_waiting_for_pong, m_state);
3,662✔
876
    if (!m_send_ping)
3,654✔
877
        m_minimize_next_ping_delay = true;
3,654✔
878
}
8✔
879

8✔
880

8✔
881
void Connection::initiate_ping_delay(milliseconds_type now)
3,662✔
882
{
116✔
883
    REALM_ASSERT(!m_ping_delay_in_progress);
116✔
884
    REALM_ASSERT(!m_waiting_for_pong);
116✔
885
    REALM_ASSERT(!m_send_ping);
886

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

913

914
    m_ping_delay_in_progress = true;
915

140✔
916
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
140✔
917
        if (status == ErrorCodes::OperationAborted)
140✔
918
            return;
140✔
919
        else if (!status.is_ok())
920
            throw Exception(status);
140✔
921

140✔
922
        handle_ping_delay();                                    // Throws
923
    });                                                         // Throws
140✔
924
    logger.debug("Will emit a ping in %1 milliseconds", delay); // Throws
140✔
925
}
140✔
926

128✔
927

12✔
928
void Connection::handle_ping_delay()
×
929
{
930
    REALM_ASSERT(m_ping_delay_in_progress);
12✔
931
    m_ping_delay_in_progress = false;
12✔
932
    m_send_ping = true;
140✔
933

934
    initiate_pong_timeout(); // Throws
935

936
    if (m_state == ConnectionState::connected && !m_sending)
12✔
937
        send_next_message(); // Throws
12✔
938
}
12✔
939

12✔
940

12✔
941
void Connection::initiate_pong_timeout()
12✔
942
{
943
    REALM_ASSERT(!m_ping_delay_in_progress);
944
    REALM_ASSERT(!m_waiting_for_pong);
945
    REALM_ASSERT(m_send_ping);
100,520✔
946

947
    m_waiting_for_pong = true;
100,520✔
948
    m_pong_wait_started_at = monotonic_clock_now();
×
949

950
    milliseconds_type time = m_client.m_pong_keepalive_timeout;
100,520✔
951
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
98,978✔
952
        if (status == ErrorCodes::OperationAborted)
×
953
            return;
954
        else if (!status.is_ok())
×
955
            throw Exception(status);
×
956

×
957
        handle_pong_timeout(); // Throws
×
958
    });                        // Throws
98,978✔
959
}
98,978✔
960

100,520✔
961

100,520✔
962
void Connection::handle_pong_timeout()
100,520✔
963
{
964
    REALM_ASSERT(m_waiting_for_pong);
965
    logger.debug("Timeout on reception of PONG message"); // Throws
966
    close_due_to_transient_error({ErrorCodes::ConnectionClosed, "Timed out waiting for PONG response from server"},
98,984✔
967
                                 ConnectionTerminationReason::pong_timeout);
98,984✔
968
}
98,984✔
969

128✔
970

128✔
971
void Connection::initiate_write_message(const OutputBuffer& out, Session* sess)
98,984✔
972
{
98,984✔
973
    // Stop sending messages if an websocket error was received.
98,984✔
974
    if (m_websocket_error_received)
98,984✔
975
        return;
976

977
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
978
        if (sentinel->destroyed) {
160,514✔
979
            return;
160,514✔
980
        }
160,514✔
981
        if (!status.is_ok()) {
160,514✔
982
            if (status != ErrorCodes::Error::OperationAborted) {
160,514✔
983
                // Write errors will be handled by the websocket_write_error_handler() callback
128✔
984
                logger.error("Connection: write failed %1: %2", status.code_string(), status.reason());
128✔
985
            }
128✔
986
            return;
224,730✔
987
        }
988
        handle_write_message(); // Throws
989
    });                         // Throws
990
    m_sending_session = sess;
165,134✔
991
    m_sending = true;
992
}
165,134✔
993

165,134✔
994

165,134✔
995
void Connection::handle_write_message()
996
{
165,134✔
997
    m_sending_session->message_sent(); // Throws
2,824✔
998
    if (m_sending_session->m_state == Session::Deactivated) {
2,824✔
999
        finish_session_deactivation(m_sending_session);
1000
    }
1001
    m_sending_session = nullptr;
1002
    m_sending = false;
165,134✔
1003
    send_next_message(); // Throws
100,790✔
1004
}
165,134✔
1005

160,386✔
1006

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

1022
        Session& sess = *m_sessions_enlisted_to_send.front();
128✔
1023
        m_sessions_enlisted_to_send.pop_front();
128✔
1024
        sess.send_message(); // Throws
128✔
1025

128✔
1026
        if (sess.m_state == Session::Deactivated) {
128✔
1027
            finish_session_deactivation(&sess);
128✔
1028
        }
1029

1030
        // An enlisted session may choose to not send a message. In that case,
1031
        // we should pass the opportunity to the next enlisted session.
128✔
1032
        if (m_sending)
128✔
1033
            break;
128✔
1034
    }
×
1035
}
1036

×
1037

×
1038
void Connection::send_ping()
×
1039
{
×
1040
    REALM_ASSERT(!m_ping_delay_in_progress);
128✔
1041
    REALM_ASSERT(m_waiting_for_pong);
128✔
1042
    REALM_ASSERT(m_send_ping);
128✔
1043

128✔
1044
    m_send_ping = false;
1045
    if (m_reconnect_info.scheduled_reset)
1046
        m_ping_after_scheduled_reset_of_reconnect_info = true;
1047

128✔
1048
    m_last_ping_sent_at = monotonic_clock_now();
128✔
1049
    logger.debug("Sending: PING(timestamp=%1, rtt=%2)", m_last_ping_sent_at,
128✔
1050
                 m_previous_ping_rtt); // Throws
128✔
1051

128✔
1052
    ClientProtocol& protocol = get_client_protocol();
128✔
1053
    OutputBuffer& out = get_output_buffer();
1054
    protocol.make_ping(out, m_last_ping_sent_at, m_previous_ping_rtt); // Throws
1055
    initiate_write_ping(out);                                          // Throws
1056
    m_ping_sent = true;
79,482✔
1057
}
1058

1059

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

4,574✔
1078

12✔
1079
void Connection::handle_write_ping()
4,574✔
1080
{
4,574✔
1081
    REALM_ASSERT(m_sending);
4,574✔
1082
    REALM_ASSERT(!m_sending_session);
1083
    m_sending = false;
1084
    send_next_message(); // Throws
1085
}
12✔
1086

12✔
1087

×
1088
void Connection::handle_message_received(util::Span<const char> data)
×
1089
{
×
1090
    // parse_message_received() parses the message and calls the proper handler
1091
    // on the Connection object (this).
12✔
1092
    get_client_protocol().parse_message_received<Connection>(*this, std::string_view(data.data(), data.size()));
1093
}
12✔
1094

12✔
1095

12✔
1096
void Connection::initiate_disconnect_wait()
×
1097
{
12✔
1098
    REALM_ASSERT(!m_reconnect_delay_in_progress);
12✔
1099

12✔
1100
    if (m_disconnect_delay_in_progress) {
12✔
1101
        m_reconnect_disconnect_timer.reset();
1102
        m_disconnect_delay_in_progress = false;
1103
    }
1104

16✔
1105
    milliseconds_type time = m_client.m_connection_linger_time;
16✔
1106

16✔
1107
    m_reconnect_disconnect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
16✔
1108
        // If the operation is aborted, the connection object may have been
16✔
1109
        // destroyed.
16✔
1110
        if (status != ErrorCodes::OperationAborted)
1111
            handle_disconnect_wait(status); // Throws
1112
    });                                     // Throws
1113
    m_disconnect_delay_in_progress = true;
440✔
1114
}
440✔
1115

1116

440✔
1117
void Connection::handle_disconnect_wait(Status status)
440✔
1118
{
1119
    if (!status.is_ok()) {
1120
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
1121
        throw Exception(status);
606✔
1122
    }
606✔
1123

606✔
1124
    m_disconnect_delay_in_progress = false;
606✔
1125

1126
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
606✔
1127
    if (m_num_active_unsuspended_sessions == 0) {
606✔
1128
        if (m_client.m_connection_linger_time > 0)
1129
            logger.detail("Linger time expired"); // Throws
1130
        voluntary_disconnect();                   // Throws
1131
        logger.info("Disconnected");              // Throws
1132
    }
1133
}
62✔
1134

62✔
1135

62✔
1136
void Connection::close_due_to_protocol_error(Status status)
1137
{
62✔
1138
    SessionErrorInfo error_info(std::move(status), IsFatal{true});
62✔
1139
    error_info.server_requests_action = ProtocolErrorInfo::Action::ProtocolViolation;
62✔
1140
    involuntary_disconnect(std::move(error_info),
62✔
1141
                           ConnectionTerminationReason::sync_protocol_violation); // Throws
62✔
1142
}
1143

1144

1145
void Connection::close_due_to_client_side_error(Status status, IsFatal is_fatal, ConnectionTerminationReason reason)
3,752✔
1146
{
1147
    logger.info("Connection closed due to error: %1", status); // Throws
3,752✔
1148

1149
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
3,752✔
1150
}
3,546✔
1151

3,546✔
1152

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

3,546✔
1159
    involuntary_disconnect(std::move(error_info), reason); // Throw
7,644✔
1160
}
1161

4,098✔
1162

4,098✔
1163
// Close connection due to error discovered on the server-side, and then
4,098✔
1164
// reported to the client by way of a connection-level ERROR message.
4,098✔
1165
void Connection::close_due_to_server_side_error(ProtocolError error_code, const ProtocolErrorInfo& info)
1,932✔
1166
{
4,098✔
1167
    logger.info("Connection closed due to error reported by server: %1 (%2)", info.message,
3,546✔
1168
                int(error_code)); // Throws
1169

3,752✔
1170
    const auto reason = info.is_fatal ? ConnectionTerminationReason::server_said_do_not_reconnect
1171
                                      : ConnectionTerminationReason::server_said_try_again_later;
3,752✔
1172
    involuntary_disconnect(SessionErrorInfo{info, protocol_error_to_status(error_code, info.message)},
3,752✔
1173
                           reason); // Throws
3,752✔
1174
}
3,752✔
1175

3,752✔
1176

3,752✔
1177
void Connection::disconnect(const SessionErrorInfo& info)
3,752✔
1178
{
3,752✔
1179
    // Cancel connect timeout watchdog
1180
    m_connect_timer.reset();
3,752✔
1181

3,752✔
1182
    if (m_state == ConnectionState::connected) {
3,752✔
1183
        m_disconnect_time = monotonic_clock_now();
3,752✔
1184
        m_disconnect_has_occurred = true;
3,752✔
1185

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

×
1202
    change_state_to_disconnected();
×
1203

×
1204
    m_ping_delay_in_progress = false;
×
1205
    m_waiting_for_pong = false;
1206
    m_send_ping = false;
126✔
1207
    m_minimize_next_ping_delay = false;
×
1208
    m_ping_after_scheduled_reset_of_reconnect_info = false;
×
1209
    m_ping_sent = false;
×
1210
    m_heartbeat_timer.reset();
×
1211
    m_previous_ping_rtt = 0;
×
1212

×
1213
    m_websocket_sentinel->destroyed = true;
1214
    m_websocket_sentinel.reset();
126✔
1215
    m_websocket.reset();
126✔
1216
    m_input_body_buffer.reset();
126✔
1217
    m_sending_session = nullptr;
126✔
1218
    m_sessions_enlisted_to_send.clear();
1219
    m_sending = false;
1220

1221
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
1222
    initiate_reconnect_wait();                                           // Throws
126✔
1223
}
92✔
1224

92✔
1225
bool Connection::is_flx_sync_connection() const noexcept
92✔
1226
{
92✔
1227
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
1228
}
126✔
1229

126✔
1230
void Connection::receive_pong(milliseconds_type timestamp)
1231
{
126✔
1232
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
1233

126✔
1234
    bool legal_at_this_time = (m_waiting_for_pong && !m_send_ping);
×
1235
    if (REALM_UNLIKELY(!legal_at_this_time)) {
126✔
1236
        close_due_to_protocol_error(
1237
            {ErrorCodes::SyncProtocolInvariantFailed, "Received PONG message when it was not valid"}); // Throws
1238
        return;
73,292✔
1239
    }
73,292✔
1240

×
1241
    if (REALM_UNLIKELY(timestamp != m_last_ping_sent_at)) {
×
1242
        close_due_to_protocol_error(
1243
            {ErrorCodes::SyncProtocolInvariantFailed,
73,292✔
1244
             util::format("Received PONG message with an invalid timestamp (expected %1, received %2)",
73,294✔
1245
                          m_last_ping_sent_at, timestamp)}); // Throws
73,294✔
1246
        return;
73,294✔
1247
    }
1248

2,147,483,647✔
1249
    milliseconds_type now = monotonic_clock_now();
×
1250
    milliseconds_type round_trip_time = now - timestamp;
×
1251
    logger.debug("Round trip time was %1 milliseconds", round_trip_time);
×
1252
    m_previous_ping_rtt = round_trip_time;
×
1253

×
1254
    // If this PONG message is a response to a PING mesage that was sent after
×
1255
    // the last invocation of cancel_reconnect_delay(), then the connection is
2,147,483,647✔
1256
    // still good, and we do not have to skip the next reconnect delay.
2,147,483,647✔
1257
    if (m_ping_after_scheduled_reset_of_reconnect_info) {
2,147,483,647✔
1258
        REALM_ASSERT(m_reconnect_info.scheduled_reset);
2,147,483,647✔
1259
        m_ping_after_scheduled_reset_of_reconnect_info = false;
2,147,483,647✔
1260
        m_reconnect_info.scheduled_reset = false;
73,292✔
1261
    }
1262

1263
    m_heartbeat_timer.reset();
766✔
1264
    m_waiting_for_pong = false;
766✔
1265

766✔
1266
    initiate_ping_delay(now); // Throws
700✔
1267

700✔
1268
    if (m_client.m_roundtrip_time_handler)
×
1269
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
×
1270
}
700✔
1271

×
1272
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
×
1273
{
×
1274
    if (session_ident == 0) {
1275
        return nullptr;
700✔
1276
    }
2✔
1277

2✔
1278
    auto* sess = get_session(session_ident);
700✔
1279
    if (REALM_LIKELY(sess)) {
700✔
1280
        return sess;
1281
    }
66✔
1282
    // Check the history to see if the message received was for a previous session
66✔
1283
    if (auto it = m_session_history.find(session_ident); it == m_session_history.end()) {
66✔
1284
        logger.error("Bad session identifier in %1 message, session_ident = %2", message, session_ident);
1285
        close_due_to_protocol_error(
66✔
1286
            {ErrorCodes::SyncProtocolInvariantFailed,
66✔
1287
             util::format("Received message %1 for session iden %2 when that session never existed", message,
62✔
1288
                          session_ident)});
62✔
1289
    }
62✔
1290
    else {
62✔
1291
        logger.error("Received %1 message for closed session, session_ident = %2", message,
62✔
1292
                     session_ident); // Throws
×
1293
    }
×
1294
    return nullptr;
×
1295
}
×
1296

×
1297
void Connection::receive_error_message(const ProtocolErrorInfo& info, session_ident_type session_ident)
4✔
1298
{
4✔
1299
    Session* sess = nullptr;
4✔
1300
    if (session_ident != 0) {
4✔
1301
        sess = find_and_validate_session(session_ident, "ERROR");
4✔
1302
        if (REALM_UNLIKELY(!sess)) {
66✔
1303
            return;
1304
        }
1305
        if (auto status = sess->receive_error_message(info); !status.is_ok()) {
1306
            close_due_to_protocol_error(std::move(status)); // Throws
1307
            return;
20✔
1308
        }
20✔
1309

×
1310
        if (sess->m_state == Session::Deactivated) {
×
1311
            finish_session_deactivation(sess);
×
1312
        }
1313
        return;
20✔
1314
    }
×
1315

×
1316
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
×
1317
                info.message, info.raw_error_code, info.is_fatal, session_ident,
1318
                info.server_requests_action); // Throws
20✔
1319

20✔
1320
    bool known_error_code = bool(get_protocol_error_message(info.raw_error_code));
×
1321
    if (REALM_LIKELY(known_error_code)) {
×
1322
        ProtocolError error_code = ProtocolError(info.raw_error_code);
1323
        if (REALM_LIKELY(!is_session_level_error(error_code))) {
20✔
1324
            close_due_to_server_side_error(error_code, info); // Throws
×
1325
            return;
×
1326
        }
20✔
1327
        close_due_to_protocol_error(
1328
            {ErrorCodes::SyncProtocolInvariantFailed,
1329
             util::format("Received ERROR message with a non-connection-level error code %1 without a session ident",
1330
                          info.raw_error_code)});
3,716✔
1331
    }
3,716✔
1332
    else {
3,716✔
1333
        close_due_to_protocol_error(
×
1334
            {ErrorCodes::SyncProtocolInvariantFailed,
×
1335
             util::format("Received ERROR message with unknown error code %1", info.raw_error_code)});
1336
    }
3,716✔
1337
}
×
1338

3,716✔
1339

1340
void Connection::receive_query_error_message(int raw_error_code, std::string_view message, int64_t query_version,
1341
                                             session_ident_type session_ident)
47,920✔
1342
{
47,920✔
1343
    if (session_ident == 0) {
47,920✔
1344
        return close_due_to_protocol_error(
×
1345
            {ErrorCodes::SyncProtocolInvariantFailed, "Received query error message for session ident 0"});
×
1346
    }
1347

47,920✔
1348
    if (!is_flx_sync_connection()) {
2✔
1349
        return close_due_to_protocol_error({ErrorCodes::SyncProtocolInvariantFailed,
2✔
1350
                                            "Received a FLX query error message on a non-FLX sync connection"});
47,920✔
1351
    }
1352

1353
    Session* sess = find_and_validate_session(session_ident, "QUERY_ERROR");
16,462✔
1354
    if (REALM_UNLIKELY(!sess)) {
16,462✔
1355
        return;
16,462✔
1356
    }
×
1357

×
1358
    if (auto status = sess->receive_query_error_message(raw_error_code, message, query_version); !status.is_ok()) {
1359
        close_due_to_protocol_error(std::move(status));
16,462✔
1360
    }
10✔
1361
}
16,462✔
1362

1363

1364
void Connection::receive_ident_message(session_ident_type session_ident, SaltedFileIdent client_file_ident)
1365
{
4,424✔
1366
    Session* sess = find_and_validate_session(session_ident, "IDENT");
4,424✔
1367
    if (REALM_UNLIKELY(!sess)) {
4,424✔
1368
        return;
×
1369
    }
×
1370

1371
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
4,424✔
1372
        close_due_to_protocol_error(std::move(status)); // Throws
×
1373
}
×
1374

×
1375
void Connection::receive_download_message(session_ident_type session_ident, const DownloadMessage& message)
1376
{
4,424✔
1377
    Session* sess = find_and_validate_session(session_ident, "DOWNLOAD");
4,424✔
1378
    if (REALM_UNLIKELY(!sess)) {
4,424✔
1379
        return;
4,424✔
1380
    }
1381

1382
    if (auto status = sess->receive_download_message(message); !status.is_ok()) {
1383
        close_due_to_protocol_error(std::move(status));
1384
    }
52✔
1385
}
52✔
1386

52✔
1387
void Connection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
×
1388
{
×
1389
    Session* sess = find_and_validate_session(session_ident, "MARK");
1390
    if (REALM_UNLIKELY(!sess)) {
52✔
1391
        return;
×
1392
    }
×
1393

52✔
1394
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
1395
        close_due_to_protocol_error(std::move(status)); // Throws
1396
}
1397

1398

5,996✔
1399
void Connection::receive_unbound_message(session_ident_type session_ident)
5,996✔
1400
{
5,996✔
1401
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
5,994✔
1402
    if (REALM_UNLIKELY(!sess)) {
5,994✔
1403
        return;
2✔
1404
    }
2✔
1405

2✔
1406
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
1407
        close_due_to_protocol_error(std::move(status)); // Throws
5,996✔
1408
        return;
3,996✔
1409
    }
3,980✔
1410

3,980✔
1411
    if (sess->m_state == Session::Deactivated) {
3,980✔
1412
        finish_session_deactivation(sess);
1413
    }
16✔
1414
}
16✔
1415

16✔
1416

3,996✔
1417
void Connection::receive_test_command_response(session_ident_type session_ident, request_ident_type request_ident,
1418
                                               std::string_view body)
2,000✔
1419
{
2,000✔
1420
    Session* sess = find_and_validate_session(session_ident, "TEST_COMMAND");
1421
    if (REALM_UNLIKELY(!sess)) {
1422
        return;
1423
    }
5,542✔
1424

1425
    if (auto status = sess->receive_test_command_response(request_ident, body); !status.is_ok()) {
5,542✔
1426
        close_due_to_protocol_error(std::move(status));
2,496✔
1427
    }
2,496✔
1428
}
2,496✔
1429

2,496✔
1430

5,542✔
1431
void Connection::receive_server_log_message(session_ident_type session_ident, util::Logger::Level level,
1432
                                            std::string_view message)
1433
{
1434
    std::string prefix;
×
1435
    if (REALM_LIKELY(!m_appservices_coid.empty())) {
×
1436
        prefix = util::format("Server[%1]", m_appservices_coid);
×
1437
    }
1438
    else {
1439
        prefix = "Server";
1440
    }
1441

1442
    if (session_ident != 0) {
1443
        if (auto sess = get_session(session_ident)) {
1444
            sess->logger.log(LogCategory::session, level, "%1 log: %2", prefix, message);
1445
            return;
1446
        }
1447

1448
        logger.log(util::LogCategory::session, level, "%1 log for unknown session %2: %3", prefix, session_ident,
166,742✔
1449
                   message);
166,742✔
1450
        return;
166,742✔
1451
    }
166,742✔
1452

61,308✔
1453
    logger.log(level, "%1 log: %2", prefix, message);
166,742✔
1454
}
1455

1456

1457
void Connection::receive_appservices_request_id(std::string_view coid)
72✔
1458
{
72✔
1459
    // Only set once per connection
72✔
1460
    if (!coid.empty() && m_appservices_coid.empty()) {
1461
        m_appservices_coid = coid;
1462
        logger.log(util::LogCategory::session, util::LogCategory::Level::info,
4,118✔
1463
                   "Connected to app services with request id: \"%1\"", m_appservices_coid);
4,118✔
1464
    }
1465
}
4,118✔
1466

4,056✔
1467

1468
void Connection::handle_protocol_error(Status status)
62✔
1469
{
1470
    close_due_to_protocol_error(std::move(status));
62✔
1471
}
1472

62✔
1473

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

23,392✔
1490

1491
std::string Connection::get_active_appservices_connection_id()
44✔
1492
{
44✔
1493
    return m_appservices_coid;
44✔
1494
}
44✔
1495

44✔
1496
void Session::cancel_resumption_delay()
44✔
1497
{
44✔
1498
    REALM_ASSERT_EX(m_state == Active, m_state);
44✔
1499

44✔
1500
    if (!m_suspended)
1501
        return;
88✔
1502

88✔
1503
    m_suspended = false;
44✔
1504

44✔
1505
    logger.debug("Resumed"); // Throws
44✔
1506

44✔
1507
    if (unbind_process_complete())
44✔
1508
        initiate_rebind(); // Throws
44✔
1509

44✔
1510
    m_conn.one_more_active_unsuspended_session(); // Throws
1511
    if (m_try_again_activation_timer) {
1512
        m_try_again_activation_timer.reset();
1513
    }
1514

1515
    on_resumed(); // Throws
45,252✔
1516
}
45,252✔
1517

45,252✔
1518

21,792✔
1519
void Session::gather_pending_compensating_writes(util::Span<Changeset> changesets,
×
1520
                                                 std::vector<ProtocolErrorInfo>* out)
×
1521
{
×
1522
    if (m_pending_compensating_write_errors.empty() || changesets.empty()) {
×
1523
        return;
21,792✔
1524
    }
21,792✔
1525

21,792✔
1526
#ifdef REALM_DEBUG
1527
    REALM_ASSERT_DEBUG(
23,460✔
1528
        std::is_sorted(m_pending_compensating_write_errors.begin(), m_pending_compensating_write_errors.end(),
23,460✔
1529
                       [](const ProtocolErrorInfo& lhs, const ProtocolErrorInfo& rhs) {
23,460✔
1530
                           REALM_ASSERT_DEBUG(lhs.compensating_write_server_version.has_value());
23,460✔
1531
                           REALM_ASSERT_DEBUG(rhs.compensating_write_server_version.has_value());
23,460✔
1532
                           return *lhs.compensating_write_server_version < *rhs.compensating_write_server_version;
23,436✔
1533
                       }));
23,436✔
1534
#endif
23,460✔
1535

15,542✔
1536
    while (!m_pending_compensating_write_errors.empty() &&
15,542✔
1537
           *m_pending_compensating_write_errors.front().compensating_write_server_version <=
15,542✔
1538
               changesets.back().version) {
7,918✔
1539
        auto& cur_error = m_pending_compensating_write_errors.front();
7,918✔
1540
        REALM_ASSERT_3(*cur_error.compensating_write_server_version, >=, changesets.front().version);
7,918✔
1541
        out->push_back(std::move(cur_error));
7,918✔
1542
        m_pending_compensating_write_errors.pop_front();
1543
    }
23,460✔
1544
}
44✔
1545

44✔
1546

44✔
1547
void Session::integrate_changesets(const SyncProgress& progress, std::uint_fast64_t downloadable_bytes,
44✔
1548
                                   const ReceivedChangesets& received_changesets, VersionInfo& version_info,
44✔
1549
                                   DownloadBatchState download_batch_state)
44✔
1550
{
44✔
1551
    auto& history = get_history();
44✔
1552
    if (received_changesets.empty()) {
44✔
1553
        if (download_batch_state == DownloadBatchState::MoreToCome) {
44✔
1554
            throw IntegrationException(ErrorCodes::SyncProtocolInvariantFailed,
44✔
1555
                                       "received empty download message that was not the last in batch",
×
1556
                                       ProtocolError::bad_progress);
×
1557
        }
44✔
1558
        history.set_sync_progress(progress, &downloadable_bytes, version_info); // Throws
23,460✔
1559
        return;
1560
    }
1561

1562
    std::vector<ProtocolErrorInfo> pending_compensating_write_errors;
40✔
1563
    auto transact = get_db()->start_read();
40✔
1564
    history.integrate_server_changesets(
40✔
1565
        progress, &downloadable_bytes, received_changesets, version_info, download_batch_state, logger, transact,
40✔
1566
        [&](const TransactionRef&, util::Span<Changeset> changesets) {
1567
            gather_pending_compensating_writes(changesets, &pending_compensating_write_errors);
40✔
1568
        }); // Throws
40✔
1569
    if (received_changesets.size() == 1) {
40✔
1570
        logger.debug("1 remote changeset integrated, producing client version %1",
40✔
1571
                     version_info.sync_version.version); // Throws
1572
    }
40✔
1573
    else {
1574
        logger.debug("%2 remote changesets integrated, producing client version %1",
1575
                     version_info.sync_version.version, received_changesets.size()); // Throws
1576
    }
40✔
1577

40✔
1578
    for (const auto& pending_error : pending_compensating_write_errors) {
36✔
1579
        logger.info("Reporting compensating write for client version %1 in server version %2: %3",
36✔
1580
                    pending_error.compensating_write_rejected_client_version,
40✔
1581
                    *pending_error.compensating_write_server_version, pending_error.message);
1582
        try {
1583
            on_connection_state_changed(
1584
                m_conn.get_state(),
47,152✔
1585
                SessionErrorInfo{pending_error,
47,152✔
1586
                                 protocol_error_to_status(static_cast<ProtocolError>(pending_error.raw_error_code),
47,152✔
1587
                                                          pending_error.message)});
47,152✔
1588
        }
1589
        catch (...) {
47,152✔
1590
            logger.error("Exception thrown while reporting compensating write: %1", exception_to_status());
47,152✔
1591
        }
1592
    }
47,152✔
1593
}
34,140✔
1594

14,202✔
1595

892✔
1596
void Session::on_integration_failure(const IntegrationException& error)
14,202✔
1597
{
14,202✔
1598
    REALM_ASSERT_EX(m_state == Active, m_state);
1599
    REALM_ASSERT(!m_client_error && !m_error_to_send);
34,140✔
1600
    logger.error("Failed to integrate downloaded changesets: %1", error.to_status());
34,140✔
1601

34,140✔
1602
    m_client_error = util::make_optional<IntegrationException>(error);
1603
    m_error_to_send = true;
47,152✔
1604
    SessionErrorInfo error_info{error.to_status(), IsFatal{false}};
1605
    error_info.server_requests_action = ProtocolErrorInfo::Action::Warning;
1606
    // Surface the error to the user otherwise is lost.
47,152✔
1607
    on_connection_state_changed(m_conn.get_state(), std::move(error_info));
47,152✔
1608

27,298✔
1609
    // Since the deactivation process has not been initiated, the UNBIND
1610
    // message cannot have been sent unless an ERROR message was received.
47,152✔
1611
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
1612
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
1613
        ensure_enlisted_to_send(); // Throws
47,152✔
1614
    }
3,228✔
1615
}
3,228✔
1616

3,228✔
1617
void Session::on_changesets_integrated(version_type client_version, const SyncProgress& progress,
1618
                                       bool changesets_integrated)
1619
{
1620
    REALM_ASSERT_EX(m_state == Active, m_state);
47,152✔
1621
    REALM_ASSERT_3(progress.download.server_version, >=, m_download_progress.server_version);
47,152✔
1622
    bool upload_progressed = (progress.upload.client_version > m_progress.upload.client_version);
47,142✔
1623

47,142✔
1624
    m_download_progress = progress.download;
47,152✔
1625
    m_progress = progress;
1626

1627
    if (upload_progressed) {
1628
        if (progress.upload.client_version > m_last_version_selected_for_upload) {
10,274✔
1629
            if (progress.upload.client_version > m_upload_progress.client_version)
1630
                m_upload_progress = progress.upload;
10,274✔
1631
            m_last_version_selected_for_upload = progress.upload.client_version;
1632
        }
1633

1634
        notify_upload_progress();
10,286✔
1635
        check_for_upload_completion();
10,286✔
1636
    }
10,286✔
1637

10,286✔
1638
    bool resume_upload = do_recognize_sync_version(client_version); // Allows upload process to resume
10,286✔
1639

10,286✔
1640
    // notify also when final DOWNLOAD received with no changesets
1641
    bool download_progressed = changesets_integrated || (!upload_progressed && resume_upload);
1642
    if (download_progressed)
1643
        notify_download_progress();
10,284✔
1644

10,284✔
1645
    check_for_download_completion(); // Throws
1646

10,284✔
1647
    // If the client migrated from PBS to FLX, create subscriptions when new tables are received from server.
1648
    if (auto migration_store = get_migration_store(); migration_store && m_is_flx_sync_session) {
10,284✔
1649
        auto& flx_subscription_store = *get_flx_subscription_store();
10,286✔
1650
        get_migration_store()->create_subscriptions(flx_subscription_store);
10,286✔
1651
    }
10,286✔
1652

1653
    // Since the deactivation process has not been initiated, the UNBIND
10,286✔
1654
    // message cannot have been sent unless an ERROR message was received.
10,286✔
1655
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
9,910✔
1656
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
9,910✔
1657
        ensure_enlisted_to_send(); // Throws
9,910✔
1658
    }
10,286✔
1659
}
10,284✔
1660

10,284✔
1661

10,284✔
1662
Session::~Session()
10,284✔
1663
{
10,284✔
1664
    //    REALM_ASSERT_EX(m_state == Unactivated || m_state == Deactivated, m_state);
10,284✔
1665
}
10,284✔
1666

1667

10,284✔
1668
std::string Session::make_logger_prefix(session_ident_type ident)
10,284✔
1669
{
10,284✔
1670
    std::ostringstream out;
10,284✔
1671
    out.imbue(std::locale::classic());
10,284✔
1672
    out << "Session[" << ident << "]: "; // Throws
10,284✔
1673
    return out.str();                    // Throws
1674
}
10,284✔
1675

10,284✔
1676

1677
void Session::activate()
10,284✔
1678
{
10,284✔
1679
    REALM_ASSERT_EX(m_state == Unactivated, m_state);
1680

10,284✔
1681
    logger.debug("Activating"); // Throws
10,284✔
1682

1683
    bool has_pending_client_reset = false;
10,284✔
1684
    if (REALM_LIKELY(!get_client().is_dry_run())) {
10,284✔
1685
        bool file_exists = util::File::exists(get_realm_path());
10,284✔
1686
        m_performing_client_reset = get_client_reset_config().has_value();
10,284✔
1687

×
1688
        logger.info("client_reset_config = %1, Realm exists = %2 ", m_performing_client_reset, file_exists);
×
1689
        if (!m_performing_client_reset) {
10,284✔
1690
            get_history().get_status(m_last_version_available, m_client_file_ident, m_progress,
4✔
1691
                                     &has_pending_client_reset); // Throws
4✔
1692
        }
1693
    }
10,286✔
1694
    logger.debug("client_file_ident = %1, client_file_ident_salt = %2", m_client_file_ident.ident,
20✔
1695
                 m_client_file_ident.salt); // Throws
20✔
1696
    m_upload_progress = m_progress.upload;
10,286✔
1697
    m_last_version_selected_for_upload = m_upload_progress.client_version;
1698
    m_download_progress = m_progress.download;
1699
    REALM_ASSERT_3(m_last_version_available, >=, m_progress.upload.client_version);
1700
    init_progress_handler();
1701

1702
    logger.debug("last_version_available  = %1", m_last_version_available);                    // Throws
10,274✔
1703
    logger.debug("progress_download_server_version = %1", m_progress.download.server_version); // Throws
10,274✔
1704
    logger.debug("progress_download_client_version = %1",
1705
                 m_progress.download.last_integrated_client_version);                                      // Throws
10,274✔
1706
    logger.debug("progress_upload_server_version = %1", m_progress.upload.last_integrated_server_version); // Throws
1707
    logger.debug("progress_upload_client_version = %1", m_progress.upload.client_version);                 // Throws
10,274✔
1708

1709
    reset_protocol_state();
10,274✔
1710
    m_state = Active;
9,666✔
1711

1712
    call_debug_hook(SyncClientHookEvent::SessionActivating, m_progress, m_last_sent_flx_query_version,
10,274✔
1713
                    DownloadBatchState::SteadyState, 0);
5,308✔
1714

5,308✔
1715
    REALM_ASSERT(!m_suspended);
5,308✔
1716
    m_conn.one_more_active_unsuspended_session(); // Throws
1717

1718
    try {
1719
        process_pending_flx_bootstrap();
1720
    }
4,966✔
1721
    catch (const IntegrationException& error) {
964✔
1722
        on_integration_failure(error);
1723
    }
964✔
1724
    catch (...) {
964✔
1725
        on_integration_failure(IntegrationException(exception_to_status()));
1726
    }
1727

4,002✔
1728
    if (has_pending_client_reset) {
3,790✔
1729
        handle_pending_client_reset_acknowledgement();
3,790✔
1730
    }
3,790✔
1731
}
4,002✔
1732

1733

1734
// The caller (Connection) must discard the session if the session has become
1735
// deactivated upon return.
10,274✔
1736
void Session::initiate_deactivation()
10,274✔
1737
{
10,274✔
1738
    REALM_ASSERT_EX(m_state == Active, m_state);
1739

10,274✔
1740
    logger.debug("Initiating deactivation"); // Throws
10,274✔
1741

1742
    m_state = Deactivating;
1743

1744
    if (!m_suspended)
1745
        m_conn.one_less_active_unsuspended_session(); // Throws
1746

1747
    if (m_enlisted_to_send) {
1748
        REALM_ASSERT(!unbind_process_complete());
1749
        return;
165,134✔
1750
    }
165,134✔
1751

165,134✔
1752
    // Deactivate immediately if the BIND message has not yet been sent and the
165,134✔
1753
    // session is not enlisted to send, or if the unbinding process has already
165,134✔
1754
    // completed.
1755
    if (!m_bind_message_sent || unbind_process_complete()) {
1756
        complete_deactivation(); // Throws
1757
        // Life cycle state is now Deactivated
9,332✔
1758
        return;
2,824✔
1759
    }
1760

2,824✔
1761
    // Ready to send the UNBIND message, if it has not already been sent
1762
    if (!m_unbind_message_sent) {
1763
        enlist_to_send(); // Throws
1764
        return;
6,508✔
1765
    }
6,508✔
1766
}
6,508✔
1767

9,332✔
1768

1769
void Session::complete_deactivation()
1770
{
1771
    REALM_ASSERT_EX(m_state == Deactivating, m_state);
155,802✔
1772
    m_state = Deactivated;
1773

155,802✔
1774
    logger.debug("Deactivation completed"); // Throws
9,028✔
1775
}
1776

146,774✔
1777

7,422✔
1778
// Called by the associated Connection object when this session is granted an
7,422✔
1779
// opportunity to send a message.
7,422✔
1780
//
7,422✔
1781
// The caller (Connection) must discard the session if the session has become
1782
// deactivated upon return.
139,352✔
1783
void Session::send_message()
139,352✔
1784
{
108✔
1785
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
108✔
1786
    REALM_ASSERT(m_enlisted_to_send);
139,352✔
1787
    m_enlisted_to_send = false;
52✔
1788
    if (m_state == Deactivating || m_error_message_received || m_suspended) {
52✔
1789
        // Deactivation has been initiated. If the UNBIND message has not been
1790
        // sent yet, there is no point in sending it. Instead, we can let the
139,300✔
1791
        // deactivation process complete.
30✔
1792
        if (!m_bind_message_sent) {
1793
            return complete_deactivation(); // Throws
1794
            // Life cycle state is now Deactivated
139,270✔
1795
        }
12✔
1796

12✔
1797
        // Session life cycle state is Deactivating or the unbinding process has
1798
        // been initiated by a session specific ERROR message
139,258✔
1799
        if (!m_unbind_message_sent)
17,264✔
1800
            send_unbind_message(); // Throws
1801
        return;
122,000✔
1802
    }
122,000✔
1803

106,978✔
1804
    // Session life cycle state is Active and the unbinding process has
106,978✔
1805
    // not been initiated
1806
    REALM_ASSERT(!m_unbind_message_sent);
15,022✔
1807

15,022✔
1808
    if (!m_bind_message_sent)
×
1809
        return send_bind_message(); // Throws
×
1810

1811
    if (!m_ident_message_sent) {
15,022✔
1812
        if (have_client_file_ident())
15,022✔
1813
            send_ident_message(); // Throws
14,994✔
1814
        return;
14,994✔
1815
    }
1816

1817
    const auto has_pending_test_command = std::any_of(m_pending_test_commands.begin(), m_pending_test_commands.end(),
28✔
1818
                                                      [](const PendingTestCommand& command) {
15,022✔
1819
                                                          return command.pending;
1820
                                                      });
121,994✔
1821
    if (has_pending_test_command) {
16✔
1822
        return send_test_command_message();
16✔
1823
    }
1824

121,984✔
1825
    if (m_error_to_send)
121,984✔
1826
        return send_json_error_message(); // Throws
106,978✔
1827

106,978✔
1828
    // Stop sending upload, mark and query messages when the client detects an error.
1829
    if (m_client_error) {
15,006✔
1830
        return;
3,074✔
1831
    }
3,074✔
1832

1833
    if (m_target_download_mark > m_last_download_mark_sent)
11,932✔
1834
        return send_mark_message(); // Throws
1835

11,932✔
1836
    auto is_upload_allowed = [&]() -> bool {
9,916✔
1837
        if (!m_is_flx_sync_session) {
9,916✔
1838
            return true;
1839
        }
2,016✔
1840

11,932✔
1841
        auto migration_store = get_migration_store();
1842
        if (!migration_store) {
121,978✔
1843
            return true;
1,146✔
1844
        }
1,146✔
1845

1846
        auto sentinel_query_version = migration_store->get_sentinel_subscription_set_version();
120,832✔
1847
        if (!sentinel_query_version) {
59,340✔
1848
            return true;
59,340✔
1849
        }
120,832✔
1850

1851
        // Do not allow upload if the last query sent is the sentinel one used by the migration store.
1852
        return m_last_sent_flx_query_version != *sentinel_query_version;
1853
    };
9,028✔
1854

9,028✔
1855
    if (!is_upload_allowed()) {
1856
        return;
9,028✔
1857
    }
9,028✔
1858

9,028✔
1859
    auto check_pending_flx_version = [&]() -> bool {
1860
        if (!m_is_flx_sync_session) {
1861
            return false;
9,028✔
1862
        }
9,028✔
1863

9,028✔
1864
        if (!m_allow_upload) {
1865
            return false;
9,028✔
1866
        }
9,028✔
1867

1,470✔
1868
        m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(m_last_sent_flx_query_version);
1,470✔
1869

60✔
1870
        if (!m_pending_flx_sub_set) {
60✔
1871
            return false;
1,470✔
1872
        }
1,470✔
1873

1874
        return m_upload_progress.client_version >= m_pending_flx_sub_set->snapshot_version;
1,470✔
1875
    };
1,470✔
1876

1,470✔
1877
    if (check_pending_flx_version()) {
1,470✔
1878
        return send_query_change_message(); // throws
1,470✔
1879
    }
1,470✔
1880

1,470✔
1881
    if (m_allow_upload && (m_last_version_available > m_upload_progress.client_version)) {
1,470✔
1882
        return send_upload_message(); // Throws
1,470✔
1883
    }
1,470✔
1884
}
1,470✔
1885

1,470✔
1886

1,470✔
1887
void Session::send_bind_message()
7,558✔
1888
{
7,558✔
1889
    REALM_ASSERT_EX(m_state == Active, m_state);
7,558✔
1890

7,558✔
1891
    session_ident_type session_ident = m_ident;
7,558✔
1892
    bool need_client_file_ident = !have_client_file_ident();
7,558✔
1893
    const bool is_subserver = false;
7,558✔
1894

9,028✔
1895

1896
    ClientProtocol& protocol = m_conn.get_client_protocol();
9,028✔
1897
    int protocol_version = m_conn.get_negotiated_protocol_version();
9,028✔
1898
    OutputBuffer& out = m_conn.get_output_buffer();
9,028✔
1899
    // Discard the token since it's ignored by the server.
1900
    std::string empty_access_token;
1901
    if (m_is_flx_sync_session) {
1902
        nlohmann::json bind_json_data;
9,028✔
1903
        if (auto migrated_partition = get_migration_store()->get_migrated_partition()) {
3,878✔
1904
            bind_json_data["migratedPartition"] = *migrated_partition;
9,028✔
1905
        }
1906
        bind_json_data["sessionReason"] = static_cast<uint64_t>(get_session_reason());
1907
        auto schema_version = get_schema_version();
1908
        // Send 0 if schema is not versioned.
7,422✔
1909
        bind_json_data["schemaVersion"] = schema_version != uint64_t(-1) ? schema_version : 0;
7,422✔
1910
        if (logger.would_log(util::Logger::Level::debug)) {
7,422✔
1911
            std::string json_data_dump;
7,422✔
1912
            if (!bind_json_data.empty()) {
7,422✔
1913
                json_data_dump = bind_json_data.dump();
1914
            }
1915
            logger.debug(
7,422✔
1916
                "Sending: BIND(session_ident=%1, need_client_file_ident=%2, is_subserver=%3, json_data=\"%4\")",
7,422✔
1917
                session_ident, need_client_file_ident, is_subserver, json_data_dump);
7,422✔
1918
        }
1919
        protocol.make_flx_bind_message(protocol_version, out, session_ident, bind_json_data, empty_access_token,
7,422✔
1920
                                       need_client_file_ident, is_subserver); // Throws
1,388✔
1921
    }
1,388✔
1922
    else {
1,388✔
1923
        std::string server_path = get_virt_path();
1,388✔
1924
        logger.debug("Sending: BIND(session_ident=%1, need_client_file_ident=%2, is_subserver=%3, server_path=%4)",
1,388✔
1925
                     session_ident, need_client_file_ident, is_subserver, server_path);
1,388✔
1926
        protocol.make_pbs_bind_message(protocol_version, out, session_ident, server_path, empty_access_token,
1,388✔
1927
                                       need_client_file_ident, is_subserver); // Throws
1,388✔
1928
    }
1,388✔
1929
    m_conn.initiate_write_message(out, this); // Throws
1,388✔
1930

1,388✔
1931
    m_bind_message_sent = true;
1,388✔
1932
    call_debug_hook(SyncClientHookEvent::BindMessageSent, m_progress, m_last_sent_flx_query_version,
1,388✔
1933
                    DownloadBatchState::SteadyState, 0);
6,034✔
1934

6,034✔
1935
    // Ready to send the IDENT message if the file identifier pair is already
6,034✔
1936
    // available.
6,034✔
1937
    if (!need_client_file_ident)
6,034✔
1938
        enlist_to_send(); // Throws
6,034✔
1939
}
6,034✔
1940

6,034✔
1941

6,034✔
1942
void Session::send_ident_message()
7,422✔
1943
{
1944
    REALM_ASSERT_EX(m_state == Active, m_state);
7,422✔
1945
    REALM_ASSERT(m_bind_message_sent);
1946
    REALM_ASSERT(!m_unbind_message_sent);
1947
    REALM_ASSERT(have_client_file_ident());
7,422✔
1948

7,422✔
1949

1950
    ClientProtocol& protocol = m_conn.get_client_protocol();
1951
    OutputBuffer& out = m_conn.get_output_buffer();
1,146✔
1952
    session_ident_type session_ident = m_ident;
1,146✔
1953

1,146✔
1954
    if (m_is_flx_sync_session) {
1,146✔
1955
        const auto active_query_set = get_flx_subscription_store()->get_active();
1,146✔
1956
        const auto active_query_body = active_query_set.to_ext_json();
1,146✔
1957
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
1958
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
1,146✔
1959
                     "latest_server_version_salt=%6, query_version=%7, query_size=%8, query=\"%9\")",
×
1960
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
×
1961
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
1962
                     m_progress.latest_server_version.salt, active_query_set.version(), active_query_body.size(),
1,146✔
1963
                     active_query_body); // Throws
1,146✔
1964
        protocol.make_flx_ident_message(out, session_ident, m_client_file_ident, m_progress,
1,146✔
1965
                                        active_query_set.version(), active_query_body); // Throws
1,146✔
1966
        m_last_sent_flx_query_version = active_query_set.version();
1,146✔
1967
    }
1968
    else {
1,146✔
1969
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
1,146✔
1970
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
1,146✔
1971
                     "latest_server_version_salt=%6)",
1,146✔
1972
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
1,146✔
1973
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
1974
                     m_progress.latest_server_version.salt);                                  // Throws
1,146✔
1975
        protocol.make_pbs_ident_message(out, session_ident, m_client_file_ident, m_progress); // Throws
1976
    }
1,146✔
1977
    m_conn.initiate_write_message(out, this); // Throws
1,146✔
1978

1979
    m_ident_message_sent = true;
1980

59,340✔
1981
    // Other messages may be waiting to be sent
59,340✔
1982
    enlist_to_send(); // Throws
59,340✔
1983
}
59,340✔
1984

1985
void Session::send_query_change_message()
59,340✔
1986
{
×
1987
    REALM_ASSERT_EX(m_state == Active, m_state);
1988
    REALM_ASSERT(m_ident_message_sent);
59,340✔
1989
    REALM_ASSERT(!m_unbind_message_sent);
59,340✔
1990
    REALM_ASSERT(m_pending_flx_sub_set);
870✔
1991
    REALM_ASSERT_3(m_pending_flx_sub_set->query_version, >, m_last_sent_flx_query_version);
870✔
1992

870✔
1993
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
1994
        return;
59,340✔
1995
    }
59,340✔
1996

59,340✔
1997
    auto sub_store = get_flx_subscription_store();
59,340✔
1998
    auto latest_sub_set = sub_store->get_by_version(m_pending_flx_sub_set->query_version);
1999
    auto latest_queries = latest_sub_set.to_ext_json();
59,340✔
2000
    logger.debug("Sending: QUERY(query_version=%1, query_size=%2, query=\"%3\", snapshot_version=%4)",
2001
                 latest_sub_set.version(), latest_queries.size(), latest_queries, latest_sub_set.snapshot_version());
29,750✔
2002

2003
    OutputBuffer& out = m_conn.get_output_buffer();
2004
    session_ident_type session_ident = get_ident();
29,750✔
2005
    ClientProtocol& protocol = m_conn.get_client_protocol();
274✔
2006
    protocol.make_query_change_message(out, session_ident, latest_sub_set.version(), latest_queries);
274✔
2007
    m_conn.initiate_write_message(out, this);
2008

274✔
2009
    m_last_sent_flx_query_version = latest_sub_set.version();
274✔
2010

29,750✔
2011
    request_download_completion_notification();
29,590✔
2012
}
29,590✔
2013

29,590✔
2014
void Session::send_upload_message()
2015
{
59,066✔
2016
    REALM_ASSERT_EX(m_state == Active, m_state);
596✔
2017
    REALM_ASSERT(m_ident_message_sent);
596✔
2018
    REALM_ASSERT(!m_unbind_message_sent);
596✔
2019

2020
    if (REALM_UNLIKELY(get_client().is_dry_run()))
59,066✔
2021
        return;
59,066✔
2022

2023
    version_type target_upload_version = m_last_version_available;
59,066✔
2024
    if (m_pending_flx_sub_set) {
59,066✔
2025
        REALM_ASSERT(m_is_flx_sync_session);
59,066✔
2026
        target_upload_version = m_pending_flx_sub_set->snapshot_version;
59,066✔
2027
    }
2028

59,066✔
2029
    std::vector<UploadChangeset> uploadable_changesets;
59,066✔
2030
    version_type locked_server_version = 0;
2031
    get_history().find_uploadable_changesets(m_upload_progress, target_upload_version, uploadable_changesets,
59,066✔
2032
                                             locked_server_version); // Throws
43,560✔
2033

43,560✔
2034
    if (uploadable_changesets.empty()) {
43,560✔
2035
        // Nothing more to upload right now
43,560✔
2036
        check_for_upload_completion(); // Throws
43,560✔
2037
        // If we need to limit upload up to some version other than the last client version available and there are no
43,560✔
2038
        // changes to upload, then there is no need to send an empty message.
×
2039
        if (m_pending_flx_sub_set) {
×
2040
            logger.debug("Empty UPLOAD was skipped (progress_client_version=%1, progress_server_version=%2)",
×
2041
                         m_upload_progress.client_version, m_upload_progress.last_integrated_server_version);
×
2042
            // Other messages may be waiting to be sent
×
2043
            return enlist_to_send(); // Throws
×
2044
        }
×
2045
    }
×
2046
    else {
×
2047
        m_last_version_selected_for_upload = uploadable_changesets.back().progress.client_version;
2048
    }
×
2049

×
2050
    if (m_pending_flx_sub_set && target_upload_version < m_last_version_available) {
×
2051
        logger.trace("Limiting UPLOAD message up to version %1 to send QUERY version %2",
×
2052
                     m_pending_flx_sub_set->snapshot_version, m_pending_flx_sub_set->query_version);
×
2053
    }
×
2054

×
2055
    version_type progress_client_version = m_upload_progress.client_version;
×
2056
    version_type progress_server_version = m_upload_progress.last_integrated_server_version;
×
2057

×
2058
    logger.debug("Sending: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
×
2059
                 "locked_server_version=%3, num_changesets=%4)",
×
2060
                 progress_client_version, progress_server_version, locked_server_version,
×
2061
                 uploadable_changesets.size()); // Throws
×
2062

2063
    ClientProtocol& protocol = m_conn.get_client_protocol();
2064
    ClientProtocol::UploadMessageBuilder upload_message_builder = protocol.make_upload_message_builder(); // Throws
2065

2066
    for (const UploadChangeset& uc : uploadable_changesets) {
2067
        logger.debug(util::LogCategory::changeset,
2068
                     "Fetching changeset for upload (client_version=%1, server_version=%2, "
2069
                     "changeset_size=%3, origin_timestamp=%4, origin_file_ident=%5)",
2070
                     uc.progress.client_version, uc.progress.last_integrated_server_version, uc.changeset.size(),
2071
                     uc.origin_timestamp, uc.origin_file_ident); // Throws
2072
        if (logger.would_log(util::Logger::Level::trace)) {
2073
            BinaryData changeset_data = uc.changeset.get_first_chunk();
2074
            if (changeset_data.size() < 1024) {
2075
                logger.trace(util::LogCategory::changeset, "Changeset: %1",
2076
                             _impl::clamped_hex_dump(changeset_data)); // Throws
2077
            }
2078
            else {
2079
                logger.trace(util::LogCategory::changeset, "Changeset(comp): %1 %2", changeset_data.size(),
2080
                             protocol.compressed_hex_dump(changeset_data));
2081
            }
2082

2083
#if REALM_DEBUG
2084
            ChunkedBinaryInputStream in{changeset_data};
2085
            Changeset log;
2086
            try {
2087
                parse_changeset(in, log);
2088
                std::stringstream ss;
2089
                log.print(ss);
2090
                logger.trace(util::LogCategory::changeset, "Changeset (parsed):\n%1", ss.str());
2091
            }
2092
            catch (const BadChangesetError& err) {
43,560✔
2093
                logger.error(util::LogCategory::changeset, "Unable to parse changeset: %1", err.what());
43,560✔
2094
            }
43,560✔
2095
#endif
43,560✔
2096
        }
43,560✔
2097

43,560✔
2098
#if 0 // Upload log compaction is currently not implemented
43,560✔
2099
        if (!get_client().m_disable_upload_compaction) {
2100
            ChangesetEncoder::Buffer encode_buffer;
59,066✔
2101

59,066✔
2102
            {
59,066✔
2103
                // Upload compaction only takes place within single changesets to
59,066✔
2104
                // avoid another client seeing inconsistent snapshots.
59,066✔
2105
                ChunkedBinaryInputStream stream{uc.changeset};
59,066✔
2106
                Changeset changeset;
59,066✔
2107
                parse_changeset(stream, changeset); // Throws
2108
                // FIXME: What is the point of setting these? How can compaction care about them?
2109
                changeset.version = uc.progress.client_version;
59,066✔
2110
                changeset.last_integrated_remote_version = uc.progress.last_integrated_server_version;
59,066✔
2111
                changeset.origin_timestamp = uc.origin_timestamp;
2112
                changeset.origin_file_ident = uc.origin_file_ident;
2113

2114
                compact_changesets(&changeset, 1);
17,264✔
2115
                encode_changeset(changeset, encode_buffer);
17,264✔
2116

17,264✔
2117
                logger.debug(util::LogCategory::changeset, "Upload compaction: original size = %1, compacted size = %2", uc.changeset.size(),
17,264✔
2118
                             encode_buffer.size()); // Throws
17,264✔
2119
            }
2120

17,264✔
2121
            upload_message_builder.add_changeset(
17,264✔
2122
                uc.progress.client_version, uc.progress.last_integrated_server_version, uc.origin_timestamp,
2123
                uc.origin_file_ident, BinaryData{encode_buffer.data(), encode_buffer.size()}); // Throws
17,264✔
2124
        }
17,264✔
2125
        else
17,264✔
2126
#endif
17,264✔
2127
        {
17,264✔
2128
            upload_message_builder.add_changeset(uc.progress.client_version,
2129
                                                 uc.progress.last_integrated_server_version, uc.origin_timestamp,
17,264✔
2130
                                                 uc.origin_file_ident,
2131
                                                 uc.changeset); // Throws
2132
        }
17,264✔
2133
    }
17,264✔
2134

2135
    int protocol_version = m_conn.get_negotiated_protocol_version();
2136
    OutputBuffer& out = m_conn.get_output_buffer();
2137
    session_ident_type session_ident = get_ident();
6,508✔
2138
    upload_message_builder.make_upload_message(protocol_version, out, session_ident, progress_client_version,
6,508✔
2139
                                               progress_server_version,
6,508✔
2140
                                               locked_server_version); // Throws
6,508✔
2141
    m_conn.initiate_write_message(out, this);                          // Throws
2142

6,508✔
2143
    // Other messages may be waiting to be sent
2144
    enlist_to_send(); // Throws
6,508✔
2145
}
6,508✔
2146

6,508✔
2147

6,508✔
2148
void Session::send_mark_message()
6,508✔
2149
{
2150
    REALM_ASSERT_EX(m_state == Active, m_state);
6,508✔
2151
    REALM_ASSERT(m_ident_message_sent);
6,508✔
2152
    REALM_ASSERT(!m_unbind_message_sent);
2153
    REALM_ASSERT_3(m_target_download_mark, >, m_last_download_mark_sent);
2154

2155
    request_ident_type request_ident = m_target_download_mark;
30✔
2156
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
30✔
2157

30✔
2158
    ClientProtocol& protocol = m_conn.get_client_protocol();
30✔
2159
    OutputBuffer& out = m_conn.get_output_buffer();
30✔
2160
    session_ident_type session_ident = get_ident();
30✔
2161
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
2162
    m_conn.initiate_write_message(out, this);                      // Throws
30✔
2163

30✔
2164
    m_last_download_mark_sent = request_ident;
30✔
2165

30✔
2166
    // Other messages may be waiting to be sent
2167
    enlist_to_send(); // Throws
30✔
2168
}
30✔
2169

30✔
2170

2171
void Session::send_unbind_message()
30✔
2172
{
30✔
2173
    REALM_ASSERT_EX(m_state == Deactivating || m_error_message_received || m_suspended, m_state);
30✔
2174
    REALM_ASSERT(m_bind_message_sent);
30✔
2175
    REALM_ASSERT(!m_unbind_message_sent);
30✔
2176

2177
    logger.debug("Sending: UNBIND"); // Throws
30✔
2178

30✔
2179
    ClientProtocol& protocol = m_conn.get_client_protocol();
30✔
2180
    OutputBuffer& out = m_conn.get_output_buffer();
2181
    session_ident_type session_ident = get_ident();
2182
    protocol.make_unbind_message(out, session_ident); // Throws
2183
    m_conn.initiate_write_message(out, this);         // Throws
52✔
2184

52✔
2185
    m_unbind_message_sent = true;
2186
}
52✔
2187

52✔
2188

52✔
2189
void Session::send_json_error_message()
52✔
2190
{
52✔
2191
    REALM_ASSERT_EX(m_state == Active, m_state);
2192
    REALM_ASSERT(m_ident_message_sent);
52✔
2193
    REALM_ASSERT(!m_unbind_message_sent);
52✔
2194
    REALM_ASSERT(m_error_to_send);
52✔
2195
    REALM_ASSERT(m_client_error);
2196

52✔
2197
    ClientProtocol& protocol = m_conn.get_client_protocol();
52✔
2198
    OutputBuffer& out = m_conn.get_output_buffer();
2199
    session_ident_type session_ident = get_ident();
52✔
2200
    auto protocol_error = m_client_error->error_for_server;
52✔
2201

2202
    auto message = util::format("%1", m_client_error->to_status());
52✔
2203
    logger.info("Sending: ERROR \"%1\" (error_code=%2, session_ident=%3)", message, static_cast<int>(protocol_error),
52✔
2204
                session_ident); // Throws
2205

2206
    nlohmann::json error_body_json;
3,656✔
2207
    error_body_json["message"] = std::move(message);
2208
    protocol.make_json_error_message(out, session_ident, static_cast<int>(protocol_error),
2209
                                     error_body_json.dump()); // Throws
3,656✔
2210
    m_conn.initiate_write_message(out, this);                 // Throws
2211

2212
    m_error_to_send = false;
2213
    enlist_to_send(); // Throws
3,656✔
2214
}
3,656✔
2215

3,280✔
2216

3,280✔
2217
void Session::send_test_command_message()
2218
{
376✔
2219
    REALM_ASSERT_EX(m_state == Active, m_state);
300✔
2220

300✔
2221
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
376✔
2222
                           [](const PendingTestCommand& command) {
376✔
2223
                               return command.pending;
376✔
2224
                           });
376✔
2225
    REALM_ASSERT(it != m_pending_test_commands.end());
376✔
2226

376✔
2227
    ClientProtocol& protocol = m_conn.get_client_protocol();
×
2228
    OutputBuffer& out = m_conn.get_output_buffer();
×
2229
    auto session_ident = get_ident();
2230

2231
    logger.info("Sending: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", it->body, session_ident, it->id);
376✔
2232
    protocol.make_test_command_message(out, session_ident, it->id, it->body);
2233

376✔
2234
    m_conn.initiate_write_message(out, this); // Throws;
376✔
2235
    it->pending = false;
376✔
2236

376✔
2237
    enlist_to_send();
376✔
2238
}
376✔
2239

376✔
2240
bool Session::client_reset_if_needed()
376✔
2241
{
376✔
2242
    // Regardless of what happens, once we return from this function we will
376✔
2243
    // no longer be in the middle of a client reset
2244
    m_performing_client_reset = false;
376✔
2245

376✔
2246
    // Even if we end up not actually performing a client reset, consume the
376✔
2247
    // config to ensure that the resources it holds are released
2248
    auto client_reset_config = std::exchange(get_client_reset_config(), std::nullopt);
2249
    if (!client_reset_config) {
2250
        return false;
376✔
2251
    }
376✔
2252

2253
    auto on_flx_version_complete = [this](int64_t version) {
376✔
2254
        this->on_flx_sync_version_complete(version);
296✔
2255
    };
296✔
2256
    bool did_reset = client_reset::perform_client_reset(
2257
        logger, *get_db(), *client_reset_config->fresh_copy, client_reset_config->mode,
376✔
2258
        std::move(client_reset_config->notify_before_client_reset),
2259
        std::move(client_reset_config->notify_after_client_reset), m_client_file_ident, get_flx_subscription_store(),
2260
        on_flx_version_complete, client_reset_config->recovery_is_allowed);
376✔
2261
    if (!did_reset) {
268✔
2262
        return false;
268✔
2263
    }
2264

376✔
2265
    // The fresh Realm has been used to reset the state
376✔
2266
    logger.debug("Client reset is completed, path=%1", get_realm_path()); // Throws
2267

2268
    SaltedFileIdent client_file_ident;
3,716✔
2269
    bool has_pending_client_reset = false;
3,716✔
2270
    get_history().get_status(m_last_version_available, client_file_ident, m_progress,
3,716✔
2271
                             &has_pending_client_reset); // Throws
2272
    REALM_ASSERT_3(m_client_file_ident.ident, ==, client_file_ident.ident);
2273
    REALM_ASSERT_3(m_client_file_ident.salt, ==, client_file_ident.salt);
2274
    REALM_ASSERT_EX(m_progress.download.last_integrated_client_version == 0,
2275
                    m_progress.download.last_integrated_client_version);
3,716✔
2276
    REALM_ASSERT_EX(m_progress.upload.client_version == 0, m_progress.upload.client_version);
60✔
2277
    logger.trace("last_version_available  = %1", m_last_version_available); // Throws
2278

3,656✔
2279
    m_upload_progress = m_progress.upload;
3,656✔
2280
    m_download_progress = m_progress.download;
3,656✔
2281
    init_progress_handler();
×
2282
    // In recovery mode, there may be new changesets to upload and nothing left to download.
×
2283
    // In FLX DiscardLocal mode, there may be new commits due to subscription handling.
3,656✔
2284
    // For both, we want to allow uploads again without needing external changes to download first.
×
2285
    m_allow_upload = true;
×
2286
    REALM_ASSERT_EX(m_last_version_selected_for_upload == 0, m_last_version_selected_for_upload);
3,656✔
2287

×
2288
    if (has_pending_client_reset) {
×
2289
        handle_pending_client_reset_acknowledgement();
2290
    }
3,656✔
2291

2292
    update_subscription_version_info();
3,656✔
2293

2294
    // If a migration or rollback is in progress, mark it complete when client reset is completed.
×
2295
    if (auto migration_store = get_migration_store()) {
×
2296
        migration_store->complete_migration_or_rollback();
×
2297
    }
2298

2299
    return true;
2300
}
3,656✔
2301

3,656✔
2302
Status Session::receive_ident_message(SaltedFileIdent client_file_ident)
3,656✔
2303
{
3,656✔
2304
    logger.debug("Received: IDENT(client_file_ident=%1, client_file_ident_salt=%2)", client_file_ident.ident,
3,656✔
2305
                 client_file_ident.salt); // Throws
80✔
2306

80✔
2307
    // Ignore the message if the deactivation process has been initiated,
80✔
2308
    // because in that case, the associated Realm and SessionWrapper must
80✔
2309
    // not be accessed any longer.
80✔
2310
    if (m_state != Active)
80✔
2311
        return Status::OK(); // Success
3,576✔
2312

3,280✔
2313
    bool legal_at_this_time = (m_bind_message_sent && !have_client_file_ident() && !m_error_message_received &&
3,280✔
2314
                               !m_unbound_message_received);
3,280✔
2315
    if (REALM_UNLIKELY(!legal_at_this_time)) {
3,280✔
2316
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received IDENT message when it was not legal"};
3,280✔
2317
    }
3,280✔
2318
    if (REALM_UNLIKELY(client_file_ident.ident < 1)) {
2319
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier in IDENT message"};
2320
    }
3,576✔
2321
    if (REALM_UNLIKELY(client_file_ident.salt == 0)) {
3,576✔
2322
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier salt in IDENT message"};
3,656✔
2323
    }
2324

2325
    m_client_file_ident = client_file_ident;
47,920✔
2326

2327
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
2328
        // Ready to send the IDENT message
2329
        ensure_enlisted_to_send(); // Throws
47,920✔
2330
        return Status::OK();       // Success
514✔
2331
    }
2332

47,406✔
2333
    // if a client reset happens, it will take care of setting the file ident
47,406✔
2334
    // and if not, we do it here
2335
    bool did_client_reset = false;
47,406✔
2336
    try {
45,792✔
2337
        did_client_reset = client_reset_if_needed();
2338
    }
2339
    catch (const std::exception& e) {
47,406✔
2340
        auto err_msg = util::format("A fatal error occurred during client reset: '%1'", e.what());
47,406✔
2341
        logger.error(err_msg.c_str());
47,406✔
2342
        SessionErrorInfo err_info(Status{ErrorCodes::AutoClientResetFailed, err_msg}, IsFatal{true});
45,260✔
2343
        suspend(err_info);
2344
        return Status::OK();
47,406✔
2345
    }
47,406✔
2346
    if (!did_client_reset) {
3,454✔
2347
        get_history().set_client_file_ident(client_file_ident,
3,454✔
2348
                                            m_fix_up_object_ids); // Throws
3,454✔
2349
        m_progress.download.last_integrated_client_version = 0;
3,454✔
2350
        m_progress.upload.client_version = 0;
3,454✔
2351
        m_last_version_selected_for_upload = 0;
3,454✔
2352
    }
3,454✔
2353

3,454✔
2354
    // Ready to send the IDENT message
3,454✔
2355
    ensure_enlisted_to_send(); // Throws
43,952✔
2356
    return Status::OK();       // Success
43,952✔
2357
}
43,952✔
2358

43,952✔
2359
Status Session::receive_download_message(const DownloadMessage& message)
43,952✔
2360
{
43,952✔
2361
    // Ignore the message if the deactivation process has been initiated,
43,952✔
2362
    // because in that case, the associated Realm and SessionWrapper must
43,952✔
2363
    // not be accessed any longer.
43,952✔
2364
    if (m_state != Active)
43,952✔
2365
        return Status::OK();
2366

2367
    bool is_flx = m_conn.is_flx_sync_connection();
2368
    int64_t query_version = is_flx ? *message.query_version : 0;
47,406✔
2369

×
2370
    if (!is_flx || query_version > 0)
×
2371
        enable_progress_notifications();
×
2372

2373
    // If this is a PBS connection, then every download message is its own complete batch.
47,406✔
2374
    bool last_in_batch = is_flx ? *message.last_in_batch : true;
47,406✔
2375
    auto batch_state = last_in_batch ? sync::DownloadBatchState::LastInBatch : sync::DownloadBatchState::MoreToCome;
2✔
2376
    if (is_steady_state_download_message(batch_state, query_version))
2✔
2377
        batch_state = DownloadBatchState::SteadyState;
47,404✔
2378

×
2379
    auto&& progress = message.progress;
×
2380
    if (is_flx) {
×
2381
        logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
2382
                     "latest_server_version=%3, latest_server_version_salt=%4, "
47,404✔
2383
                     "upload_client_version=%5, upload_server_version=%6, progress_estimate=%7, "
47,404✔
2384
                     "last_in_batch=%8, query_version=%9, num_changesets=%10, ...)",
48,902✔
2385
                     progress.download.server_version, progress.download.last_integrated_client_version,
2386
                     progress.latest_server_version.version, progress.latest_server_version.salt,
2387
                     progress.upload.client_version, progress.upload.last_integrated_server_version,
45,558✔
2388
                     message.progress_estimate, last_in_batch, query_version, message.changesets.size()); // Throws
45,558✔
2389
    }
2390
    else {
45,558✔
2391
        logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
45,558✔
2392
                     "latest_server_version=%3, latest_server_version_salt=%4, "
×
2393
                     "upload_client_version=%5, upload_server_version=%6, "
×
2394
                     "downloadable_bytes=%7, num_changesets=%8, ...)",
×
2395
                     progress.download.server_version, progress.download.last_integrated_client_version,
×
2396
                     progress.latest_server_version.version, progress.latest_server_version.salt,
45,558✔
2397
                     progress.upload.client_version, progress.upload.last_integrated_server_version,
2398
                     message.downloadable_bytes, message.changesets.size()); // Throws
2399
    }
45,558✔
2400

45,558✔
2401
    // Ignore download messages when the client detects an error. This is to prevent transforming the same bad
45,558✔
2402
    // changeset over and over again.
45,558✔
2403
    if (m_client_error) {
×
2404
        logger.debug("Ignoring download message because the client detected an integration error");
×
2405
        return Status::OK();
×
2406
    }
×
2407

×
2408
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
×
2409
    if (REALM_UNLIKELY(!legal_at_this_time)) {
45,558✔
2410
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received DOWNLOAD message when it was not legal"};
2411
    }
2412
    if (auto status = check_received_sync_progress(progress); REALM_UNLIKELY(!status.is_ok())) {
45,558✔
2413
        logger.error("Bad sync progress received (%1)", status);
45,558✔
2414
        return status;
45,558✔
2415
    }
×
2416

×
2417
    version_type server_version = m_progress.download.server_version;
×
2418
    version_type last_integrated_client_version = m_progress.download.last_integrated_client_version;
×
2419
    for (const RemoteChangeset& changeset : message.changesets) {
45,558✔
2420
        // Check that per-changeset server version is strictly increasing, except in FLX sync where the server
2421
        // version must be increasing, but can stay the same during bootstraps.
47,404✔
2422
        bool good_server_version = m_is_flx_sync_session ? (changeset.remote_version >= server_version)
47,404✔
2423
                                                         : (changeset.remote_version > server_version);
47,404✔
2424
        // Each server version cannot be greater than the one in the header of the download message.
16✔
2425
        good_server_version = good_server_version && (changeset.remote_version <= progress.download.server_version);
16✔
2426
        if (!good_server_version) {
47,388✔
2427
            return {ErrorCodes::SyncProtocolInvariantFailed,
2428
                    util::format("Bad server version in changeset header (DOWNLOAD) (%1, %2, %3)",
47,388✔
2429
                                 changeset.remote_version, server_version, progress.download.server_version)};
3,440✔
2430
        }
2431
        server_version = changeset.remote_version;
47,388✔
2432
        // Check that per-changeset last integrated client version is "weakly"
2,136✔
2433
        // increasing.
2,136✔
2434
        bool good_client_version =
2,136✔
2435
            (changeset.last_integrated_local_version >= last_integrated_client_version &&
2436
             changeset.last_integrated_local_version <= progress.download.last_integrated_client_version);
45,252✔
2437
        if (!good_client_version) {
45,252✔
2438
            return {ErrorCodes::SyncProtocolInvariantFailed,
2439
                    util::format("Bad last integrated client version in changeset header (DOWNLOAD) "
45,252✔
2440
                                 "(%1, %2, %3)",
45,252✔
2441
                                 changeset.last_integrated_local_version, last_integrated_client_version,
45,252✔
2442
                                 progress.download.last_integrated_client_version)};
×
2443
        }
×
2444
        last_integrated_client_version = changeset.last_integrated_local_version;
45,252✔
2445
        // Server shouldn't send our own changes, and zero is not a valid client
2446
        // file identifier.
2447
        bool good_file_ident =
2448
            (changeset.origin_file_ident > 0 && changeset.origin_file_ident != m_client_file_ident.ident);
45,252✔
2449
        if (!good_file_ident) {
45,252✔
2450
            return {ErrorCodes::SyncProtocolInvariantFailed,
45,252✔
2451
                    util::format("Bad origin file identifier in changeset header (DOWNLOAD)",
2452
                                 changeset.origin_file_ident)};
2453
        }
16,462✔
2454
    }
16,462✔
2455

2456
    auto hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageReceived, progress, query_version,
2457
                                       batch_state, message.changesets.size());
2458
    if (hook_action == SyncClientHookAction::EarlyReturn) {
2459
        return Status::OK();
16,462✔
2460
    }
56✔
2461
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
2462

16,406✔
2463
    if (is_flx)
16,406✔
2464
        update_download_estimate(message.progress_estimate);
10✔
2465

10✔
2466
    if (process_flx_bootstrap_message(progress, batch_state, query_version, message.changesets)) {
16,396✔
2467
        clear_resumption_delay_state();
16,396✔
2468
        return Status::OK();
16,396✔
2469
    }
×
2470

×
2471
    uint64_t downloadable_bytes = is_flx ? 0 : message.downloadable_bytes;
×
2472
    initiate_integrate_changesets(downloadable_bytes, batch_state, progress, message.changesets); // Throws
×
2473

×
2474
    hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
×
2475
                                  batch_state, message.changesets.size());
2476
    if (hook_action == SyncClientHookAction::EarlyReturn) {
16,396✔
2477
        return Status::OK();
16,396✔
2478
    }
16,396✔
2479
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
2480

16,396✔
2481
    // When we receive a DOWNLOAD message successfully, we can clear the backoff timer value used to reconnect
16,396✔
2482
    // after a retryable session error.
2483
    clear_resumption_delay_state();
2484
    return Status::OK();
2485
}
2486

2487
Status Session::receive_mark_message(request_ident_type request_ident)
4,424✔
2488
{
4,424✔
2489
    logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
2490

4,424✔
2491
    // Ignore the message if the deactivation process has been initiated,
4,424✔
2492
    // because in that case, the associated Realm and SessionWrapper must
×
2493
    // not be accessed any longer.
×
2494
    if (m_state != Active)
2495
        return Status::OK(); // Success
2496

2497
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
2498
    if (REALM_UNLIKELY(!legal_at_this_time)) {
2499
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received MARK message when it was not legal"};
4,424!
2500
    }
2501
    bool good_request_ident =
4,424✔
2502
        (request_ident <= m_last_download_mark_sent && request_ident > m_last_download_mark_received);
2503
    if (REALM_UNLIKELY(!good_request_ident)) {
2504
        return {
4,424✔
2505
            ErrorCodes::SyncProtocolInvariantFailed,
2506
            util::format(
2507
                "Received MARK message with invalid request identifer (last mark sent: %1 last mark received: %2)",
4,422✔
2508
                m_last_download_mark_sent, m_last_download_mark_received)};
2509
    }
4,422✔
2510

2511
    m_server_version_at_last_download_mark = m_progress.download.server_version;
4,424✔
2512
    m_last_download_mark_received = request_ident;
4,424✔
2513
    check_for_download_completion(); // Throws
2514

2515
    return Status::OK(); // Success
2516
}
20✔
2517

20✔
2518

2519
// The caller (Connection) must discard the session if the session has become
2520
// deactivated upon return.
2521
Status Session::receive_unbound_message()
20✔
2522
{
20✔
2523
    logger.debug("Received: UNBOUND");
20✔
2524

20✔
2525
    bool legal_at_this_time = (m_unbind_message_sent && !m_error_message_received && !m_unbound_message_received);
20✔
2526
    if (REALM_UNLIKELY(!legal_at_this_time)) {
2527
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received UNBOUND message when it was not legal"};
2528
    }
2529

2530
    // The fact that the UNBIND message has been sent, but an ERROR message has
712✔
2531
    // not been received, implies that the deactivation process must have been
712✔
2532
    // initiated, so this session must be in the Deactivating state or the session
712✔
2533
    // has been suspended because of a client side error.
2534
    REALM_ASSERT_EX(m_state == Deactivating || m_suspended, m_state);
712✔
2535

712✔
2536
    m_unbound_message_received = true;
×
2537

×
2538
    // Detect completion of the unbinding process
2539
    if (m_unbind_message_send_complete && m_state == Deactivating) {
712✔
2540
        // The deactivation process completes when the unbinding process
712✔
2541
        // completes.
712✔
2542
        complete_deactivation(); // Throws
×
2543
        // Life cycle state is now Deactivated
×
2544
    }
×
2545

×
2546
    return Status::OK(); // Success
2547
}
2548

2549

712✔
2550
Status Session::receive_query_error_message(int error_code, std::string_view message, int64_t query_version)
710✔
2551
{
710✔
2552
    logger.info("Received QUERY_ERROR \"%1\" (error_code=%2, query_version=%3)", message, error_code, query_version);
8✔
2553
    // Ignore the message if the deactivation process has been initiated,
8✔
2554
    // because in that case, the associated Realm and SessionWrapper must
710✔
2555
    // not be accessed any longer.
2556
    if (m_state == Active) {
2557
        on_flx_sync_error(query_version, message); // throws
2558
    }
704✔
2559
    return Status::OK();
2560
}
2561

44✔
2562
// The caller (Connection) must discard the session if the session has become
44✔
2563
// deactivated upon return.
44✔
2564
Status Session::receive_error_message(const ProtocolErrorInfo& info)
44✔
2565
{
44✔
2566
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, error_action=%4)", info.message,
44✔
2567
                info.raw_error_code, info.is_fatal, info.server_requests_action); // Throws
2568

660✔
2569
    bool legal_at_this_time = (m_bind_message_sent && !m_error_message_received && !m_unbound_message_received);
2570
    if (REALM_UNLIKELY(!legal_at_this_time)) {
68✔
2571
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received ERROR message when it was not legal"};
68✔
2572
    }
68✔
2573

68✔
2574
    auto protocol_error = static_cast<ProtocolError>(info.raw_error_code);
2575
    auto status = protocol_error_to_status(protocol_error, info.message);
68✔
2576
    if (status != ErrorCodes::UnknownError && REALM_UNLIKELY(!is_session_level_error(protocol_error))) {
68✔
2577
        return {ErrorCodes::SyncProtocolInvariantFailed,
2578
                util::format("Received ERROR message for session with non-session-level error code %1",
68✔
2579
                             info.raw_error_code)};
68✔
2580
    }
2581

592✔
2582
    // Can't process debug hook actions once the Session is undergoing deactivation, since
592✔
2583
    // the SessionWrapper may not be available
592✔
2584
    if (m_state == Active) {
660✔
2585
        auto debug_action = call_debug_hook(SyncClientHookEvent::ErrorMessageReceived, info);
2586
        if (debug_action == SyncClientHookAction::EarlyReturn) {
2587
            return Status::OK();
672✔
2588
        }
672✔
2589
    }
672✔
2590

672✔
2591
    // For compensating write errors, we need to defer raising them to the SDK until after the server version
2592
    // containing the compensating write has appeared in a download message.
672✔
2593
    if (status == ErrorCodes::SyncCompensatingWrite) {
2594
        // If the client is not active, the compensating writes will not be processed now, but will be
2595
        // sent again the next time the client connects
672✔
2596
        if (m_state == Active) {
2597
            REALM_ASSERT(info.compensating_write_server_version.has_value());
2598
            m_pending_compensating_write_errors.push_back(info);
2599
        }
2✔
2600
        return Status::OK();
2601
    }
2602

2603
    if (protocol_error == ProtocolError::schema_version_changed) {
2✔
2604
        // Enable upload immediately if the session is still active.
2605
        if (m_state == Active) {
2✔
2606
            auto wt = get_db()->start_write();
2607
            _impl::sync_schema_migration::track_sync_schema_migration(*wt, *info.previous_schema_version);
2608
            wt->commit();
2609
            // Notify SyncSession a schema migration is required.
672✔
2610
            on_connection_state_changed(m_conn.get_state(), SessionErrorInfo{info});
670✔
2611
        }
670✔
2612
        // Keep the session active to upload any unsynced changes.
670✔
2613
        return Status::OK();
670✔
2614
    }
2615

672✔
2616
    m_error_message_received = true;
58✔
2617
    suspend(SessionErrorInfo{info, std::move(status)});
58✔
2618
    return Status::OK();
2619
}
2620

672✔
2621
void Session::suspend(const SessionErrorInfo& info)
670✔
2622
{
672✔
2623
    REALM_ASSERT(!m_suspended);
2624
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
2625
    logger.debug("Suspended"); // Throws
52✔
2626

52✔
2627
    m_suspended = true;
52✔
2628

52✔
2629
    // Detect completion of the unbinding process
52✔
2630
    if (m_unbind_message_send_complete && m_error_message_received) {
52✔
2631
        // The fact that the UNBIND message has been sent, but we are not being suspended because
52✔
2632
        // we received an ERROR message implies that the deactivation process must
×
2633
        // have been initiated, so this session must be in the Deactivating state.
×
2634
        REALM_ASSERT_EX(m_state == Deactivating, m_state);
×
2635

2636
        // The deactivation process completes when the unbinding process
52✔
2637
        // completes.
52✔
2638
        complete_deactivation(); // Throws
2639
        // Life cycle state is now Deactivated
52✔
2640
    }
52✔
2641

2642
    // Notify the application of the suspension of the session if the session is
2643
    // still in the Active state
58✔
2644
    if (m_state == Active) {
58✔
2645
        call_debug_hook(SyncClientHookEvent::SessionSuspended, info);
2646
        m_conn.one_less_active_unsuspended_session(); // Throws
58✔
2647
        on_suspended(info);                           // Throws
58✔
2648
    }
58✔
2649

58✔
2650
    if (!info.is_fatal) {
2651
        begin_resumption_delay(info);
2652
    }
2653

26✔
2654
    // Ready to send the UNBIND message, if it has not been sent already
26✔
2655
    if (!m_unbind_message_sent)
58✔
2656
        ensure_enlisted_to_send(); // Throws
58✔
2657
}
58✔
2658

12✔
2659
Status Session::receive_test_command_response(request_ident_type ident, std::string_view body)
46✔
2660
{
×
2661
    logger.info("Received: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", body, m_ident, ident);
2662
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
46✔
2663
                           [&](const PendingTestCommand& command) {
46✔
2664
                               return command.id == ident;
46✔
2665
                           });
58✔
2666
    if (it == m_pending_test_commands.end()) {
2667
        return {ErrorCodes::SyncProtocolInvariantFailed,
2668
                util::format("Received test command response for a non-existent ident %1", ident)};
47,388✔
2669
    }
47,388✔
2670

×
2671
    it->promise.emplace_value(std::string{body});
×
2672
    m_pending_test_commands.erase(it);
×
2673

47,388✔
2674
    return Status::OK();
2675
}
2676

47,404✔
2677
void Session::begin_resumption_delay(const ProtocolErrorInfo& error_info)
47,404✔
2678
{
47,404✔
2679
    REALM_ASSERT(!m_try_again_activation_timer);
47,404✔
2680

47,404✔
2681
    m_try_again_delay_info.update(static_cast<sync::ProtocolError>(error_info.raw_error_code),
×
2682
                                  error_info.resumption_delay_interval);
×
2683
    auto try_again_interval = m_try_again_delay_info.delay_interval();
×
2684
    if (ProtocolError(error_info.raw_error_code) == ProtocolError::session_closed) {
×
2685
        // FIXME With compensating writes the server sends this error after completing a bootstrap. Doing the
47,404✔
2686
        // normal backoff behavior would result in waiting up to 5 minutes in between each query change which is
×
2687
        // not acceptable latency. So for this error code alone, we hard-code a 1 second retry interval.
×
2688
        try_again_interval = std::chrono::milliseconds{1000};
×
2689
    }
×
2690
    logger.debug("Will attempt to resume session after %1 milliseconds", try_again_interval.count());
47,404✔
2691
    m_try_again_activation_timer = get_client().create_timer(try_again_interval, [this](Status status) {
×
2692
        if (status == ErrorCodes::OperationAborted)
×
2693
            return;
×
2694
        else if (!status.is_ok())
×
2695
            throw Exception(status);
47,404✔
2696

×
2697
        m_try_again_activation_timer.reset();
×
2698
        cancel_resumption_delay();
×
2699
    });
×
2700
}
47,404✔
2701

×
2702
void Session::clear_resumption_delay_state()
×
2703
{
×
2704
    if (m_try_again_activation_timer) {
×
2705
        logger.debug("Clearing resumption delay state after successful download");
47,404✔
2706
        m_try_again_delay_info.reset();
×
2707
    }
×
2708
}
×
2709

×
2710
Status Session::check_received_sync_progress(const SyncProgress& progress) noexcept
×
2711
{
47,404✔
2712
    const SyncProgress& a = m_progress;
×
2713
    const SyncProgress& b = progress;
×
2714
    std::string message;
×
2715
    if (b.latest_server_version.version < a.latest_server_version.version) {
×
2716
        message = util::format("Latest server version in download messages must be weakly increasing throughout a "
×
2717
                               "session (current: %1, received: %2)",
47,404✔
2718
                               a.latest_server_version.version, b.latest_server_version.version);
×
2719
    }
×
2720
    if (b.upload.client_version < a.upload.client_version) {
×
2721
        message = util::format("Last integrated client version in download messages must be weakly increasing "
×
2722
                               "throughout a session (current: %1, received: %2)",
×
2723
                               a.upload.client_version, b.upload.client_version);
2724
    }
47,404✔
2725
    if (b.upload.client_version > m_last_version_available) {
47,402✔
2726
        message = util::format("Last integrated client version on server cannot be greater than the latest client "
47,402✔
2727
                               "version in existence (current: %1, received: %2)",
2✔
2728
                               m_last_version_available, b.upload.client_version);
47,404✔
2729
    }
2730
    if (b.download.server_version < a.download.server_version) {
2731
        message =
2732
            util::format("Download cursor must be weakly increasing throughout a session (current: %1, received: %2)",
79,504✔
2733
                         a.download.server_version, b.download.server_version);
79,504✔
2734
    }
79,504✔
2735
    if (b.download.server_version > b.latest_server_version.version) {
47,910✔
2736
        message = util::format(
47,910✔
2737
            "Download cursor cannot be greater than the latest server version in existence (cursor: %1, latest: %2)",
2738
            b.download.server_version, b.latest_server_version.version);
2739
    }
31,594✔
2740
    if (b.download.last_integrated_client_version < a.download.last_integrated_client_version) {
262✔
2741
        message = util::format(
2742
            "Last integrated client version on the server at the position in the server's history of the download "
2743
            "cursor must be weakly increasing throughout a session (current: %1, received: %2)",
31,332✔
2744
            a.download.last_integrated_client_version, b.download.last_integrated_client_version);
31,332✔
2745
    }
31,332✔
2746
    if (b.download.last_integrated_client_version > b.upload.client_version) {
5,188✔
2747
        message = util::format("Last integrated client version on the server in the position at the server's history "
2748
                               "of the download cursor cannot be greater than the latest client version integrated "
2749
                               "on the server (download: %1, upload: %2)",
26,144✔
2750
                               b.download.last_integrated_client_version, b.upload.client_version);
26,144✔
2751
    }
26,144✔
2752
    if (b.download.server_version < b.upload.last_integrated_server_version) {
11,194✔
2753
        message = util::format(
2754
            "The server version of the download cursor cannot be less than the server version integrated in the "
14,950✔
2755
            "latest client version acknowledged by the server (download: %1, upload: %2)",
14,950✔
2756
            b.download.server_version, b.upload.last_integrated_server_version);
14,950✔
2757
    }
2758

2759
    if (message.empty()) {
2760
        return Status::OK();
63,546✔
2761
    }
63,546✔
2762
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
63,546✔
2763
}
63,546✔
2764

46,912✔
2765

16,634✔
2766
void Session::check_for_upload_completion()
392✔
2767
{
16,242✔
2768
    REALM_ASSERT_EX(m_state == Active, m_state);
×
2769
    if (!m_upload_completion_notification_requested) {
16,242✔
2770
        return;
16,242✔
2771
    }
2772

2773
    // during an ongoing client reset operation, we never upload anything
4,624✔
2774
    if (m_performing_client_reset)
4,624✔
2775
        return;
4,624✔
2776

16,242✔
2777
    // Upload process must have reached end of history
16,242✔
2778
    REALM_ASSERT_3(m_upload_progress.client_version, <=, m_last_version_available);
2779
    bool scan_complete = (m_upload_progress.client_version == m_last_version_available);
2780
    if (!scan_complete)
2781
        return;
2782

2783
    // All uploaded changesets must have been acknowledged by the server
2784
    REALM_ASSERT_3(m_progress.upload.client_version, <=, m_last_version_selected_for_upload);
2785
    bool all_uploads_accepted = (m_progress.upload.client_version == m_last_version_selected_for_upload);
2786
    if (!all_uploads_accepted)
2787
        return;
2788

2789
    m_upload_completion_notification_requested = false;
2790
    on_upload_completion(); // Throws
2791
}
2792

2793

2794
void Session::check_for_download_completion()
2795
{
2796
    REALM_ASSERT_3(m_target_download_mark, >=, m_last_download_mark_received);
2797
    REALM_ASSERT_3(m_last_download_mark_received, >=, m_last_triggering_download_mark);
2798
    if (m_last_download_mark_received == m_last_triggering_download_mark)
2799
        return;
2800
    if (m_last_download_mark_received < m_target_download_mark)
2801
        return;
2802
    if (m_download_progress.server_version < m_server_version_at_last_download_mark)
2803
        return;
2804
    m_last_triggering_download_mark = m_target_download_mark;
2805
    if (REALM_UNLIKELY(!m_allow_upload)) {
2806
        // Activate the upload process now, and enable immediate reactivation
2807
        // after a subsequent fast reconnect.
2808
        m_allow_upload = true;
2809
        ensure_enlisted_to_send(); // Throws
2810
    }
2811
    on_download_completion(); // Throws
2812
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc