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

realm / realm-core / github_pull_request_285284

21 Nov 2023 01:56PM UTC coverage: 91.664% (-0.03%) from 91.689%
github_pull_request_285284

Pull #7123

Evergreen

jedelbo
Merge branch 'master' into jf/mql
Pull Request #7123: PoC: Add MQL translation skeleton

92364 of 169228 branches covered (0.0%)

264 of 308 new or added lines in 5 files covered. (85.71%)

102 existing lines in 21 files now uncovered.

231504 of 252558 relevant lines covered (91.66%)

5988933.97 hits per line

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

85.44
/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/protocol.hpp>
12
#include <realm/util/assert.hpp>
13
#include <realm/util/basic_system_errors.hpp>
14
#include <realm/util/memory_stream.hpp>
15
#include <realm/util/platform_info.hpp>
16
#include <realm/util/random.hpp>
17
#include <realm/util/safe_int_ops.hpp>
18
#include <realm/util/scope_exit.hpp>
19
#include <realm/util/to_string.hpp>
20
#include <realm/util/uri.hpp>
21
#include <realm/version.hpp>
22

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

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

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

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

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

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

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

54

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

61

62
std::chrono::milliseconds ClientImpl::ReconnectInfo::delay_interval()
63
{
5,374✔
64
    if (scheduled_reset) {
5,374✔
65
        reset();
4✔
66
    }
4✔
67

2,888✔
68
    if (!m_backoff_state.triggering_error) {
5,374✔
69
        return std::chrono::milliseconds::zero();
4,150✔
70
    }
4,150✔
71

700✔
72
    switch (*m_backoff_state.triggering_error) {
1,224✔
73
        case ConnectionTerminationReason::closed_voluntarily:
80✔
74
            return std::chrono::milliseconds::zero();
80✔
75
        case ConnectionTerminationReason::server_said_do_not_reconnect:
20✔
76
            return std::chrono::milliseconds::max();
20✔
77
        default:
1,120✔
78
            if (m_reconnect_mode == ReconnectMode::testing) {
1,120✔
79
                return std::chrono::milliseconds::max();
900✔
80
            }
900✔
81

110✔
82
            REALM_ASSERT(m_reconnect_mode == ReconnectMode::normal);
220✔
83
            return m_backoff_state.delay_interval();
220✔
84
    }
1,224✔
85
}
1,224✔
86

87

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

1,526✔
132
    protocol = protocol_2;
3,400✔
133
    address = std::move(address_2);
3,400✔
134
    port = port_3;
3,400✔
135
    path = std::move(path_2);
3,400✔
136
    return true;
3,400✔
137
}
3,400✔
138

139

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

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

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

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

4,422✔
206
    REALM_ASSERT_EX(m_socket_provider, "Must provide socket provider in sync Client config");
8,982✔
207

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

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

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

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

234

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

254

255
void ClientImpl::drain_connections()
256
{
8,982✔
257
    logger.debug("Draining connections during sync client shutdown");
8,982✔
258
    for (auto& server_slot_pair : m_server_slots) {
5,684✔
259
        auto& server_slot = server_slot_pair.second;
2,388✔
260

1,126✔
261
        if (server_slot.connection) {
2,388✔
262
            auto& conn = server_slot.connection;
2,298✔
263
            conn->force_close();
2,298✔
264
        }
2,298✔
265
        else {
90✔
266
            for (auto& conn_pair : server_slot.alt_connections) {
46✔
267
                conn_pair.second->force_close();
4✔
268
            }
4✔
269
        }
90✔
270
    }
2,388✔
271
}
8,982✔
272

273

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

8,246✔
286
        std::lock_guard lock(m_drain_mutex);
16,484✔
287
        REALM_ASSERT(m_outstanding_posts);
16,484✔
288
        --m_outstanding_posts;
16,484✔
289
        m_drain_cv.notify_all();
16,484✔
290
    });
16,484✔
291
}
16,484✔
292

293

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

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

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

319

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

340

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

359

360
void Connection::cancel_reconnect_delay()
361
{
1,944✔
362
    REALM_ASSERT(m_activated);
1,944✔
363

1,154✔
364
    if (m_reconnect_delay_in_progress) {
1,944✔
365
        if (m_nonzero_reconnect_delay)
1,732✔
366
            logger.detail("Canceling reconnect delay"); // Throws
870✔
367

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

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

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

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

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

1,084✔
414
    m_force_closed = true;
2,302✔
415

1,084✔
416
    if (m_state != ConnectionState::disconnected) {
2,302✔
417
        voluntary_disconnect();
2,210✔
418
    }
2,210✔
419

1,084✔
420
    REALM_ASSERT_EX(m_state == ConnectionState::disconnected, m_state);
2,302✔
421
    if (m_reconnect_delay_in_progress || m_disconnect_delay_in_progress) {
2,302✔
422
        m_reconnect_disconnect_timer.reset();
92✔
423
        m_reconnect_delay_in_progress = false;
92✔
424
        m_disconnect_delay_in_progress = false;
92✔
425
    }
92✔
426

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

1,084✔
437
    for (auto& sess : to_close) {
1,162✔
438
        sess->force_close();
154✔
439
    }
154✔
440

1,084✔
441
    logger.debug("Force closed idle connection");
2,302✔
442
}
2,302✔
443

444

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

487

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

37,744✔
495
    using sf = SimulatedFailure;
72,724✔
496
    if (sf::check_trigger(sf::sync_client__read_head)) {
72,724✔
497
        close_due_to_client_side_error(
424✔
498
            {ErrorCodes::RuntimeError, "Simulated failure during sync client websocket read"}, IsFatal{false},
424✔
499
            ConnectionTerminationReason::read_or_write_error);
424✔
500
        return bool(m_websocket);
424✔
501
    }
424✔
502

37,474✔
503
    handle_message_received(data);
72,300✔
504
    return bool(m_websocket);
72,300✔
505
}
72,300✔
506

507

508
void Connection::websocket_error_handler()
509
{
524✔
510
    m_websocket_error_received = true;
524✔
511
}
524✔
512

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

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

356✔
627
    return bool(m_websocket);
644✔
628
}
644✔
629

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

3,924✔
638
    // If we've been force closed then we don't need/want to reconnect. Just return early here.
3,924✔
639
    if (m_force_closed) {
7,582✔
640
        return;
2,210✔
641
    }
2,210✔
642

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

2,338✔
652
    if (delay == std::chrono::milliseconds::zero()) {
4,452✔
653
        m_nonzero_reconnect_delay = false;
4,234✔
654
    }
4,234✔
655
    else {
218✔
656
        logger.detail("Allowing reconnection in %1 milliseconds", delay.count()); // Throws
218✔
657
        m_nonzero_reconnect_delay = true;
218✔
658
    }
218✔
659

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

671

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

1,694✔
679
    REALM_ASSERT(m_reconnect_delay_in_progress);
3,346✔
680
    m_reconnect_delay_in_progress = false;
3,346✔
681

1,694✔
682
    if (m_num_active_unsuspended_sessions > 0)
3,346✔
683
        initiate_reconnect(); // Throws
3,346✔
684
}
3,346✔
685

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

693
    Connection* conn;
694
    util::bind_ptr<LifecycleSentinel> sentinel;
695

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

1,650✔
702
        return conn->websocket_connected_handler(protocol);
3,258✔
703
    }
3,258✔
704

705
    void websocket_error_handler() override
706
    {
524✔
707
        if (sentinel->destroyed) {
524✔
708
            return;
×
709
        }
×
710

296✔
711
        conn->websocket_error_handler();
524✔
712
    }
524✔
713

714
    bool websocket_binary_message_received(util::Span<const char> data) override
715
    {
72,728✔
716
        if (sentinel->destroyed) {
72,728✔
717
            return false;
×
718
        }
×
719

37,746✔
720
        return conn->websocket_binary_message_received(data);
72,728✔
721
    }
72,728✔
722

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

356✔
729
        return conn->websocket_closed_handler(was_clean, error_code, msg);
644✔
730
    }
644✔
731
};
732

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

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

1,694✔
745
    // Watchdog
1,694✔
746
    initiate_connect_wait(); // Throws
3,346✔
747

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

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

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

783

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

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

800

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

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

816

817
void Connection::handle_connection_established()
818
{
3,258✔
819
    // Cancel connect timeout watchdog
1,650✔
820
    m_connect_timer.reset();
3,258✔
821

1,650✔
822
    m_state = ConnectionState::connected;
3,258✔
823

1,650✔
824
    milliseconds_type now = monotonic_clock_now();
3,258✔
825
    m_pong_wait_started_at = now; // Initially, no time was spent waiting for a PONG message
3,258✔
826
    initiate_ping_delay(now);     // Throws
3,258✔
827

1,650✔
828
    bool fast_reconnect = false;
3,258✔
829
    if (m_disconnect_has_occurred) {
3,258✔
830
        milliseconds_type time = now - m_disconnect_time;
942✔
831
        if (time <= m_client.m_fast_reconnect_limit)
942✔
832
            fast_reconnect = true;
942✔
833
    }
942✔
834

1,650✔
835
    for (auto& p : m_sessions) {
4,276✔
836
        Session& sess = *p.second;
4,276✔
837
        sess.connection_established(fast_reconnect); // Throws
4,276✔
838
    }
4,276✔
839

1,650✔
840
    report_connection_state_change(ConnectionState::connected); // Throws
3,258✔
841
}
3,258✔
842

843

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

860

861
void Connection::initiate_ping_delay(milliseconds_type now)
862
{
3,680✔
863
    REALM_ASSERT(!m_ping_delay_in_progress);
3,680✔
864
    REALM_ASSERT(!m_waiting_for_pong);
3,680✔
865
    REALM_ASSERT(!m_send_ping);
3,680✔
866

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

1,830✔
893

1,830✔
894
    m_ping_delay_in_progress = true;
3,680✔
895

1,830✔
896
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
3,680✔
897
        if (status == ErrorCodes::OperationAborted)
3,680✔
898
            return;
3,440✔
899
        else if (!status.is_ok())
240✔
900
            throw Exception(status);
×
901

92✔
902
        handle_ping_delay();                                    // Throws
240✔
903
    });                                                         // Throws
240✔
904
    logger.debug("Will emit a ping in %1 milliseconds", delay); // Throws
3,680✔
905
}
3,680✔
906

907

908
void Connection::handle_ping_delay()
909
{
238✔
910
    REALM_ASSERT(m_ping_delay_in_progress);
238✔
911
    m_ping_delay_in_progress = false;
238✔
912
    m_send_ping = true;
238✔
913

92✔
914
    initiate_pong_timeout(); // Throws
238✔
915

92✔
916
    if (m_state == ConnectionState::connected && !m_sending)
238✔
917
        send_next_message(); // Throws
210✔
918
}
238✔
919

920

921
void Connection::initiate_pong_timeout()
922
{
238✔
923
    REALM_ASSERT(!m_ping_delay_in_progress);
238✔
924
    REALM_ASSERT(!m_waiting_for_pong);
238✔
925
    REALM_ASSERT(m_send_ping);
238✔
926

92✔
927
    m_waiting_for_pong = true;
238✔
928
    m_pong_wait_started_at = monotonic_clock_now();
238✔
929

92✔
930
    milliseconds_type time = m_client.m_pong_keepalive_timeout;
238✔
931
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
238✔
932
        if (status == ErrorCodes::OperationAborted)
238✔
933
            return;
226✔
934
        else if (!status.is_ok())
12✔
935
            throw Exception(status);
×
936

6✔
937
        handle_pong_timeout(); // Throws
12✔
938
    });                        // Throws
12✔
939
}
238✔
940

941

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

950

951
void Connection::initiate_write_message(const OutputBuffer& out, Session* sess)
952
{
93,312✔
953
    // Stop sending messages if an websocket error was received.
47,694✔
954
    if (m_websocket_error_received)
93,312✔
955
        return;
×
956

47,694✔
957
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
93,312✔
958
        if (sentinel->destroyed) {
93,202✔
959
            return;
1,430✔
960
        }
1,430✔
961
        if (!status.is_ok()) {
91,772✔
962
            if (status != ErrorCodes::Error::OperationAborted) {
×
963
                // Write errors will be handled by the websocket_write_error_handler() callback
964
                logger.error("Connection: write failed %1: %2", status.code_string(), status.reason());
×
965
            }
×
966
            return;
×
967
        }
×
968
        handle_write_message(); // Throws
91,772✔
969
    });                         // Throws
91,772✔
970
    m_sending_session = sess;
93,312✔
971
    m_sending = true;
93,312✔
972
}
93,312✔
973

974

975
void Connection::handle_write_message()
976
{
91,766✔
977
    m_sending_session->message_sent(); // Throws
91,766✔
978
    if (m_sending_session->m_state == Session::Deactivated) {
91,766✔
979
        finish_session_deactivation(m_sending_session);
84✔
980
    }
84✔
981
    m_sending_session = nullptr;
91,766✔
982
    m_sending = false;
91,766✔
983
    send_next_message(); // Throws
91,766✔
984
}
91,766✔
985

986

987
void Connection::send_next_message()
988
{
148,992✔
989
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
148,992✔
990
    REALM_ASSERT(!m_sending_session);
148,992✔
991
    REALM_ASSERT(!m_sending);
148,992✔
992
    if (m_send_ping) {
148,992✔
993
        send_ping(); // Throws
226✔
994
        return;
226✔
995
    }
226✔
996
    while (!m_sessions_enlisted_to_send.empty()) {
207,404✔
997
        // The state of being connected is not supposed to be able to change
77,224✔
998
        // across this loop thanks to the "no callback reentrance" guarantee
77,224✔
999
        // provided by Websocket::async_write_text(), and friends.
77,224✔
1000
        REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
152,136✔
1001

77,224✔
1002
        Session& sess = *m_sessions_enlisted_to_send.front();
152,136✔
1003
        m_sessions_enlisted_to_send.pop_front();
152,136✔
1004
        sess.send_message(); // Throws
152,136✔
1005

77,224✔
1006
        if (sess.m_state == Session::Deactivated) {
152,136✔
1007
            finish_session_deactivation(&sess);
1,972✔
1008
        }
1,972✔
1009

77,224✔
1010
        // An enlisted session may choose to not send a message. In that case,
77,224✔
1011
        // we should pass the opportunity to the next enlisted session.
77,224✔
1012
        if (m_sending)
152,136✔
1013
            break;
93,498✔
1014
    }
152,136✔
1015
}
148,766✔
1016

1017

1018
void Connection::send_ping()
1019
{
226✔
1020
    REALM_ASSERT(!m_ping_delay_in_progress);
226✔
1021
    REALM_ASSERT(m_waiting_for_pong);
226✔
1022
    REALM_ASSERT(m_send_ping);
226✔
1023

86✔
1024
    m_send_ping = false;
226✔
1025
    if (m_reconnect_info.scheduled_reset)
226✔
1026
        m_ping_after_scheduled_reset_of_reconnect_info = true;
172✔
1027

86✔
1028
    m_last_ping_sent_at = monotonic_clock_now();
226✔
1029
    logger.debug("Sending: PING(timestamp=%1, rtt=%2)", m_last_ping_sent_at,
226✔
1030
                 m_previous_ping_rtt); // Throws
226✔
1031

86✔
1032
    ClientProtocol& protocol = get_client_protocol();
226✔
1033
    OutputBuffer& out = get_output_buffer();
226✔
1034
    protocol.make_ping(out, m_last_ping_sent_at, m_previous_ping_rtt); // Throws
226✔
1035
    initiate_write_ping(out);                                          // Throws
226✔
1036
    m_ping_sent = true;
226✔
1037
}
226✔
1038

1039

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

1058

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

1067

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

1075

1076
void Connection::initiate_disconnect_wait()
1077
{
4,372✔
1078
    REALM_ASSERT(!m_reconnect_delay_in_progress);
4,372✔
1079

2,076✔
1080
    if (m_disconnect_delay_in_progress) {
4,372✔
1081
        m_reconnect_disconnect_timer.reset();
2,096✔
1082
        m_disconnect_delay_in_progress = false;
2,096✔
1083
    }
2,096✔
1084

2,076✔
1085
    milliseconds_type time = m_client.m_connection_linger_time;
4,372✔
1086

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

1096

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

6✔
1104
    m_disconnect_delay_in_progress = false;
12✔
1105

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

1115

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

1124

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

276✔
1129
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
434✔
1130
}
434✔
1131

1132

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

294✔
1139
    involuntary_disconnect(std::move(error_info), reason); // Throw
522✔
1140
}
522✔
1141

1142

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

34✔
1150
    const auto reason = info.is_fatal ? ConnectionTerminationReason::server_said_do_not_reconnect
46✔
1151
                                      : ConnectionTerminationReason::server_said_try_again_later;
60✔
1152
    involuntary_disconnect(SessionErrorInfo{info, protocol_error_to_status(error_code, info.message)},
72✔
1153
                           reason); // Throws
72✔
1154
}
72✔
1155

1156

1157
void Connection::disconnect(const SessionErrorInfo& info)
1158
{
3,346✔
1159
    // Cancel connect timeout watchdog
1,694✔
1160
    m_connect_timer.reset();
3,346✔
1161

1,694✔
1162
    if (m_state == ConnectionState::connected) {
3,346✔
1163
        m_disconnect_time = monotonic_clock_now();
3,258✔
1164
        m_disconnect_has_occurred = true;
3,258✔
1165

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

1,694✔
1182
    change_state_to_disconnected();
3,346✔
1183

1,694✔
1184
    m_ping_delay_in_progress = false;
3,346✔
1185
    m_waiting_for_pong = false;
3,346✔
1186
    m_send_ping = false;
3,346✔
1187
    m_minimize_next_ping_delay = false;
3,346✔
1188
    m_ping_after_scheduled_reset_of_reconnect_info = false;
3,346✔
1189
    m_ping_sent = false;
3,346✔
1190
    m_heartbeat_timer.reset();
3,346✔
1191
    m_previous_ping_rtt = 0;
3,346✔
1192

1,694✔
1193
    m_websocket_sentinel->destroyed = true;
3,346✔
1194
    m_websocket_sentinel.reset();
3,346✔
1195
    m_websocket.reset();
3,346✔
1196
    m_input_body_buffer.reset();
3,346✔
1197
    m_sending_session = nullptr;
3,346✔
1198
    m_sessions_enlisted_to_send.clear();
3,346✔
1199
    m_sending = false;
3,346✔
1200

1,694✔
1201
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
3,346✔
1202
    initiate_reconnect_wait();                                           // Throws
3,346✔
1203
}
3,346✔
1204

1205
bool Connection::is_flx_sync_connection() const noexcept
1206
{
102,146✔
1207
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
102,146✔
1208
}
102,146✔
1209

1210
void Connection::receive_pong(milliseconds_type timestamp)
1211
{
222✔
1212
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
222✔
1213

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

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

86✔
1229
    milliseconds_type now = monotonic_clock_now();
222✔
1230
    milliseconds_type round_trip_time = now - timestamp;
222✔
1231
    logger.debug("Round trip time was %1 milliseconds", round_trip_time);
222✔
1232
    m_previous_ping_rtt = round_trip_time;
222✔
1233

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

86✔
1243
    m_heartbeat_timer.reset();
222✔
1244
    m_waiting_for_pong = false;
222✔
1245

86✔
1246
    initiate_ping_delay(now); // Throws
222✔
1247

86✔
1248
    if (m_client.m_roundtrip_time_handler)
222✔
1249
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
×
1250
}
222✔
1251

1252
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
1253
{
66,266✔
1254
    if (session_ident == 0) {
66,266✔
1255
        return nullptr;
×
1256
    }
×
1257

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

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

476✔
1290
        if (sess->m_state == Session::Deactivated) {
918✔
1291
            finish_session_deactivation(sess);
2✔
1292
        }
2✔
1293
        return;
918✔
1294
    }
918✔
1295

36✔
1296
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
76✔
1297
                info.message, info.raw_error_code, info.is_fatal, session_ident,
76✔
1298
                info.server_requests_action); // Throws
76✔
1299

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

1319

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

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

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

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

1343

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

1,538✔
1351
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
3,248✔
1352
        close_due_to_protocol_error(std::move(status)); // Throws
×
1353
}
3,248✔
1354

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

22,738✔
1365
    if (auto status = sess->receive_download_message(progress, downloadable_bytes, batch_state, query_version,
42,922✔
1366
                                                     received_changesets);
42,922✔
1367
        !status.is_ok()) {
42,922✔
1368
        close_due_to_protocol_error(std::move(status));
×
1369
    }
×
1370
}
42,922✔
1371

1372
void Connection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
1373
{
15,636✔
1374
    Session* sess = find_and_validate_session(session_ident, "MARK");
15,636✔
1375
    if (REALM_UNLIKELY(!sess)) {
15,636✔
1376
        return;
×
1377
    }
×
1378

7,728✔
1379
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
15,636✔
UNCOV
1380
        close_due_to_protocol_error(std::move(status)); // Throws
×
1381
}
15,636✔
1382

1383

1384
void Connection::receive_unbound_message(session_ident_type session_ident)
1385
{
3,482✔
1386
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
3,482✔
1387
    if (REALM_UNLIKELY(!sess)) {
3,482✔
1388
        return;
×
1389
    }
×
1390

1,846✔
1391
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
3,482✔
1392
        close_due_to_protocol_error(std::move(status)); // Throws
×
1393
        return;
×
1394
    }
×
1395

1,846✔
1396
    if (sess->m_state == Session::Deactivated) {
3,482✔
1397
        finish_session_deactivation(sess);
3,482✔
1398
    }
3,482✔
1399
}
3,482✔
1400

1401

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

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

1415

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

3,000✔
1427
    if (session_ident != 0) {
5,740✔
1428
        if (auto sess = get_session(session_ident)) {
3,872✔
1429
            sess->logger.log(level, "%1 log: %2", prefix, message);
3,872✔
1430
            return;
3,872✔
1431
        }
3,872✔
1432

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

966✔
1437
    logger.log(level, "%1 log: %2", prefix, message);
1,868✔
1438
}
1,868✔
1439

1440

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

1450

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

1456

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

1473

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

1479
void Session::cancel_resumption_delay()
1480
{
4,056✔
1481
    REALM_ASSERT_EX(m_state == Active, m_state);
4,056✔
1482

2,412✔
1483
    if (!m_suspended)
4,056✔
1484
        return;
3,656✔
1485

220✔
1486
    m_suspended = false;
400✔
1487

220✔
1488
    logger.debug("Resumed"); // Throws
400✔
1489

220✔
1490
    if (unbind_process_complete())
400✔
1491
        initiate_rebind(); // Throws
394✔
1492

220✔
1493
    m_conn.one_more_active_unsuspended_session(); // Throws
400✔
1494

220✔
1495
    on_resumed(); // Throws
400✔
1496
}
400✔
1497

1498

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

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

22✔
1516
    while (!m_pending_compensating_write_errors.empty() &&
88✔
1517
           *m_pending_compensating_write_errors.front().compensating_write_server_version <=
66✔
1518
               changesets.back().version) {
44✔
1519
        auto& cur_error = m_pending_compensating_write_errors.front();
44✔
1520
        REALM_ASSERT_3(*cur_error.compensating_write_server_version, >=, changesets.front().version);
44✔
1521
        out->push_back(std::move(cur_error));
44✔
1522
        m_pending_compensating_write_errors.pop_front();
44✔
1523
    }
44✔
1524
}
44✔
1525

1526

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

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

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

1575

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

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

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

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

1596
void Session::on_changesets_integrated(version_type client_version, const SyncProgress& progress)
1597
{
42,248✔
1598
    REALM_ASSERT_EX(m_state == Active, m_state);
42,248✔
1599
    REALM_ASSERT_3(progress.download.server_version, >=, m_download_progress.server_version);
42,248✔
1600
    m_download_progress = progress.download;
42,248✔
1601
    bool upload_progressed = (progress.upload.client_version > m_progress.upload.client_version);
42,248✔
1602
    m_progress = progress;
42,248✔
1603
    if (upload_progressed) {
42,248✔
1604
        if (progress.upload.client_version > m_last_version_selected_for_upload) {
31,586✔
1605
            if (progress.upload.client_version > m_upload_progress.client_version)
13,506✔
1606
                m_upload_progress = progress.upload;
754✔
1607
            m_last_version_selected_for_upload = progress.upload.client_version;
13,506✔
1608
        }
13,506✔
1609

16,482✔
1610
        check_for_upload_completion();
31,586✔
1611
    }
31,586✔
1612

22,346✔
1613
    do_recognize_sync_version(client_version); // Allows upload process to resume
42,248✔
1614
    check_for_download_completion();           // Throws
42,248✔
1615

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

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

1630

1631
Session::~Session()
1632
{
9,684✔
1633
    //    REALM_ASSERT_EX(m_state == Unactivated || m_state == Deactivated, m_state);
4,664✔
1634
}
9,684✔
1635

1636

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

1645

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

4,664✔
1650
    logger.debug("Activating"); // Throws
9,684✔
1651

4,664✔
1652
    bool has_pending_client_reset = false;
9,684✔
1653
    if (REALM_LIKELY(!get_client().is_dry_run())) {
9,684✔
1654
        bool file_exists = util::File::exists(get_realm_path());
9,684✔
1655
        m_performing_client_reset = get_client_reset_config().has_value();
9,684✔
1656

4,664✔
1657
        logger.info("client_reset_config = %1, Realm exists = %2 ", m_performing_client_reset, file_exists);
9,684✔
1658
        if (!m_performing_client_reset) {
9,684✔
1659
            get_history().get_status(m_last_version_available, m_client_file_ident, m_progress,
9,344✔
1660
                                     &has_pending_client_reset); // Throws
9,344✔
1661
        }
9,344✔
1662
    }
9,684✔
1663
    logger.debug("client_file_ident = %1, client_file_ident_salt = %2", m_client_file_ident.ident,
9,684✔
1664
                 m_client_file_ident.salt); // Throws
9,684✔
1665
    m_upload_progress = m_progress.upload;
9,684✔
1666
    m_last_version_selected_for_upload = m_upload_progress.client_version;
9,684✔
1667
    m_download_progress = m_progress.download;
9,684✔
1668
    REALM_ASSERT_3(m_last_version_available, >=, m_progress.upload.client_version);
9,684✔
1669

4,664✔
1670
    logger.debug("last_version_available  = %1", m_last_version_available);           // Throws
9,684✔
1671
    logger.debug("progress_download_server_version = %1", m_progress.download.server_version); // Throws
9,684✔
1672
    logger.debug("progress_download_client_version = %1",
9,684✔
1673
                 m_progress.download.last_integrated_client_version);                                      // Throws
9,684✔
1674
    logger.debug("progress_upload_server_version = %1", m_progress.upload.last_integrated_server_version); // Throws
9,684✔
1675
    logger.debug("progress_upload_client_version = %1", m_progress.upload.client_version);                 // Throws
9,684✔
1676

4,664✔
1677
    reset_protocol_state();
9,684✔
1678
    m_state = Active;
9,684✔
1679

4,664✔
1680
    REALM_ASSERT(!m_suspended);
9,684✔
1681
    m_conn.one_more_active_unsuspended_session(); // Throws
9,684✔
1682

4,664✔
1683
    try {
9,684✔
1684
        process_pending_flx_bootstrap();
9,684✔
1685
    }
9,684✔
1686
    catch (const IntegrationException& error) {
4,666✔
1687
        logger.error("Error integrating bootstrap changesets: %1", error.what());
4✔
1688
        m_suspended = true;
4✔
1689
        m_conn.one_less_active_unsuspended_session(); // Throws
4✔
1690
        on_suspended(SessionErrorInfo{Status{error.code(), error.what()}, IsFatal{true}});
4✔
1691
    }
4✔
1692

4,664✔
1693
    if (has_pending_client_reset) {
9,684✔
1694
        handle_pending_client_reset_acknowledgement();
20✔
1695
    }
20✔
1696
}
9,684✔
1697

1698

1699
// The caller (Connection) must discard the session if the session has become
1700
// deactivated upon return.
1701
void Session::initiate_deactivation()
1702
{
9,682✔
1703
    REALM_ASSERT_EX(m_state == Active, m_state);
9,682✔
1704

4,662✔
1705
    logger.debug("Initiating deactivation"); // Throws
9,682✔
1706

4,662✔
1707
    m_state = Deactivating;
9,682✔
1708

4,662✔
1709
    if (!m_suspended)
9,682✔
1710
        m_conn.one_less_active_unsuspended_session(); // Throws
9,146✔
1711

4,662✔
1712
    if (m_enlisted_to_send) {
9,682✔
1713
        REALM_ASSERT(!unbind_process_complete());
4,246✔
1714
        return;
4,246✔
1715
    }
4,246✔
1716

2,294✔
1717
    // Deactivate immediately if the BIND message has not yet been sent and the
2,294✔
1718
    // session is not enlisted to send, or if the unbinding process has already
2,294✔
1719
    // completed.
2,294✔
1720
    if (!m_bind_message_sent || unbind_process_complete()) {
5,436✔
1721
        complete_deactivation(); // Throws
2,236✔
1722
        // Life cycle state is now Deactivated
414✔
1723
        return;
2,236✔
1724
    }
2,236✔
1725

1,880✔
1726
    // Ready to send the UNBIND message, if it has not already been sent
1,880✔
1727
    if (!m_unbind_message_sent) {
3,200✔
1728
        enlist_to_send(); // Throws
3,046✔
1729
        return;
3,046✔
1730
    }
3,046✔
1731
}
3,200✔
1732

1733

1734
void Session::complete_deactivation()
1735
{
9,684✔
1736
    REALM_ASSERT_EX(m_state == Deactivating, m_state);
9,684✔
1737
    m_state = Deactivated;
9,684✔
1738

4,664✔
1739
    logger.debug("Deactivation completed"); // Throws
9,684✔
1740
}
9,684✔
1741

1742

1743
// Called by the associated Connection object when this session is granted an
1744
// opportunity to send a message.
1745
//
1746
// The caller (Connection) must discard the session if the session has become
1747
// deactivated upon return.
1748
void Session::send_message()
1749
{
152,142✔
1750
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
152,142✔
1751
    REALM_ASSERT(m_enlisted_to_send);
152,142✔
1752
    m_enlisted_to_send = false;
152,142✔
1753
    if (m_state == Deactivating || m_error_message_received || m_suspended) {
152,142✔
1754
        // Deactivation has been initiated. If the UNBIND message has not been
4,404✔
1755
        // sent yet, there is no point in sending it. Instead, we can let the
4,404✔
1756
        // deactivation process complete.
4,404✔
1757
        if (!m_bind_message_sent) {
7,730✔
1758
            return complete_deactivation(); // Throws
1,972✔
1759
            // Life cycle state is now Deactivated
1,318✔
1760
        }
1,972✔
1761

3,086✔
1762
        // Session life cycle state is Deactivating or the unbinding process has
3,086✔
1763
        // been initiated by a session specific ERROR message
3,086✔
1764
        if (!m_unbind_message_sent)
5,758✔
1765
            send_unbind_message(); // Throws
5,756✔
1766
        return;
5,758✔
1767
    }
5,758✔
1768

72,820✔
1769
    // Session life cycle state is Active and the unbinding process has
72,820✔
1770
    // not been initiated
72,820✔
1771
    REALM_ASSERT(!m_unbind_message_sent);
144,412✔
1772

72,820✔
1773
    if (!m_bind_message_sent)
144,412✔
1774
        return send_bind_message(); // Throws
8,116✔
1775

68,350✔
1776
    if (!m_ident_message_sent) {
136,296✔
1777
        if (have_client_file_ident())
6,646✔
1778
            send_ident_message(); // Throws
6,646✔
1779
        return;
6,646✔
1780
    }
6,646✔
1781

64,940✔
1782
    const auto has_pending_test_command = std::any_of(m_pending_test_commands.begin(), m_pending_test_commands.end(),
129,650✔
1783
                                                      [](const PendingTestCommand& command) {
64,988✔
1784
                                                          return command.pending;
96✔
1785
                                                      });
96✔
1786
    if (has_pending_test_command) {
129,650✔
1787
        return send_test_command_message();
44✔
1788
    }
44✔
1789

64,918✔
1790
    if (m_error_to_send)
129,606✔
1791
        return send_json_error_message(); // Throws
26✔
1792

64,908✔
1793
    // Stop sending upload, mark and query messages when the client detects an error.
64,908✔
1794
    if (m_client_error) {
129,580✔
1795
        return;
14✔
1796
    }
14✔
1797

64,900✔
1798
    if (m_target_download_mark > m_last_download_mark_sent)
129,566✔
1799
        return send_mark_message(); // Throws
16,344✔
1800

56,802✔
1801
    auto is_upload_allowed = [&]() -> bool {
113,224✔
1802
        if (!m_is_flx_sync_session) {
113,218✔
1803
            return true;
102,098✔
1804
        }
102,098✔
1805

5,834✔
1806
        auto migration_store = get_migration_store();
11,120✔
1807
        if (!migration_store) {
11,120✔
1808
            return true;
×
1809
        }
×
1810

5,834✔
1811
        auto sentinel_query_version = migration_store->get_sentinel_subscription_set_version();
11,120✔
1812
        if (!sentinel_query_version) {
11,120✔
1813
            return true;
11,092✔
1814
        }
11,092✔
1815

14✔
1816
        // Do not allow upload if the last query sent is the sentinel one used by the migration store.
14✔
1817
        return m_last_sent_flx_query_version != *sentinel_query_version;
28✔
1818
    };
28✔
1819

56,802✔
1820
    if (!is_upload_allowed()) {
113,222✔
1821
        return;
14✔
1822
    }
14✔
1823

56,794✔
1824
    auto check_pending_flx_version = [&]() -> bool {
113,210✔
1825
        if (!m_is_flx_sync_session) {
113,204✔
1826
            return false;
102,104✔
1827
        }
102,104✔
1828

5,826✔
1829
        if (!m_allow_upload) {
11,100✔
1830
            return false;
2,234✔
1831
        }
2,234✔
1832

4,576✔
1833
        m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(m_last_sent_flx_query_version);
8,866✔
1834

4,576✔
1835
        if (!m_pending_flx_sub_set) {
8,866✔
1836
            return false;
7,320✔
1837
        }
7,320✔
1838

778✔
1839
        return m_upload_progress.client_version >= m_pending_flx_sub_set->snapshot_version;
1,546✔
1840
    };
1,546✔
1841

56,794✔
1842
    if (check_pending_flx_version()) {
113,208✔
1843
        return send_query_change_message(); // throws
890✔
1844
    }
890✔
1845

56,348✔
1846
    if (m_allow_upload && (m_last_version_available > m_upload_progress.client_version)) {
112,318✔
1847
        return send_upload_message(); // Throws
55,676✔
1848
    }
55,676✔
1849
}
112,318✔
1850

1851

1852
void Session::send_bind_message()
1853
{
8,116✔
1854
    REALM_ASSERT_EX(m_state == Active, m_state);
8,116✔
1855

4,470✔
1856
    session_ident_type session_ident = m_ident;
8,116✔
1857
    bool need_client_file_ident = !have_client_file_ident();
8,116✔
1858
    const bool is_subserver = false;
8,116✔
1859

4,470✔
1860

4,470✔
1861
    ClientProtocol& protocol = m_conn.get_client_protocol();
8,116✔
1862
    int protocol_version = m_conn.get_negotiated_protocol_version();
8,116✔
1863
    OutputBuffer& out = m_conn.get_output_buffer();
8,116✔
1864
    // Discard the token since it's ignored by the server.
4,470✔
1865
    std::string empty_access_token;
8,116✔
1866
    if (m_is_flx_sync_session) {
8,116✔
1867
        nlohmann::json bind_json_data;
1,418✔
1868
        if (auto migrated_partition = get_migration_store()->get_migrated_partition()) {
1,418✔
1869
            bind_json_data["migratedPartition"] = *migrated_partition;
60✔
1870
        }
60✔
1871
        bind_json_data["sessionReason"] = static_cast<uint64_t>(get_session_reason());
1,418✔
1872
        if (logger.would_log(util::Logger::Level::debug)) {
1,418✔
1873
            std::string json_data_dump;
1,418✔
1874
            if (!bind_json_data.empty()) {
1,418✔
1875
                json_data_dump = bind_json_data.dump();
1,418✔
1876
            }
1,418✔
1877
            logger.debug(
1,418✔
1878
                "Sending: BIND(session_ident=%1, need_client_file_ident=%2, is_subserver=%3, json_data=\"%4\")",
1,418✔
1879
                session_ident, need_client_file_ident, is_subserver, json_data_dump);
1,418✔
1880
        }
1,418✔
1881
        protocol.make_flx_bind_message(protocol_version, out, session_ident, bind_json_data, empty_access_token,
1,418✔
1882
                                       need_client_file_ident, is_subserver); // Throws
1,418✔
1883
    }
1,418✔
1884
    else {
6,698✔
1885
        std::string server_path = get_virt_path();
6,698✔
1886
        logger.debug("Sending: BIND(session_ident=%1, need_client_file_ident=%2, is_subserver=%3, server_path=%4)",
6,698✔
1887
                     session_ident, need_client_file_ident, is_subserver, server_path);
6,698✔
1888
        protocol.make_pbs_bind_message(protocol_version, out, session_ident, server_path, empty_access_token,
6,698✔
1889
                                       need_client_file_ident, is_subserver); // Throws
6,698✔
1890
    }
6,698✔
1891
    m_conn.initiate_write_message(out, this); // Throws
8,116✔
1892

4,470✔
1893
    m_bind_message_sent = true;
8,116✔
1894

4,470✔
1895
    // Ready to send the IDENT message if the file identifier pair is already
4,470✔
1896
    // available.
4,470✔
1897
    if (!need_client_file_ident)
8,116✔
1898
        enlist_to_send(); // Throws
3,508✔
1899
}
8,116✔
1900

1901

1902
void Session::send_ident_message()
1903
{
6,646✔
1904
    REALM_ASSERT_EX(m_state == Active, m_state);
6,646✔
1905
    REALM_ASSERT(m_bind_message_sent);
6,646✔
1906
    REALM_ASSERT(!m_unbind_message_sent);
6,646✔
1907
    REALM_ASSERT(have_client_file_ident());
6,646✔
1908

3,410✔
1909

3,410✔
1910
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,646✔
1911
    OutputBuffer& out = m_conn.get_output_buffer();
6,646✔
1912
    session_ident_type session_ident = m_ident;
6,646✔
1913

3,410✔
1914
    if (m_is_flx_sync_session) {
6,646✔
1915
        const auto active_query_set = get_flx_subscription_store()->get_active();
1,008✔
1916
        const auto active_query_body = active_query_set.to_ext_json();
1,008✔
1917
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
1,008✔
1918
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
1,008✔
1919
                     "latest_server_version_salt=%6, query_version=%7, query_size=%8, query=\"%9\")",
1,008✔
1920
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
1,008✔
1921
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
1,008✔
1922
                     m_progress.latest_server_version.salt, active_query_set.version(), active_query_body.size(),
1,008✔
1923
                     active_query_body); // Throws
1,008✔
1924
        protocol.make_flx_ident_message(out, session_ident, m_client_file_ident, m_progress,
1,008✔
1925
                                        active_query_set.version(), active_query_body); // Throws
1,008✔
1926
        m_last_sent_flx_query_version = active_query_set.version();
1,008✔
1927
    }
1,008✔
1928
    else {
5,638✔
1929
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
5,638✔
1930
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
5,638✔
1931
                     "latest_server_version_salt=%6)",
5,638✔
1932
                     m_client_file_ident.ident, m_client_file_ident.salt, m_progress.download.server_version,
5,638✔
1933
                     m_progress.download.last_integrated_client_version, m_progress.latest_server_version.version,
5,638✔
1934
                     m_progress.latest_server_version.salt);                                  // Throws
5,638✔
1935
        protocol.make_pbs_ident_message(out, session_ident, m_client_file_ident, m_progress); // Throws
5,638✔
1936
    }
5,638✔
1937
    m_conn.initiate_write_message(out, this); // Throws
6,646✔
1938

3,410✔
1939
    m_ident_message_sent = true;
6,646✔
1940

3,410✔
1941
    // Other messages may be waiting to be sent
3,410✔
1942
    enlist_to_send(); // Throws
6,646✔
1943
}
6,646✔
1944

1945
void Session::send_query_change_message()
1946
{
890✔
1947
    REALM_ASSERT_EX(m_state == Active, m_state);
890✔
1948
    REALM_ASSERT(m_ident_message_sent);
890✔
1949
    REALM_ASSERT(!m_unbind_message_sent);
890✔
1950
    REALM_ASSERT(m_pending_flx_sub_set);
890✔
1951
    REALM_ASSERT_3(m_pending_flx_sub_set->query_version, >, m_last_sent_flx_query_version);
890✔
1952

446✔
1953
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
890✔
1954
        return;
×
1955
    }
×
1956

446✔
1957
    auto sub_store = get_flx_subscription_store();
890✔
1958
    auto latest_sub_set = sub_store->get_by_version(m_pending_flx_sub_set->query_version);
890✔
1959
    auto latest_queries = latest_sub_set.to_ext_json();
890✔
1960
    logger.debug("Sending: QUERY(query_version=%1, query_size=%2, query=\"%3\", snapshot_version=%4)",
890✔
1961
                 latest_sub_set.version(), latest_queries.size(), latest_queries, latest_sub_set.snapshot_version());
890✔
1962

446✔
1963
    OutputBuffer& out = m_conn.get_output_buffer();
890✔
1964
    session_ident_type session_ident = get_ident();
890✔
1965
    ClientProtocol& protocol = m_conn.get_client_protocol();
890✔
1966
    protocol.make_query_change_message(out, session_ident, latest_sub_set.version(), latest_queries);
890✔
1967
    m_conn.initiate_write_message(out, this);
890✔
1968

446✔
1969
    m_last_sent_flx_query_version = latest_sub_set.version();
890✔
1970

446✔
1971
    request_download_completion_notification();
890✔
1972
}
890✔
1973

1974
void Session::send_upload_message()
1975
{
55,674✔
1976
    REALM_ASSERT_EX(m_state == Active, m_state);
55,674✔
1977
    REALM_ASSERT(m_ident_message_sent);
55,674✔
1978
    REALM_ASSERT(!m_unbind_message_sent);
55,674✔
1979

28,246✔
1980
    if (REALM_UNLIKELY(get_client().is_dry_run()))
55,674✔
1981
        return;
28,246✔
1982

28,246✔
1983
    version_type target_upload_version = m_last_version_available;
55,674✔
1984
    if (m_pending_flx_sub_set) {
55,674✔
1985
        REALM_ASSERT(m_is_flx_sync_session);
662✔
1986
        target_upload_version = m_pending_flx_sub_set->snapshot_version;
662✔
1987
    }
662✔
1988

28,246✔
1989
    std::vector<UploadChangeset> uploadable_changesets;
55,674✔
1990
    version_type locked_server_version = 0;
55,674✔
1991
    get_history().find_uploadable_changesets(m_upload_progress, target_upload_version, uploadable_changesets,
55,674✔
1992
                                             locked_server_version); // Throws
55,674✔
1993

28,246✔
1994
    if (uploadable_changesets.empty()) {
55,674✔
1995
        // Nothing more to upload right now
13,910✔
1996
        check_for_upload_completion(); // Throws
28,212✔
1997
        // If we need to limit upload up to some version other than the last client version available and there are no
13,910✔
1998
        // changes to upload, then there is no need to send an empty message.
13,910✔
1999
        if (m_pending_flx_sub_set) {
28,212✔
2000
            logger.debug("Empty UPLOAD was skipped (progress_client_version=%1, progress_server_version=%2)",
188✔
2001
                         m_upload_progress.client_version, m_upload_progress.last_integrated_server_version);
188✔
2002
            // Other messages may be waiting to be sent
94✔
2003
            return enlist_to_send(); // Throws
188✔
2004
        }
188✔
2005
    }
27,462✔
2006
    else {
27,462✔
2007
        m_last_version_selected_for_upload = uploadable_changesets.back().progress.client_version;
27,462✔
2008
    }
27,462✔
2009

28,246✔
2010
    if (m_pending_flx_sub_set && target_upload_version < m_last_version_available) {
55,580✔
2011
        logger.trace("Limiting UPLOAD message up to version %1 to send QUERY version %2",
474✔
2012
                     m_pending_flx_sub_set->snapshot_version, m_pending_flx_sub_set->query_version);
474✔
2013
    }
474✔
2014

28,152✔
2015
    version_type progress_client_version = m_upload_progress.client_version;
55,486✔
2016
    version_type progress_server_version = m_upload_progress.last_integrated_server_version;
55,486✔
2017

28,152✔
2018
    logger.debug("Sending: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
55,486✔
2019
                 "locked_server_version=%3, num_changesets=%4)",
55,486✔
2020
                 progress_client_version, progress_server_version, locked_server_version,
55,486✔
2021
                 uploadable_changesets.size()); // Throws
55,486✔
2022

28,152✔
2023
    ClientProtocol& protocol = m_conn.get_client_protocol();
55,486✔
2024
    ClientProtocol::UploadMessageBuilder upload_message_builder = protocol.make_upload_message_builder(); // Throws
55,486✔
2025

28,152✔
2026
    for (const UploadChangeset& uc : uploadable_changesets) {
49,820✔
2027
        logger.debug("Fetching changeset for upload (client_version=%1, server_version=%2, "
42,178✔
2028
                     "changeset_size=%3, origin_timestamp=%4, origin_file_ident=%5)",
42,178✔
2029
                     uc.progress.client_version, uc.progress.last_integrated_server_version, uc.changeset.size(),
42,178✔
2030
                     uc.origin_timestamp, uc.origin_file_ident); // Throws
42,178✔
2031
        if (logger.would_log(util::Logger::Level::trace)) {
42,178✔
2032
            BinaryData changeset_data = uc.changeset.get_first_chunk();
×
2033
            if (changeset_data.size() < 1024) {
×
2034
                logger.trace("Changeset: %1",
×
2035
                             _impl::clamped_hex_dump(changeset_data)); // Throws
×
2036
            }
×
2037
            else {
×
2038
                logger.trace("Changeset(comp): %1 %2", changeset_data.size(),
×
2039
                             protocol.compressed_hex_dump(changeset_data));
×
2040
            }
×
2041

2042
#if REALM_DEBUG
×
2043
            ChunkedBinaryInputStream in{changeset_data};
×
2044
            Changeset log;
×
2045
            try {
×
2046
                parse_changeset(in, log);
×
2047
                std::stringstream ss;
×
2048
                log.print(ss);
×
2049
                logger.trace("Changeset (parsed):\n%1", ss.str());
×
2050
            }
×
2051
            catch (const BadChangesetError& err) {
×
2052
                logger.error("Unable to parse changeset: %1", err.what());
×
2053
            }
×
2054
#endif
×
2055
        }
×
2056

20,510✔
2057
#if 0 // Upload log compaction is currently not implemented
2058
        if (!get_client().m_disable_upload_compaction) {
2059
            ChangesetEncoder::Buffer encode_buffer;
2060

2061
            {
2062
                // Upload compaction only takes place within single changesets to
2063
                // avoid another client seeing inconsistent snapshots.
2064
                ChunkedBinaryInputStream stream{uc.changeset};
2065
                Changeset changeset;
2066
                parse_changeset(stream, changeset); // Throws
2067
                // FIXME: What is the point of setting these? How can compaction care about them?
2068
                changeset.version = uc.progress.client_version;
2069
                changeset.last_integrated_remote_version = uc.progress.last_integrated_server_version;
2070
                changeset.origin_timestamp = uc.origin_timestamp;
2071
                changeset.origin_file_ident = uc.origin_file_ident;
2072

2073
                compact_changesets(&changeset, 1);
2074
                encode_changeset(changeset, encode_buffer);
2075

2076
                logger.debug("Upload compaction: original size = %1, compacted size = %2", uc.changeset.size(),
2077
                             encode_buffer.size()); // Throws
2078
            }
2079

2080
            upload_message_builder.add_changeset(
2081
                uc.progress.client_version, uc.progress.last_integrated_server_version, uc.origin_timestamp,
2082
                uc.origin_file_ident, BinaryData{encode_buffer.data(), encode_buffer.size()}); // Throws
2083
        }
2084
        else
2085
#endif
2086
        {
42,178✔
2087
            upload_message_builder.add_changeset(uc.progress.client_version,
42,178✔
2088
                                                 uc.progress.last_integrated_server_version, uc.origin_timestamp,
42,178✔
2089
                                                 uc.origin_file_ident,
42,178✔
2090
                                                 uc.changeset); // Throws
42,178✔
2091
        }
42,178✔
2092
    }
42,178✔
2093

28,152✔
2094
    int protocol_version = m_conn.get_negotiated_protocol_version();
55,486✔
2095
    OutputBuffer& out = m_conn.get_output_buffer();
55,486✔
2096
    session_ident_type session_ident = get_ident();
55,486✔
2097
    upload_message_builder.make_upload_message(protocol_version, out, session_ident, progress_client_version,
55,486✔
2098
                                               progress_server_version,
55,486✔
2099
                                               locked_server_version); // Throws
55,486✔
2100
    m_conn.initiate_write_message(out, this);                          // Throws
55,486✔
2101

28,152✔
2102
    // Other messages may be waiting to be sent
28,152✔
2103
    enlist_to_send(); // Throws
55,486✔
2104
}
55,486✔
2105

2106

2107
void Session::send_mark_message()
2108
{
16,344✔
2109
    REALM_ASSERT_EX(m_state == Active, m_state);
16,344✔
2110
    REALM_ASSERT(m_ident_message_sent);
16,344✔
2111
    REALM_ASSERT(!m_unbind_message_sent);
16,344✔
2112
    REALM_ASSERT_3(m_target_download_mark, >, m_last_download_mark_sent);
16,344✔
2113

8,098✔
2114
    request_ident_type request_ident = m_target_download_mark;
16,344✔
2115
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
16,344✔
2116

8,098✔
2117
    ClientProtocol& protocol = m_conn.get_client_protocol();
16,344✔
2118
    OutputBuffer& out = m_conn.get_output_buffer();
16,344✔
2119
    session_ident_type session_ident = get_ident();
16,344✔
2120
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
16,344✔
2121
    m_conn.initiate_write_message(out, this);                      // Throws
16,344✔
2122

8,098✔
2123
    m_last_download_mark_sent = request_ident;
16,344✔
2124

8,098✔
2125
    // Other messages may be waiting to be sent
8,098✔
2126
    enlist_to_send(); // Throws
16,344✔
2127
}
16,344✔
2128

2129

2130
void Session::send_unbind_message()
2131
{
5,758✔
2132
    REALM_ASSERT_EX(m_state == Deactivating || m_error_message_received || m_suspended, m_state);
5,758✔
2133
    REALM_ASSERT(m_bind_message_sent);
5,758✔
2134
    REALM_ASSERT(!m_unbind_message_sent);
5,758✔
2135

3,086✔
2136
    logger.debug("Sending: UNBIND"); // Throws
5,758✔
2137

3,086✔
2138
    ClientProtocol& protocol = m_conn.get_client_protocol();
5,758✔
2139
    OutputBuffer& out = m_conn.get_output_buffer();
5,758✔
2140
    session_ident_type session_ident = get_ident();
5,758✔
2141
    protocol.make_unbind_message(out, session_ident); // Throws
5,758✔
2142
    m_conn.initiate_write_message(out, this);         // Throws
5,758✔
2143

3,086✔
2144
    m_unbind_message_sent = true;
5,758✔
2145
}
5,758✔
2146

2147

2148
void Session::send_json_error_message()
2149
{
26✔
2150
    REALM_ASSERT_EX(m_state == Active, m_state);
26✔
2151
    REALM_ASSERT(m_ident_message_sent);
26✔
2152
    REALM_ASSERT(!m_unbind_message_sent);
26✔
2153
    REALM_ASSERT(m_error_to_send);
26✔
2154
    REALM_ASSERT(m_client_error);
26✔
2155

10✔
2156
    ClientProtocol& protocol = m_conn.get_client_protocol();
26✔
2157
    OutputBuffer& out = m_conn.get_output_buffer();
26✔
2158
    session_ident_type session_ident = get_ident();
26✔
2159
    auto protocol_error = m_client_error->error_for_server;
26✔
2160

10✔
2161
    auto message = util::format("%1", m_client_error->to_status());
26✔
2162
    logger.info("Sending: ERROR \"%1\" (error_code=%2, session_ident=%3)", message, static_cast<int>(protocol_error),
26✔
2163
                session_ident); // Throws
26✔
2164

10✔
2165
    nlohmann::json error_body_json;
26✔
2166
    error_body_json["message"] = std::move(message);
26✔
2167
    protocol.make_json_error_message(out, session_ident, static_cast<int>(protocol_error),
26✔
2168
                                     error_body_json.dump()); // Throws
26✔
2169
    m_conn.initiate_write_message(out, this);                 // Throws
26✔
2170

10✔
2171
    m_error_to_send = false;
26✔
2172
    enlist_to_send(); // Throws
26✔
2173
}
26✔
2174

2175

2176
void Session::send_test_command_message()
2177
{
44✔
2178
    REALM_ASSERT_EX(m_state == Active, m_state);
44✔
2179

22✔
2180
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
44✔
2181
                           [](const PendingTestCommand& command) {
44✔
2182
                               return command.pending;
44✔
2183
                           });
44✔
2184
    REALM_ASSERT(it != m_pending_test_commands.end());
44✔
2185

22✔
2186
    ClientProtocol& protocol = m_conn.get_client_protocol();
44✔
2187
    OutputBuffer& out = m_conn.get_output_buffer();
44✔
2188
    auto session_ident = get_ident();
44✔
2189

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

22✔
2193
    m_conn.initiate_write_message(out, this); // Throws;
44✔
2194
    it->pending = false;
44✔
2195

22✔
2196
    enlist_to_send();
44✔
2197
}
44✔
2198

2199
bool Session::client_reset_if_needed()
2200
{
3,230✔
2201
    // Regardless of what happens, once we return from this function we will
1,532✔
2202
    // no longer be in the middle of a client reset
1,532✔
2203
    m_performing_client_reset = false;
3,230✔
2204

1,532✔
2205
    // Even if we end up not actually performing a client reset, consume the
1,532✔
2206
    // config to ensure that the resources it holds are released
1,532✔
2207
    auto client_reset_config = std::exchange(get_client_reset_config(), std::nullopt);
3,230✔
2208
    if (!client_reset_config) {
3,230✔
2209
        return false;
2,890✔
2210
    }
2,890✔
2211

170✔
2212
    auto on_flx_version_complete = [this](int64_t version) {
340✔
2213
        this->on_flx_sync_version_complete(version);
232✔
2214
    };
232✔
2215
    bool did_reset = client_reset::perform_client_reset(
340✔
2216
        logger, *get_db(), *client_reset_config->fresh_copy, client_reset_config->mode,
340✔
2217
        std::move(client_reset_config->notify_before_client_reset),
340✔
2218
        std::move(client_reset_config->notify_after_client_reset), m_client_file_ident, get_flx_subscription_store(),
340✔
2219
        on_flx_version_complete, client_reset_config->recovery_is_allowed);
340✔
2220
    if (!did_reset) {
340✔
2221
        return false;
×
2222
    }
×
2223

170✔
2224
    // The fresh Realm has been used to reset the state
170✔
2225
    logger.debug("Client reset is completed, path=%1", get_realm_path()); // Throws
340✔
2226

170✔
2227
    SaltedFileIdent client_file_ident;
340✔
2228
    bool has_pending_client_reset = false;
340✔
2229
    get_history().get_status(m_last_version_available, client_file_ident, m_progress,
340✔
2230
                             &has_pending_client_reset); // Throws
340✔
2231
    REALM_ASSERT_3(m_client_file_ident.ident, ==, client_file_ident.ident);
340✔
2232
    REALM_ASSERT_3(m_client_file_ident.salt, ==, client_file_ident.salt);
340✔
2233
    REALM_ASSERT_EX(m_progress.download.last_integrated_client_version == 0,
340✔
2234
                    m_progress.download.last_integrated_client_version);
340✔
2235
    REALM_ASSERT_EX(m_progress.upload.client_version == 0, m_progress.upload.client_version);
340✔
2236
    REALM_ASSERT_EX(m_progress.upload.last_integrated_server_version == 0,
340✔
2237
                    m_progress.upload.last_integrated_server_version);
340✔
2238
    logger.trace("last_version_available  = %1", m_last_version_available); // Throws
340✔
2239

170✔
2240
    m_upload_progress = m_progress.upload;
340✔
2241
    m_download_progress = m_progress.download;
340✔
2242
    // In recovery mode, there may be new changesets to upload and nothing left to download.
170✔
2243
    // In FLX DiscardLocal mode, there may be new commits due to subscription handling.
170✔
2244
    // For both, we want to allow uploads again without needing external changes to download first.
170✔
2245
    m_allow_upload = true;
340✔
2246
    REALM_ASSERT_EX(m_last_version_selected_for_upload == 0, m_last_version_selected_for_upload);
340✔
2247

170✔
2248
    if (has_pending_client_reset) {
340✔
2249
        handle_pending_client_reset_acknowledgement();
268✔
2250
    }
268✔
2251

170✔
2252
    update_subscription_version_info();
340✔
2253

170✔
2254
    // If a migration or rollback is in progress, mark it complete when client reset is completed.
170✔
2255
    if (auto migration_store = get_migration_store()) {
340✔
2256
        migration_store->complete_migration_or_rollback();
240✔
2257
    }
240✔
2258

170✔
2259
    return true;
340✔
2260
}
340✔
2261

2262
Status Session::receive_ident_message(SaltedFileIdent client_file_ident)
2263
{
3,248✔
2264
    logger.debug("Received: IDENT(client_file_ident=%1, client_file_ident_salt=%2)", client_file_ident.ident,
3,248✔
2265
                 client_file_ident.salt); // Throws
3,248✔
2266

1,538✔
2267
    // Ignore the message if the deactivation process has been initiated,
1,538✔
2268
    // because in that case, the associated Realm and SessionWrapper must
1,538✔
2269
    // not be accessed any longer.
1,538✔
2270
    if (m_state != Active)
3,248✔
2271
        return Status::OK(); // Success
18✔
2272

1,532✔
2273
    bool legal_at_this_time = (m_bind_message_sent && !have_client_file_ident() && !m_error_message_received &&
3,230✔
2274
                               !m_unbound_message_received);
3,230✔
2275
    if (REALM_UNLIKELY(!legal_at_this_time)) {
3,230✔
2276
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received IDENT message when it was not legal"};
×
2277
    }
×
2278
    if (REALM_UNLIKELY(client_file_ident.ident < 1)) {
3,230✔
2279
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier in IDENT message"};
×
2280
    }
×
2281
    if (REALM_UNLIKELY(client_file_ident.salt == 0)) {
3,230✔
2282
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier salt in IDENT message"};
×
2283
    }
×
2284

1,532✔
2285
    m_client_file_ident = client_file_ident;
3,230✔
2286

1,532✔
2287
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
3,230✔
2288
        // Ready to send the IDENT message
2289
        ensure_enlisted_to_send(); // Throws
×
2290
        return Status::OK();       // Success
×
2291
    }
×
2292

1,532✔
2293
    // if a client reset happens, it will take care of setting the file ident
1,532✔
2294
    // and if not, we do it here
1,532✔
2295
    bool did_client_reset = false;
3,230✔
2296
    try {
3,230✔
2297
        did_client_reset = client_reset_if_needed();
3,230✔
2298
    }
3,230✔
2299
    catch (const std::exception& e) {
1,568✔
2300
        auto err_msg = util::format("A fatal error occurred during client reset: '%1'", e.what());
72✔
2301
        logger.error(err_msg.c_str());
72✔
2302
        SessionErrorInfo err_info(Status{ErrorCodes::AutoClientResetFailed, err_msg}, IsFatal{true});
72✔
2303
        suspend(err_info);
72✔
2304
        return Status::OK();
72✔
2305
    }
72✔
2306
    if (!did_client_reset) {
3,158✔
2307
        get_history().set_client_file_ident(client_file_ident,
2,890✔
2308
                                            m_fix_up_object_ids); // Throws
2,890✔
2309
        m_progress.download.last_integrated_client_version = 0;
2,890✔
2310
        m_progress.upload.client_version = 0;
2,890✔
2311
        m_last_version_selected_for_upload = 0;
2,890✔
2312
    }
2,890✔
2313

1,496✔
2314
    // Ready to send the IDENT message
1,496✔
2315
    ensure_enlisted_to_send(); // Throws
3,158✔
2316
    return Status::OK();       // Success
3,158✔
2317
}
3,158✔
2318

2319
Status Session::receive_download_message(const SyncProgress& progress, std::uint_fast64_t downloadable_bytes,
2320
                                         DownloadBatchState batch_state, int64_t query_version,
2321
                                         const ReceivedChangesets& received_changesets)
2322
{
42,922✔
2323
    REALM_ASSERT_EX(query_version >= 0, query_version);
42,922✔
2324
    // Ignore the message if the deactivation process has been initiated,
22,738✔
2325
    // because in that case, the associated Realm and SessionWrapper must
22,738✔
2326
    // not be accessed any longer.
22,738✔
2327
    if (m_state != Active)
42,922✔
2328
        return Status::OK();
466✔
2329

22,450✔
2330
    if (is_steady_state_download_message(batch_state, query_version)) {
42,456✔
2331
        batch_state = DownloadBatchState::SteadyState;
40,806✔
2332
    }
40,806✔
2333

22,450✔
2334
    logger.debug("Received: DOWNLOAD(download_server_version=%1, download_client_version=%2, "
42,456✔
2335
                 "latest_server_version=%3, latest_server_version_salt=%4, "
42,456✔
2336
                 "upload_client_version=%5, upload_server_version=%6, downloadable_bytes=%7, "
42,456✔
2337
                 "last_in_batch=%8, query_version=%9, num_changesets=%10, ...)",
42,456✔
2338
                 progress.download.server_version, progress.download.last_integrated_client_version,
42,456✔
2339
                 progress.latest_server_version.version, progress.latest_server_version.salt,
42,456✔
2340
                 progress.upload.client_version, progress.upload.last_integrated_server_version, downloadable_bytes,
42,456✔
2341
                 batch_state != DownloadBatchState::MoreToCome, query_version, received_changesets.size()); // Throws
42,456✔
2342

22,450✔
2343
    // Ignore download messages when the client detects an error. This is to prevent transforming the same bad
22,450✔
2344
    // changeset over and over again.
22,450✔
2345
    if (m_client_error) {
42,456✔
2346
        logger.debug("Ignoring download message because the client detected an integration error");
×
2347
        return Status::OK();
×
2348
    }
×
2349

22,450✔
2350
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
42,456✔
2351
    if (REALM_UNLIKELY(!legal_at_this_time)) {
42,456✔
2352
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received DOWNLOAD message when it was not legal"};
×
2353
    }
×
2354
    if (auto status = check_received_sync_progress(progress); REALM_UNLIKELY(!status.is_ok())) {
42,456✔
2355
        logger.error("Bad sync progress received (%1)", status);
×
2356
        return status;
×
2357
    }
×
2358

22,450✔
2359
    version_type server_version = m_progress.download.server_version;
42,456✔
2360
    version_type last_integrated_client_version = m_progress.download.last_integrated_client_version;
42,456✔
2361
    for (const RemoteChangeset& changeset : received_changesets) {
43,564✔
2362
        // Check that per-changeset server version is strictly increasing, except in FLX sync where the server
21,624✔
2363
        // version must be increasing, but can stay the same during bootstraps.
21,624✔
2364
        bool good_server_version = m_is_flx_sync_session ? (changeset.remote_version >= server_version)
22,484✔
2365
                                                         : (changeset.remote_version > server_version);
41,878✔
2366
        // Each server version cannot be greater than the one in the header of the download message.
21,624✔
2367
        good_server_version = good_server_version && (changeset.remote_version <= progress.download.server_version);
42,738✔
2368
        if (!good_server_version) {
42,738✔
2369
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
2370
                    util::format("Bad server version in changeset header (DOWNLOAD) (%1, %2, %3)",
×
2371
                                 changeset.remote_version, server_version, progress.download.server_version)};
×
2372
        }
×
2373
        server_version = changeset.remote_version;
42,738✔
2374
        // Check that per-changeset last integrated client version is "weakly"
21,624✔
2375
        // increasing.
21,624✔
2376
        bool good_client_version =
42,738✔
2377
            (changeset.last_integrated_local_version >= last_integrated_client_version &&
42,738✔
2378
             changeset.last_integrated_local_version <= progress.download.last_integrated_client_version);
42,740✔
2379
        if (!good_client_version) {
42,738✔
2380
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
2381
                    util::format("Bad last integrated client version in changeset header (DOWNLOAD) "
×
2382
                                 "(%1, %2, %3)",
×
2383
                                 changeset.last_integrated_local_version, last_integrated_client_version,
×
2384
                                 progress.download.last_integrated_client_version)};
×
2385
        }
×
2386
        last_integrated_client_version = changeset.last_integrated_local_version;
42,738✔
2387
        // Server shouldn't send our own changes, and zero is not a valid client
21,624✔
2388
        // file identifier.
21,624✔
2389
        bool good_file_ident =
42,738✔
2390
            (changeset.origin_file_ident > 0 && changeset.origin_file_ident != m_client_file_ident.ident);
42,740✔
2391
        if (!good_file_ident) {
42,738✔
2392
            return {ErrorCodes::SyncProtocolInvariantFailed,
×
2393
                    util::format("Bad origin file identifier in changeset header (DOWNLOAD)",
×
2394
                                 changeset.origin_file_ident)};
×
2395
        }
×
2396
    }
42,738✔
2397

22,450✔
2398
    auto hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageReceived, progress, query_version,
42,456✔
2399
                                       batch_state, received_changesets.size());
42,456✔
2400
    if (hook_action == SyncClientHookAction::EarlyReturn) {
42,456✔
2401
        return Status::OK();
12✔
2402
    }
12✔
2403
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
42,444✔
2404

22,444✔
2405
    if (process_flx_bootstrap_message(progress, batch_state, query_version, received_changesets)) {
42,444✔
2406
        clear_resumption_delay_state();
1,640✔
2407
        return Status::OK();
1,640✔
2408
    }
1,640✔
2409

21,624✔
2410
    initiate_integrate_changesets(downloadable_bytes, batch_state, progress, received_changesets); // Throws
40,804✔
2411

21,624✔
2412
    hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
40,804✔
2413
                                  batch_state, received_changesets.size());
40,804✔
2414
    if (hook_action == SyncClientHookAction::EarlyReturn) {
40,804✔
2415
        return Status::OK();
×
2416
    }
×
2417
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
40,804✔
2418

21,624✔
2419
    // When we receive a DOWNLOAD message successfully, we can clear the backoff timer value used to reconnect
21,624✔
2420
    // after a retryable session error.
21,624✔
2421
    clear_resumption_delay_state();
40,804✔
2422
    return Status::OK();
40,804✔
2423
}
40,804✔
2424

2425
Status Session::receive_mark_message(request_ident_type request_ident)
2426
{
15,636✔
2427
    logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
15,636✔
2428

7,728✔
2429
    // Ignore the message if the deactivation process has been initiated,
7,728✔
2430
    // because in that case, the associated Realm and SessionWrapper must
7,728✔
2431
    // not be accessed any longer.
7,728✔
2432
    if (m_state != Active)
15,636✔
2433
        return Status::OK(); // Success
50✔
2434

7,688✔
2435
    bool legal_at_this_time = (m_ident_message_sent && !m_error_message_received && !m_unbound_message_received);
15,586✔
2436
    if (REALM_UNLIKELY(!legal_at_this_time)) {
15,586✔
UNCOV
2437
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received MARK message when it was not legal"};
×
UNCOV
2438
    }
×
2439
    bool good_request_ident =
15,586✔
2440
        (request_ident <= m_last_download_mark_sent && request_ident > m_last_download_mark_received);
15,586✔
2441
    if (REALM_UNLIKELY(!good_request_ident)) {
15,586✔
2442
        return {
×
2443
            ErrorCodes::SyncProtocolInvariantFailed,
×
2444
            util::format(
×
2445
                "Received MARK message with invalid request identifer (last mark sent: %1 last mark received: %2)",
×
2446
                m_last_download_mark_sent, m_last_download_mark_received)};
×
2447
    }
×
2448

7,688✔
2449
    m_server_version_at_last_download_mark = m_progress.download.server_version;
15,586✔
2450
    m_last_download_mark_received = request_ident;
15,586✔
2451
    check_for_download_completion(); // Throws
15,586✔
2452

7,688✔
2453
    return Status::OK(); // Success
15,586✔
2454
}
15,586✔
2455

2456

2457
// The caller (Connection) must discard the session if the session has become
2458
// deactivated upon return.
2459
Status Session::receive_unbound_message()
2460
{
3,482✔
2461
    logger.debug("Received: UNBOUND");
3,482✔
2462

1,846✔
2463
    bool legal_at_this_time = (m_unbind_message_sent && !m_error_message_received && !m_unbound_message_received);
3,482✔
2464
    if (REALM_UNLIKELY(!legal_at_this_time)) {
3,482✔
2465
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received UNBOUND message when it was not legal"};
×
2466
    }
×
2467

1,846✔
2468
    // The fact that the UNBIND message has been sent, but an ERROR message has
1,846✔
2469
    // not been received, implies that the deactivation process must have been
1,846✔
2470
    // initiated, so this session must be in the Deactivating state or the session
1,846✔
2471
    // has been suspended because of a client side error.
1,846✔
2472
    REALM_ASSERT_EX(m_state == Deactivating || m_suspended, m_state);
3,482!
2473

1,846✔
2474
    m_unbound_message_received = true;
3,482✔
2475

1,846✔
2476
    // Detect completion of the unbinding process
1,846✔
2477
    if (m_unbind_message_send_complete && m_state == Deactivating) {
3,482✔
2478
        // The deactivation process completes when the unbinding process
1,846✔
2479
        // completes.
1,846✔
2480
        complete_deactivation(); // Throws
3,482✔
2481
        // Life cycle state is now Deactivated
1,846✔
2482
    }
3,482✔
2483

1,846✔
2484
    return Status::OK(); // Success
3,482✔
2485
}
3,482✔
2486

2487

2488
Status Session::receive_query_error_message(int error_code, std::string_view message, int64_t query_version)
2489
{
16✔
2490
    logger.info("Received QUERY_ERROR \"%1\" (error_code=%2, query_version=%3)", message, error_code, query_version);
16✔
2491
    // Ignore the message if the deactivation process has been initiated,
8✔
2492
    // because in that case, the associated Realm and SessionWrapper must
8✔
2493
    // not be accessed any longer.
8✔
2494
    if (m_state == Active) {
16✔
2495
        on_flx_sync_error(query_version, message); // throws
16✔
2496
    }
16✔
2497
    return Status::OK();
16✔
2498
}
16✔
2499

2500
// The caller (Connection) must discard the session if the session has become
2501
// deactivated upon return.
2502
Status Session::receive_error_message(const ProtocolErrorInfo& info)
2503
{
918✔
2504
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, error_action=%4)", info.message,
918✔
2505
                info.raw_error_code, info.is_fatal, info.server_requests_action); // Throws
918✔
2506

476✔
2507
    bool legal_at_this_time = (m_bind_message_sent && !m_error_message_received && !m_unbound_message_received);
918✔
2508
    if (REALM_UNLIKELY(!legal_at_this_time)) {
918✔
2509
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received ERROR message when it was not legal"};
×
2510
    }
×
2511

476✔
2512
    auto protocol_error = static_cast<ProtocolError>(info.raw_error_code);
918✔
2513
    auto status = protocol_error_to_status(protocol_error, info.message);
918✔
2514
    if (status != ErrorCodes::UnknownError && REALM_UNLIKELY(!is_session_level_error(protocol_error))) {
918✔
2515
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
2516
                util::format("Received ERROR message for session with non-session-level error code %1",
×
2517
                             info.raw_error_code)};
×
2518
    }
×
2519

476✔
2520
    // Can't process debug hook actions once the Session is undergoing deactivation, since
476✔
2521
    // the SessionWrapper may not be available
476✔
2522
    if (m_state == Active) {
918✔
2523
        auto debug_action = call_debug_hook(SyncClientHookEvent::ErrorMessageReceived, info);
914✔
2524
        if (debug_action == SyncClientHookAction::EarlyReturn) {
914✔
2525
            return Status::OK();
8✔
2526
        }
8✔
2527
    }
910✔
2528

472✔
2529
    // For compensating write errors, we need to defer raising them to the SDK until after the server version
472✔
2530
    // containing the compensating write has appeared in a download message.
472✔
2531
    if (status == ErrorCodes::SyncCompensatingWrite) {
910✔
2532
        // If the client is not active, the compensating writes will not be processed now, but will be
22✔
2533
        // sent again the next time the client connects
22✔
2534
        if (m_state == Active) {
44✔
2535
            REALM_ASSERT(info.compensating_write_server_version.has_value());
44✔
2536
            m_pending_compensating_write_errors.push_back(info);
44✔
2537
        }
44✔
2538
        return Status::OK();
44✔
2539
    }
44✔
2540

450✔
2541
    m_error_message_received = true;
866✔
2542
    suspend(SessionErrorInfo{info, std::move(status)});
866✔
2543
    return Status::OK();
866✔
2544
}
866✔
2545

2546
void Session::suspend(const SessionErrorInfo& info)
2547
{
938✔
2548
    REALM_ASSERT(!m_suspended);
938✔
2549
    REALM_ASSERT_EX(m_state == Active || m_state == Deactivating, m_state);
938✔
2550
    logger.debug("Suspended"); // Throws
938✔
2551

486✔
2552
    m_suspended = true;
938✔
2553

486✔
2554
    // Detect completion of the unbinding process
486✔
2555
    if (m_unbind_message_send_complete && m_error_message_received) {
938!
2556
        // The fact that the UNBIND message has been sent, but we are not being suspended because
2✔
2557
        // we received an ERROR message implies that the deactivation process must
2✔
2558
        // have been initiated, so this session must be in the Deactivating state.
2✔
2559
        REALM_ASSERT_EX(m_state == Deactivating, m_state);
2!
2560

2✔
2561
        // The deactivation process completes when the unbinding process
2✔
2562
        // completes.
2✔
2563
        complete_deactivation(); // Throws
2✔
2564
        // Life cycle state is now Deactivated
2✔
2565
    }
2✔
2566

486✔
2567
    // Notify the application of the suspension of the session if the session is
486✔
2568
    // still in the Active state
486✔
2569
    if (m_state == Active) {
938✔
2570
        m_conn.one_less_active_unsuspended_session(); // Throws
934✔
2571
        on_suspended(info);                           // Throws
934✔
2572
    }
934✔
2573

486✔
2574
    if (!info.is_fatal) {
938✔
2575
        begin_resumption_delay(info);
396✔
2576
    }
396✔
2577

486✔
2578
    // Ready to send the UNBIND message, if it has not been sent already
486✔
2579
    if (!m_unbind_message_sent)
938✔
2580
        ensure_enlisted_to_send(); // Throws
934✔
2581
}
938✔
2582

2583
Status Session::receive_test_command_response(request_ident_type ident, std::string_view body)
2584
{
44✔
2585
    logger.info("Received: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", body, m_ident, ident);
44✔
2586
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
44✔
2587
                           [&](const PendingTestCommand& command) {
44✔
2588
                               return command.id == ident;
44✔
2589
                           });
44✔
2590
    if (it == m_pending_test_commands.end()) {
44✔
2591
        return {ErrorCodes::SyncProtocolInvariantFailed,
×
2592
                util::format("Received test command response for a non-existent ident %1", ident)};
×
2593
    }
×
2594

22✔
2595
    it->promise.emplace_value(std::string{body});
44✔
2596
    m_pending_test_commands.erase(it);
44✔
2597

22✔
2598
    return Status::OK();
44✔
2599
}
44✔
2600

2601
void Session::begin_resumption_delay(const ProtocolErrorInfo& error_info)
2602
{
396✔
2603
    REALM_ASSERT(!m_try_again_activation_timer);
396✔
2604

218✔
2605
    m_try_again_delay_info.update(static_cast<sync::ProtocolError>(error_info.raw_error_code),
396✔
2606
                                  error_info.resumption_delay_interval);
396✔
2607
    auto try_again_interval = m_try_again_delay_info.delay_interval();
396✔
2608
    if (ProtocolError(error_info.raw_error_code) == ProtocolError::session_closed) {
396✔
2609
        // FIXME With compensating writes the server sends this error after completing a bootstrap. Doing the
10✔
2610
        // normal backoff behavior would result in waiting up to 5 minutes in between each query change which is
10✔
2611
        // not acceptable latency. So for this error code alone, we hard-code a 1 second retry interval.
10✔
2612
        try_again_interval = std::chrono::milliseconds{1000};
20✔
2613
    }
20✔
2614
    logger.debug("Will attempt to resume session after %1 milliseconds", try_again_interval.count());
396✔
2615
    m_try_again_activation_timer = get_client().create_timer(try_again_interval, [this](Status status) {
396✔
2616
        if (status == ErrorCodes::OperationAborted)
396✔
2617
            return;
4✔
2618
        else if (!status.is_ok())
392✔
2619
            throw Exception(status);
×
2620

216✔
2621
        m_try_again_activation_timer.reset();
392✔
2622
        cancel_resumption_delay();
392✔
2623
    });
392✔
2624
}
396✔
2625

2626
void Session::clear_resumption_delay_state()
2627
{
42,444✔
2628
    if (m_try_again_activation_timer) {
42,444✔
2629
        logger.debug("Clearing resumption delay state after successful download");
×
2630
        m_try_again_delay_info.reset();
×
2631
    }
×
2632
}
42,444✔
2633

2634
Status ClientImpl::Session::check_received_sync_progress(const SyncProgress& progress) noexcept
2635
{
42,454✔
2636
    const SyncProgress& a = m_progress;
42,454✔
2637
    const SyncProgress& b = progress;
42,454✔
2638
    std::string message;
42,454✔
2639
    if (b.latest_server_version.version < a.latest_server_version.version) {
42,454✔
2640
        message = util::format("Latest server version in download messages must be weakly increasing throughout a "
×
2641
                               "session (current: %1, received: %2)",
×
2642
                               a.latest_server_version.version, b.latest_server_version.version);
×
2643
    }
×
2644
    if (b.upload.client_version < a.upload.client_version) {
42,454✔
2645
        message = util::format("Last integrated client version in download messages must be weakly increasing "
×
2646
                               "throughout a session (current: %1, received: %2)",
×
2647
                               a.upload.client_version, b.upload.client_version);
×
2648
    }
×
2649
    if (b.upload.client_version > m_last_version_available) {
42,454✔
2650
        message = util::format("Last integrated client version on server cannot be greater than the latest client "
×
2651
                               "version in existence (current: %1, received: %2)",
×
2652
                               m_last_version_available, b.upload.client_version);
×
2653
    }
×
2654
    if (b.download.server_version < a.download.server_version) {
42,454✔
2655
        message =
×
2656
            util::format("Download cursor must be weakly increasing throughout a session (current: %1, received: %2)",
×
2657
                         a.download.server_version, b.download.server_version);
×
2658
    }
×
2659
    if (b.download.server_version > b.latest_server_version.version) {
42,454✔
2660
        message = util::format(
×
2661
            "Download cursor cannot be greater than the latest server version in existence (cursor: %1, latest: %2)",
×
2662
            b.download.server_version, b.latest_server_version.version);
×
2663
    }
×
2664
    if (b.download.last_integrated_client_version < a.download.last_integrated_client_version) {
42,454✔
2665
        message = util::format(
×
2666
            "Last integrated client version on the server at the position in the server's history of the download "
×
2667
            "cursor must be weakly increasing throughout a session (current: %1, received: %2)",
×
2668
            a.download.last_integrated_client_version, b.download.last_integrated_client_version);
×
2669
    }
×
2670
    if (b.download.last_integrated_client_version > b.upload.client_version) {
42,454✔
2671
        message = util::format("Last integrated client version on the server in the position at the server's history "
×
2672
                               "of the download cursor cannot be greater than the latest client version integrated "
×
2673
                               "on the server (download: %1, upload: %2)",
×
2674
                               b.download.last_integrated_client_version, b.upload.client_version);
×
2675
    }
×
2676
    if (b.download.server_version < b.upload.last_integrated_server_version) {
42,454✔
2677
        message = util::format(
×
2678
            "The server version of the download cursor cannot be less than the server version integrated in the "
×
2679
            "latest client version acknowledged by the server (download: %1, upload: %2)",
×
2680
            b.download.server_version, b.upload.last_integrated_server_version);
×
2681
    }
×
2682

22,448✔
2683
    if (message.empty()) {
42,454✔
2684
        return Status::OK();
42,454✔
2685
    }
42,454✔
UNCOV
2686
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
×
UNCOV
2687
}
×
2688

2689

2690
void Session::check_for_upload_completion()
2691
{
75,048✔
2692
    REALM_ASSERT_EX(m_state == Active, m_state);
75,048✔
2693
    if (!m_upload_completion_notification_requested) {
75,048✔
2694
        return;
44,746✔
2695
    }
44,746✔
2696

14,970✔
2697
    // during an ongoing client reset operation, we never upload anything
14,970✔
2698
    if (m_performing_client_reset)
30,302✔
2699
        return;
240✔
2700

14,850✔
2701
    // Upload process must have reached end of history
14,850✔
2702
    REALM_ASSERT_3(m_upload_progress.client_version, <=, m_last_version_available);
30,062✔
2703
    bool scan_complete = (m_upload_progress.client_version == m_last_version_available);
30,062✔
2704
    if (!scan_complete)
30,062✔
2705
        return;
4,908✔
2706

12,334✔
2707
    // All uploaded changesets must have been acknowledged by the server
12,334✔
2708
    REALM_ASSERT_3(m_progress.upload.client_version, <=, m_last_version_selected_for_upload);
25,154✔
2709
    bool all_uploads_accepted = (m_progress.upload.client_version == m_last_version_selected_for_upload);
25,154✔
2710
    if (!all_uploads_accepted)
25,154✔
2711
        return;
10,498✔
2712

7,240✔
2713
    m_upload_completion_notification_requested = false;
14,656✔
2714
    on_upload_completion(); // Throws
14,656✔
2715
}
14,656✔
2716

2717

2718
void Session::check_for_download_completion()
2719
{
57,834✔
2720
    REALM_ASSERT_3(m_target_download_mark, >=, m_last_download_mark_received);
57,834✔
2721
    REALM_ASSERT_3(m_last_download_mark_received, >=, m_last_triggering_download_mark);
57,834✔
2722
    if (m_last_download_mark_received == m_last_triggering_download_mark)
57,834✔
2723
        return;
42,072✔
2724
    if (m_last_download_mark_received < m_target_download_mark)
15,762✔
2725
        return;
324✔
2726
    if (m_download_progress.server_version < m_server_version_at_last_download_mark)
15,438✔
2727
        return;
×
2728
    m_last_triggering_download_mark = m_target_download_mark;
15,438✔
2729
    if (REALM_UNLIKELY(!m_allow_upload)) {
15,438✔
2730
        // Activate the upload process now, and enable immediate reactivation
2,004✔
2731
        // after a subsequent fast reconnect.
2,004✔
2732
        m_allow_upload = true;
4,212✔
2733
        ensure_enlisted_to_send(); // Throws
4,212✔
2734
    }
4,212✔
2735
    on_download_completion(); // Throws
15,438✔
2736
}
15,438✔
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