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

realm / realm-core / thomas.goyne_442

02 Jul 2024 07:51PM UTC coverage: 90.995% (+0.02%) from 90.974%
thomas.goyne_442

push

Evergreen

web-flow
[RCORE-2146] CAPI Remove `is_fatal` flag flip (#7751)

102372 of 180620 branches covered (56.68%)

0 of 1 new or added line in 1 file covered. (0.0%)

625 existing lines in 26 files now uncovered.

215592 of 236928 relevant lines covered (90.99%)

5608163.57 hits per line

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

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

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

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

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

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

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

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

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

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

55

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

62

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

4,782✔
69
    if (!m_backoff_state.triggering_error) {
4,782✔
70
        return std::chrono::milliseconds::zero();
71
    }
1,506✔
72

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

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

88

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

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

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

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

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

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

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

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

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

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

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

198,380✔
233
void ClientImpl::incr_outstanding_posts()
198,380✔
234
{
198,380✔
235
    util::CheckedLockGuard lock(m_drain_mutex);
198,380✔
236
    ++m_outstanding_posts;
198,380✔
237
    m_drained = false;
238
}
239

198,380✔
240
void ClientImpl::decr_outstanding_posts()
198,380✔
241
{
198,380✔
242
    util::CheckedLockGuard lock(m_drain_mutex);
198,380✔
243
    REALM_ASSERT(m_outstanding_posts);
244
    if (--m_outstanding_posts <= 0) {
245
        // Notify must happen with lock held or another thread could destroy
18,222✔
246
        // ClientImpl between when we release the lock and when we call notify
18,222✔
247
        m_drain_cv.notify_all();
198,380✔
248
    }
249
}
250

56,124✔
251
void ClientImpl::post(SyncSocketProvider::FunctionHandler&& handler)
56,124✔
252
{
56,124✔
253
    REALM_ASSERT(m_socket_provider);
56,124✔
254
    incr_outstanding_posts();
56,120✔
255
    m_socket_provider->post([handler = std::move(handler), this](Status status) {
56,118✔
256
        auto decr_guard = util::make_scope_exit([&]() noexcept {
56,118✔
257
            decr_outstanding_posts();
56,120✔
258
        });
56,120✔
259
        handler(status);
56,124✔
260
    });
261
}
262

124,622✔
263
void ClientImpl::post(util::UniqueFunction<void()>&& handler)
124,622✔
264
{
124,622✔
265
    REALM_ASSERT(m_socket_provider);
124,622✔
266
    incr_outstanding_posts();
124,622✔
267
    m_socket_provider->post([handler = std::move(handler), this](Status status) {
124,620✔
268
        auto decr_guard = util::make_scope_exit([&]() noexcept {
124,620✔
269
            decr_outstanding_posts();
124,622✔
UNCOV
270
        });
×
271
        if (status == ErrorCodes::OperationAborted)
124,622✔
272
            return;
×
273
        if (!status.is_ok())
124,622✔
274
            throw Exception(status);
124,622✔
275
        handler();
124,622✔
276
    });
277
}
278

279

9,942✔
280
void ClientImpl::drain_connections()
9,942✔
281
{
9,942✔
282
    logger.debug("Draining connections during sync client shutdown");
2,696✔
283
    for (auto& server_slot_pair : m_server_slots) {
284
        auto& server_slot = server_slot_pair.second;
2,696✔
285

2,464✔
286
        if (server_slot.connection) {
2,464✔
287
            auto& conn = server_slot.connection;
2,464✔
288
            conn->force_close();
232✔
289
        }
232✔
290
        else {
6✔
291
            for (auto& conn_pair : server_slot.alt_connections) {
6✔
292
                conn_pair.second->force_close();
232✔
293
            }
2,696✔
294
        }
9,942✔
295
    }
296
}
297

298

299
SyncSocketProvider::SyncTimer ClientImpl::create_timer(std::chrono::milliseconds delay,
17,644✔
300
                                                       SyncSocketProvider::FunctionHandler&& handler)
17,644✔
301
{
17,644✔
302
    REALM_ASSERT(m_socket_provider);
17,646✔
303
    incr_outstanding_posts();
17,648✔
304
    return m_socket_provider->create_timer(delay, [handler = std::move(handler), this](Status status) {
17,644✔
305
        auto decr_guard = util::make_scope_exit([&]() noexcept {
17,644✔
306
            decr_outstanding_posts();
17,646✔
307
        });
17,646✔
308
        handler(status);
17,644✔
309
    });
310
}
311

312

12,746✔
313
ClientImpl::SyncTrigger ClientImpl::create_trigger(SyncSocketProvider::FunctionHandler&& handler)
12,746✔
314
{
12,746✔
315
    REALM_ASSERT(m_socket_provider);
12,746✔
316
    return std::make_unique<Trigger<ClientImpl>>(this, std::move(handler));
317
}
318

2,804✔
319
Connection::~Connection()
2,804✔
UNCOV
320
{
×
UNCOV
321
    if (m_websocket_sentinel) {
×
322
        m_websocket_sentinel->destroyed = true;
×
323
        m_websocket_sentinel.reset();
2,804✔
324
    }
325
}
326

2,802✔
327
void Connection::activate()
2,802✔
328
{
2,802✔
329
    REALM_ASSERT(m_on_idle);
2,802✔
UNCOV
330
    m_activated = true;
×
331
    if (m_num_active_sessions == 0)
332
        m_on_idle->trigger();
333
    // We cannot in general connect immediately, because a prior failure to
2,802✔
334
    // connect may require a delay before reconnecting (see `m_reconnect_info`).
2,802✔
335
    initiate_reconnect_wait(); // Throws
336
}
337

338

10,082✔
339
void Connection::activate_session(std::unique_ptr<Session> sess)
10,082✔
340
{
10,082✔
341
    REALM_ASSERT(sess);
10,082✔
342
    REALM_ASSERT(&sess->m_conn == this);
10,082✔
343
    REALM_ASSERT(!m_force_closed);
10,082✔
344
    Session& sess_2 = *sess;
10,082✔
345
    session_ident_type ident = sess->m_ident;
10,082✔
346
    auto p = m_sessions.emplace(ident, std::move(sess)); // Throws
10,082✔
347
    bool was_inserted = p.second;
348
    REALM_ASSERT(was_inserted);
10,082✔
349
    // Save the session ident to the historical list of session idents
10,082✔
350
    m_session_history.insert(ident);
10,082✔
351
    sess_2.activate(); // Throws
6,982✔
352
    if (m_state == ConnectionState::connected) {
6,982✔
353
        bool fast_reconnect = false;
6,982✔
354
        sess_2.connection_established(fast_reconnect); // Throws
10,082✔
355
    }
10,082✔
356
    ++m_num_active_sessions;
357
}
358

359

10,080✔
360
void Connection::initiate_session_deactivation(Session* sess)
10,080✔
361
{
10,080✔
362
    REALM_ASSERT(sess);
10,080✔
363
    REALM_ASSERT(&sess->m_conn == this);
364
    REALM_ASSERT(m_num_active_sessions);
365
    // Since the client may be waiting for m_num_active_sessions to reach 0
366
    // in stop_and_wait() (on a separate thread), deactivate Session before
10,080✔
367
    // decrementing the num active sessions value.
10,080✔
368
    sess->initiate_deactivation(); // Throws
894✔
369
    if (sess->m_state == Session::Deactivated) {
894✔
370
        finish_session_deactivation(sess);
10,080✔
371
    }
4,382✔
372
    if (REALM_UNLIKELY(--m_num_active_sessions == 0)) {
372✔
373
        if (m_activated && m_state == ConnectionState::disconnected)
4,382✔
374
            m_on_idle->trigger();
10,080✔
375
    }
376
}
377

378

2,300✔
379
void Connection::cancel_reconnect_delay()
2,300✔
380
{
381
    REALM_ASSERT(m_activated);
2,300✔
382

2,068✔
383
    if (m_reconnect_delay_in_progress) {
1,036✔
384
        if (m_nonzero_reconnect_delay)
385
            logger.detail("Canceling reconnect delay"); // Throws
386

387
        // Cancel the in-progress wait operation by destroying the timer
388
        // object. Destruction is needed in this case, because a new wait
389
        // operation might have to be initiated before the previous one
390
        // completes (its completion handler starts to execute), so the new wait
2,068✔
391
        // operation must be done on a new timer object.
2,068✔
392
        m_reconnect_disconnect_timer.reset();
2,068✔
393
        m_reconnect_delay_in_progress = false;
2,068✔
394
        m_reconnect_info.reset();
2,068✔
395
        initiate_reconnect_wait(); // Throws
2,068✔
396
        return;
397
    }
398

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

232✔
412
        schedule_urgent_ping(); // Throws
232✔
413
        return;
414
    }
415
    // Nothing to do in this case. The next reconnect attemp will be made as
232✔
416
    // soon as there are any sessions that are both active and unsuspended.
417
}
418

7,886✔
419
void Connection::finish_session_deactivation(Session* sess)
7,886✔
420
{
7,886✔
421
    REALM_ASSERT(sess->m_state == Session::Deactivated);
7,886✔
422
    auto ident = sess->m_ident;
7,886✔
423
    m_sessions.erase(ident);
7,886✔
424
    m_session_history.erase(ident);
425
}
426

2,470✔
427
void Connection::force_close()
2,470✔
UNCOV
428
{
×
UNCOV
429
    if (m_force_closed) {
×
430
        return;
431
    }
2,470✔
432

433
    m_force_closed = true;
2,470✔
434

2,438✔
435
    if (m_state != ConnectionState::disconnected) {
2,438✔
436
        voluntary_disconnect();
437
    }
2,470✔
438

2,470✔
439
    REALM_ASSERT_EX(m_state == ConnectionState::disconnected, m_state);
34✔
440
    if (m_reconnect_delay_in_progress || m_disconnect_delay_in_progress) {
34✔
441
        m_reconnect_disconnect_timer.reset();
34✔
442
        m_reconnect_delay_in_progress = false;
34✔
443
        m_disconnect_delay_in_progress = false;
444
    }
445

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

102✔
456
    for (auto& sess : to_close) {
102✔
457
        sess->force_close();
458
    }
2,470✔
459

2,470✔
460
    logger.debug("Force closed idle connection");
461
}
462

463

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

506

80,558✔
507
bool Connection::websocket_binary_message_received(util::Span<const char> data)
80,558✔
UNCOV
508
{
×
UNCOV
509
    if (m_force_closed) {
×
510
        logger.debug("Received binary message after connection was force closed");
×
511
        return false;
512
    }
80,558✔
513

80,558✔
514
    using sf = SimulatedFailure;
460✔
515
    if (sf::check_trigger(sf::sync_client__read_head)) {
460✔
516
        close_due_to_client_side_error(
460✔
517
            {ErrorCodes::RuntimeError, "Simulated failure during sync client websocket read"}, IsFatal{false},
460✔
518
            ConnectionTerminationReason::read_or_write_error);
460✔
519
        return bool(m_websocket);
520
    }
80,098✔
521

80,098✔
522
    handle_message_received(data);
80,558✔
523
    return bool(m_websocket);
524
}
525

526

766✔
527
void Connection::websocket_error_handler()
766✔
528
{
766✔
529
    m_websocket_error_received = true;
530
}
531

870✔
532
bool Connection::websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg)
870✔
UNCOV
533
{
×
UNCOV
534
    if (m_force_closed) {
×
535
        logger.debug("Received websocket close message after connection was force closed");
×
536
        return false;
870✔
537
    }
538
    logger.info("Closing the websocket with error code=%1, message='%2', was_clean=%3", error_code, msg, was_clean);
870✔
539

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

870✔
662
    return bool(m_websocket);
663
}
664

665
// Guarantees that handle_reconnect_wait() is never called from within the
666
// execution of initiate_reconnect_wait() (no callback reentrance).
8,720✔
667
void Connection::initiate_reconnect_wait()
8,720✔
668
{
8,720✔
669
    REALM_ASSERT(m_activated);
8,720✔
670
    REALM_ASSERT(!m_reconnect_delay_in_progress);
671
    REALM_ASSERT(!m_disconnect_delay_in_progress);
672

8,720✔
673
    // If we've been force closed then we don't need/want to reconnect. Just return early here.
2,438✔
674
    if (m_force_closed) {
2,438✔
675
        return;
676
    }
6,282✔
677

6,282✔
678
    m_reconnect_delay_in_progress = true;
6,282✔
679
    auto delay = m_reconnect_info.delay_interval();
1,080✔
680
    if (delay == std::chrono::milliseconds::max()) {
681
        logger.detail("Reconnection delayed indefinitely"); // Throws
1,080✔
682
        // Not actually starting a timer corresponds to an infinite wait
1,080✔
683
        m_nonzero_reconnect_delay = true;
1,080✔
684
        return;
685
    }
5,202✔
686

4,862✔
687
    if (delay == std::chrono::milliseconds::zero()) {
4,862✔
688
        m_nonzero_reconnect_delay = false;
340✔
689
    }
340✔
690
    else {
340✔
691
        logger.detail("Allowing reconnection in %1 milliseconds", delay.count()); // Throws
340✔
692
        m_nonzero_reconnect_delay = true;
693
    }
694

695
    // We create a timer for the reconnect_disconnect timer even if the delay is zero because
696
    // we need it to be cancelable in case the connection is terminated before the timer
5,208✔
697
    // callback is run.
698
    m_reconnect_disconnect_timer = m_client.create_timer(delay, [this](Status status) {
699
        // If the operation is aborted, the connection object may have been
5,208✔
700
        // destroyed.
3,854✔
701
        if (status != ErrorCodes::OperationAborted)
5,208✔
702
            handle_reconnect_wait(status); // Throws
5,202✔
703
    });                                    // Throws
704
}
705

706

3,856✔
707
void Connection::handle_reconnect_wait(Status status)
3,856✔
UNCOV
708
{
×
UNCOV
709
    if (!status.is_ok()) {
×
710
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
711
        throw Exception(status);
712
    }
3,856✔
713

3,856✔
714
    REALM_ASSERT(m_reconnect_delay_in_progress);
715
    m_reconnect_delay_in_progress = false;
3,856✔
716

3,850✔
717
    if (m_num_active_unsuspended_sessions > 0)
3,856✔
718
        initiate_reconnect(); // Throws
719
}
720

721
struct Connection::WebSocketObserverShim : public sync::WebSocketObserver {
1,826✔
722
    explicit WebSocketObserverShim(Connection* conn)
1,826✔
723
        : conn(conn)
3,856✔
724
        , sentinel(conn->m_websocket_sentinel)
3,856✔
725
    {
726
    }
727

728
    Connection* conn;
729
    util::bind_ptr<LifecycleSentinel> sentinel;
730

3,652✔
731
    void websocket_connected_handler(const std::string& protocol) override
3,652✔
UNCOV
732
    {
×
UNCOV
733
        if (sentinel->destroyed) {
×
734
            return;
735
        }
3,652✔
736

3,652✔
737
        return conn->websocket_connected_handler(protocol);
738
    }
739

766✔
740
    void websocket_error_handler() override
766✔
UNCOV
741
    {
×
UNCOV
742
        if (sentinel->destroyed) {
×
743
            return;
744
        }
766✔
745

766✔
746
        conn->websocket_error_handler();
747
    }
748

80,558✔
749
    bool websocket_binary_message_received(util::Span<const char> data) override
80,558✔
UNCOV
750
    {
×
UNCOV
751
        if (sentinel->destroyed) {
×
752
            return false;
753
        }
80,558✔
754

80,558✔
755
        return conn->websocket_binary_message_received(data);
756
    }
757

870✔
758
    bool websocket_closed_handler(bool was_clean, WebSocketError error_code, std::string_view msg) override
870✔
UNCOV
759
    {
×
UNCOV
760
        if (sentinel->destroyed) {
×
761
            return true;
762
        }
870✔
763

870✔
764
        return conn->websocket_closed_handler(was_clean, error_code, msg);
765
    }
766
};
767

3,854✔
768
void Connection::initiate_reconnect()
3,854✔
769
{
770
    REALM_ASSERT(m_activated);
3,854✔
771

3,854✔
772
    m_state = ConnectionState::connecting;
3,854✔
UNCOV
773
    report_connection_state_change(ConnectionState::connecting); // Throws
×
UNCOV
774
    if (m_websocket_sentinel) {
×
775
        m_websocket_sentinel->destroyed = true;
3,854✔
776
    }
3,854✔
777
    m_websocket_sentinel = util::make_bind<LifecycleSentinel>();
778
    m_websocket.reset();
779

3,854✔
780
    // Watchdog
781
    initiate_connect_wait(); // Throws
3,854✔
782

3,854✔
783
    std::vector<std::string> sec_websocket_protocol;
3,854✔
784
    {
3,854✔
785
        auto protocol_prefix =
3,854✔
786
            is_flx_sync_connection() ? get_flx_websocket_protocol_prefix() : get_pbs_websocket_protocol_prefix();
3,854✔
787
        int min = get_oldest_supported_protocol_version();
3,854✔
788
        int max = get_current_protocol_version();
789
        REALM_ASSERT_3(min, <=, max);
790
        // List protocol version in descending order to ensure that the server
53,974✔
791
        // selects the highest possible version.
50,120✔
792
        for (int version = max; version >= min; --version) {
50,120✔
793
            sec_websocket_protocol.push_back(util::format("%1%2", protocol_prefix, version)); // Throws
3,854✔
794
        }
795
    }
3,854✔
796

3,854✔
797
    logger.info("Connecting to '%1%2:%3%4'", to_string(m_server_endpoint.envelope), m_server_endpoint.address,
798
                m_server_endpoint.port, m_http_request_path_prefix);
3,854✔
799

3,854✔
800
    m_websocket_error_received = false;
3,854✔
801
    m_websocket =
3,854✔
802
        m_client.m_socket_provider->connect(std::make_unique<WebSocketObserverShim>(this),
3,854✔
803
                                            WebSocketEndpoint{
3,854✔
804
                                                m_server_endpoint.address,
3,854✔
805
                                                m_server_endpoint.port,
3,854✔
806
                                                get_http_request_path(),
3,854✔
807
                                                std::move(sec_websocket_protocol),
808
                                                is_ssl(m_server_endpoint.envelope),
3,854✔
809
                                                /// DEPRECATED - The following will be removed in a future release
3,854✔
810
                                                {m_custom_http_headers.begin(), m_custom_http_headers.end()},
3,854✔
811
                                                m_verify_servers_ssl_certificate,
3,854✔
812
                                                m_ssl_trust_certificate_path,
3,854✔
813
                                                m_ssl_verify_callback,
3,854✔
814
                                                m_proxy_config,
3,854✔
815
                                            });
816
}
817

818

3,854✔
819
void Connection::initiate_connect_wait()
820
{
821
    // Deploy a watchdog to enforce an upper bound on the time it can take to
822
    // fully establish the connection (including SSL and WebSocket
823
    // handshakes). Without such a watchdog, connect operations could take very
3,854✔
824
    // long, or even indefinite time.
825
    milliseconds_type time = m_client.m_connect_timeout;
3,856✔
826

827
    m_connect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
828
        // If the operation is aborted, the connection object may have been
3,856✔
UNCOV
829
        // destroyed.
×
830
        if (status != ErrorCodes::OperationAborted)
3,856✔
831
            handle_connect_wait(status); // Throws
3,854✔
832
    });                                  // Throws
833
}
834

UNCOV
835

×
UNCOV
836
void Connection::handle_connect_wait(Status status)
×
837
{
×
838
    if (!status.is_ok()) {
×
839
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
840
        throw Exception(status);
841
    }
×
UNCOV
842

×
843
    REALM_ASSERT_EX(m_state == ConnectionState::connecting, m_state);
×
844
    logger.info("Connect timeout"); // Throws
×
845
    SessionErrorInfo error_info({ErrorCodes::SyncConnectTimeout, "Sync connection was not fully established in time"},
846
                                IsFatal{false});
UNCOV
847
    // If the connection fails/times out and the server has not been contacted yet, refresh the location
×
UNCOV
848
    // to make sure the websocket URL is correct
×
849
    if (!m_server_endpoint.is_verified) {
×
850
        error_info.server_requests_action = ProtocolErrorInfo::Action::RefreshLocation;
×
851
    }
×
852
    involuntary_disconnect(std::move(error_info), ConnectionTerminationReason::sync_connect_timeout); // Throws
853
}
854

855

3,652✔
856
void Connection::handle_connection_established()
857
{
3,652✔
858
    // Cancel connect timeout watchdog
859
    m_connect_timer.reset();
3,652✔
860

3,652✔
861
    m_state = ConnectionState::connected;
862
    m_server_endpoint.is_verified = true; // sync route is valid since connection is successful
3,652✔
863

3,652✔
864
    milliseconds_type now = monotonic_clock_now();
3,652✔
865
    m_pong_wait_started_at = now; // Initially, no time was spent waiting for a PONG message
866
    initiate_ping_delay(now);     // Throws
3,652✔
867

3,652✔
868
    bool fast_reconnect = false;
1,104✔
869
    if (m_disconnect_has_occurred) {
1,104✔
870
        milliseconds_type time = now - m_disconnect_time;
1,104✔
871
        if (time <= m_client.m_fast_reconnect_limit)
1,104✔
872
            fast_reconnect = true;
873
    }
4,874✔
874

4,874✔
875
    for (auto& p : m_sessions) {
4,874✔
876
        Session& sess = *p.second;
4,874✔
877
        sess.connection_established(fast_reconnect); // Throws
878
    }
3,652✔
879

3,652✔
880
    report_connection_state_change(ConnectionState::connected); // Throws
881
}
882

883

232✔
884
void Connection::schedule_urgent_ping()
232✔
885
{
232✔
886
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
128✔
887
    if (m_ping_delay_in_progress) {
128✔
888
        m_heartbeat_timer.reset();
128✔
889
        m_ping_delay_in_progress = false;
128✔
890
        m_minimize_next_ping_delay = true;
128✔
891
        milliseconds_type now = monotonic_clock_now();
128✔
892
        initiate_ping_delay(now); // Throws
128✔
893
        return;
104✔
894
    }
104✔
895
    REALM_ASSERT_EX(m_state == ConnectionState::connecting || m_waiting_for_pong, m_state);
104✔
896
    if (!m_send_ping)
104✔
897
        m_minimize_next_ping_delay = true;
898
}
899

900

3,924✔
901
void Connection::initiate_ping_delay(milliseconds_type now)
3,924✔
902
{
3,924✔
903
    REALM_ASSERT(!m_ping_delay_in_progress);
3,924✔
904
    REALM_ASSERT(!m_waiting_for_pong);
905
    REALM_ASSERT(!m_send_ping);
3,924✔
906

3,924✔
907
    milliseconds_type delay = 0;
3,784✔
908
    if (!m_minimize_next_ping_delay) {
909
        delay = m_client.m_ping_keepalive_period;
910
        // Make a randomized deduction of up to 10%, or up to 100% if this is
911
        // the first PING message to be sent since the connection was
912
        // established. The purpose of this randomized deduction is to reduce
913
        // the risk of many connections sending PING messages simultaneously to
3,784✔
914
        // the server.
3,784✔
915
        milliseconds_type max_deduction = (m_ping_sent ? delay / 10 : delay);
3,784✔
916
        auto distr = std::uniform_int_distribution<milliseconds_type>(0, max_deduction);
3,784✔
917
        milliseconds_type randomized_deduction = distr(m_client.get_random());
918
        delay -= randomized_deduction;
3,784✔
919
        // Deduct the time spent waiting for PONG
3,784✔
920
        REALM_ASSERT_3(now, >=, m_pong_wait_started_at);
3,784✔
921
        milliseconds_type spent_time = now - m_pong_wait_started_at;
3,776✔
922
        if (spent_time < delay) {
3,776✔
923
            delay -= spent_time;
8✔
924
        }
8✔
925
        else {
8✔
926
            delay = 0;
3,784✔
927
        }
140✔
928
    }
140✔
929
    else {
140✔
930
        m_minimize_next_ping_delay = false;
931
    }
932

3,924✔
933

934
    m_ping_delay_in_progress = true;
3,924✔
935

3,924✔
936
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(delay), [this](Status status) {
3,762✔
937
        if (status == ErrorCodes::OperationAborted)
162✔
UNCOV
938
            return;
×
939
        else if (!status.is_ok())
940
            throw Exception(status);
162✔
941

162✔
942
        handle_ping_delay();                                    // Throws
3,924✔
943
    });                                                         // Throws
3,924✔
944
    logger.debug("Will emit a ping in %1 milliseconds", delay); // Throws
945
}
946

947

162✔
948
void Connection::handle_ping_delay()
162✔
949
{
162✔
950
    REALM_ASSERT(m_ping_delay_in_progress);
162✔
951
    m_ping_delay_in_progress = false;
952
    m_send_ping = true;
162✔
953

954
    initiate_pong_timeout(); // Throws
162✔
955

114✔
956
    if (m_state == ConnectionState::connected && !m_sending)
162✔
957
        send_next_message(); // Throws
958
}
959

960

162✔
961
void Connection::initiate_pong_timeout()
162✔
962
{
162✔
963
    REALM_ASSERT(!m_ping_delay_in_progress);
162✔
964
    REALM_ASSERT(!m_waiting_for_pong);
965
    REALM_ASSERT(m_send_ping);
162✔
966

162✔
967
    m_waiting_for_pong = true;
968
    m_pong_wait_started_at = monotonic_clock_now();
162✔
969

162✔
970
    milliseconds_type time = m_client.m_pong_keepalive_timeout;
162✔
971
    m_heartbeat_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
150✔
972
        if (status == ErrorCodes::OperationAborted)
12✔
UNCOV
973
            return;
×
974
        else if (!status.is_ok())
975
            throw Exception(status);
12✔
976

12✔
977
        handle_pong_timeout(); // Throws
162✔
978
    });                        // Throws
979
}
980

981

12✔
982
void Connection::handle_pong_timeout()
12✔
983
{
12✔
984
    REALM_ASSERT(m_waiting_for_pong);
12✔
985
    logger.debug("Timeout on reception of PONG message"); // Throws
12✔
986
    close_due_to_transient_error({ErrorCodes::ConnectionClosed, "Timed out waiting for PONG response from server"},
12✔
987
                                 ConnectionTerminationReason::pong_timeout);
988
}
989

990

100,568✔
991
void Connection::initiate_write_message(const OutputBuffer& out, Session* sess)
992
{
100,568✔
UNCOV
993
    // Stop sending messages if an websocket error was received.
×
994
    if (m_websocket_error_received)
995
        return;
100,568✔
996

100,496✔
997
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
1,474✔
998
        if (sentinel->destroyed) {
1,474✔
999
            return;
99,022✔
UNCOV
1000
        }
×
1001
        if (!status.is_ok()) {
1002
            if (status != ErrorCodes::Error::OperationAborted) {
×
UNCOV
1003
                // Write errors will be handled by the websocket_write_error_handler() callback
×
1004
                logger.error("Connection: write failed %1: %2", status.code_string(), status.reason());
×
1005
            }
×
1006
            return;
99,022✔
1007
        }
99,022✔
1008
        handle_write_message(); // Throws
100,568✔
1009
    });                         // Throws
100,568✔
1010
    m_sending_session = sess;
100,568✔
1011
    m_sending = true;
1012
}
1013

1014

99,022✔
1015
void Connection::handle_write_message()
99,022✔
1016
{
99,022✔
1017
    m_sending_session->message_sent(); // Throws
124✔
1018
    if (m_sending_session->m_state == Session::Deactivated) {
124✔
1019
        finish_session_deactivation(m_sending_session);
99,022✔
1020
    }
99,022✔
1021
    m_sending_session = nullptr;
99,022✔
1022
    m_sending = false;
99,022✔
1023
    send_next_message(); // Throws
1024
}
1025

1026

164,806✔
1027
void Connection::send_next_message()
164,806✔
1028
{
164,806✔
1029
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
164,806✔
1030
    REALM_ASSERT(!m_sending_session);
164,806✔
1031
    REALM_ASSERT(!m_sending);
150✔
1032
    if (m_send_ping) {
150✔
1033
        send_ping(); // Throws
150✔
1034
        return;
231,000✔
1035
    }
1036
    while (!m_sessions_enlisted_to_send.empty()) {
1037
        // The state of being connected is not supposed to be able to change
1038
        // across this loop thanks to the "no callback reentrance" guarantee
167,184✔
1039
        // provided by Websocket::async_write_text(), and friends.
1040
        REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
167,184✔
1041

167,184✔
1042
        Session& sess = *m_sessions_enlisted_to_send.front();
167,184✔
1043
        m_sessions_enlisted_to_send.pop_front();
1044
        sess.send_message(); // Throws
167,184✔
1045

2,554✔
1046
        if (sess.m_state == Session::Deactivated) {
2,554✔
1047
            finish_session_deactivation(&sess);
1048
        }
1049

1050
        // An enlisted session may choose to not send a message. In that case,
167,184✔
1051
        // we should pass the opportunity to the next enlisted session.
100,840✔
1052
        if (m_sending)
167,184✔
1053
            break;
164,656✔
1054
    }
1055
}
1056

1057

150✔
1058
void Connection::send_ping()
150✔
1059
{
150✔
1060
    REALM_ASSERT(!m_ping_delay_in_progress);
150✔
1061
    REALM_ASSERT(m_waiting_for_pong);
1062
    REALM_ASSERT(m_send_ping);
150✔
1063

150✔
1064
    m_send_ping = false;
134✔
1065
    if (m_reconnect_info.scheduled_reset)
1066
        m_ping_after_scheduled_reset_of_reconnect_info = true;
150✔
1067

150✔
1068
    m_last_ping_sent_at = monotonic_clock_now();
150✔
1069
    logger.debug("Sending: PING(timestamp=%1, rtt=%2)", m_last_ping_sent_at,
1070
                 m_previous_ping_rtt); // Throws
150✔
1071

150✔
1072
    ClientProtocol& protocol = get_client_protocol();
150✔
1073
    OutputBuffer& out = get_output_buffer();
150✔
1074
    protocol.make_ping(out, m_last_ping_sent_at, m_previous_ping_rtt); // Throws
150✔
1075
    initiate_write_ping(out);                                          // Throws
150✔
1076
    m_ping_sent = true;
1077
}
1078

1079

150✔
1080
void Connection::initiate_write_ping(const OutputBuffer& out)
150✔
1081
{
150✔
1082
    m_websocket->async_write_binary(out.as_span(), [this, sentinel = m_websocket_sentinel](Status status) {
2✔
1083
        if (sentinel->destroyed) {
2✔
1084
            return;
148✔
UNCOV
1085
        }
×
1086
        if (!status.is_ok()) {
1087
            if (status != ErrorCodes::Error::OperationAborted) {
×
UNCOV
1088
                // Write errors will be handled by the websocket_write_error_handler() callback
×
1089
                logger.error("Connection: send ping failed %1: %2", status.code_string(), status.reason());
×
1090
            }
×
1091
            return;
148✔
1092
        }
148✔
1093
        handle_write_ping(); // Throws
150✔
1094
    });                      // Throws
150✔
1095
    m_sending = true;
1096
}
1097

1098

148✔
1099
void Connection::handle_write_ping()
148✔
1100
{
148✔
1101
    REALM_ASSERT(m_sending);
148✔
1102
    REALM_ASSERT(!m_sending_session);
148✔
1103
    m_sending = false;
148✔
1104
    send_next_message(); // Throws
1105
}
1106

1107

80,100✔
1108
void Connection::handle_message_received(util::Span<const char> data)
1109
{
1110
    // parse_message_received() parses the message and calls the proper handler
80,100✔
1111
    // on the Connection object (this).
80,100✔
1112
    get_client_protocol().parse_message_received<Connection>(*this, std::string_view(data.data(), data.size()));
1113
}
1114

1115

4,410✔
1116
void Connection::initiate_disconnect_wait()
4,410✔
1117
{
1118
    REALM_ASSERT(!m_reconnect_delay_in_progress);
4,410✔
1119

1,886✔
1120
    if (m_disconnect_delay_in_progress) {
1,886✔
1121
        m_reconnect_disconnect_timer.reset();
1,886✔
1122
        m_disconnect_delay_in_progress = false;
1123
    }
4,410✔
1124

1125
    milliseconds_type time = m_client.m_connection_linger_time;
4,410✔
1126

1127
    m_reconnect_disconnect_timer = m_client.create_timer(std::chrono::milliseconds(time), [this](Status status) {
1128
        // If the operation is aborted, the connection object may have been
4,410✔
1129
        // destroyed.
12✔
1130
        if (status != ErrorCodes::OperationAborted)
4,410✔
1131
            handle_disconnect_wait(status); // Throws
4,410✔
1132
    });                                     // Throws
4,410✔
1133
    m_disconnect_delay_in_progress = true;
1134
}
1135

1136

12✔
1137
void Connection::handle_disconnect_wait(Status status)
12✔
UNCOV
1138
{
×
UNCOV
1139
    if (!status.is_ok()) {
×
1140
        REALM_ASSERT(status != ErrorCodes::OperationAborted);
×
1141
        throw Exception(status);
1142
    }
12✔
1143

1144
    m_disconnect_delay_in_progress = false;
12✔
1145

12✔
1146
    REALM_ASSERT_EX(m_state != ConnectionState::disconnected, m_state);
12✔
UNCOV
1147
    if (m_num_active_unsuspended_sessions == 0) {
×
1148
        if (m_client.m_connection_linger_time > 0)
12✔
1149
            logger.detail("Linger time expired"); // Throws
12✔
1150
        voluntary_disconnect();                   // Throws
12✔
1151
        logger.info("Disconnected");              // Throws
12✔
1152
    }
1153
}
1154

1155

16✔
1156
void Connection::close_due_to_protocol_error(Status status)
16✔
1157
{
16✔
1158
    SessionErrorInfo error_info(std::move(status), IsFatal{true});
16✔
1159
    error_info.server_requests_action = ProtocolErrorInfo::Action::ProtocolViolation;
16✔
1160
    involuntary_disconnect(std::move(error_info),
16✔
1161
                           ConnectionTerminationReason::sync_protocol_violation); // Throws
1162
}
1163

1164

470✔
1165
void Connection::close_due_to_client_side_error(Status status, IsFatal is_fatal, ConnectionTerminationReason reason)
470✔
1166
{
1167
    logger.info("Connection closed due to error: %1", status); // Throws
470✔
1168

470✔
1169
    involuntary_disconnect(SessionErrorInfo{std::move(status), is_fatal}, reason); // Throw
1170
}
1171

1172

644✔
1173
void Connection::close_due_to_transient_error(Status status, ConnectionTerminationReason reason)
644✔
1174
{
644✔
1175
    logger.info("Connection closed due to transient error: %1", status); // Throws
644✔
1176
    SessionErrorInfo error_info{std::move(status), IsFatal{false}};
1177
    error_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
644✔
1178

644✔
1179
    involuntary_disconnect(std::move(error_info), reason); // Throw
1180
}
1181

1182

1183
// Close connection due to error discovered on the server-side, and then
1184
// reported to the client by way of a connection-level ERROR message.
66✔
1185
void Connection::close_due_to_server_side_error(ProtocolError error_code, const ProtocolErrorInfo& info)
66✔
1186
{
66✔
1187
    logger.info("Connection closed due to error reported by server: %1 (%2)", info.message,
1188
                int(error_code)); // Throws
66✔
1189

66✔
1190
    const auto reason = info.is_fatal ? ConnectionTerminationReason::server_said_do_not_reconnect
66✔
1191
                                      : ConnectionTerminationReason::server_said_try_again_later;
66✔
1192
    involuntary_disconnect(SessionErrorInfo{info, protocol_error_to_status(error_code, info.message)},
66✔
1193
                           reason); // Throws
1194
}
1195

1196

3,856✔
1197
void Connection::disconnect(const SessionErrorInfo& info)
1198
{
3,856✔
1199
    // Cancel connect timeout watchdog
1200
    m_connect_timer.reset();
3,856✔
1201

3,648✔
1202
    if (m_state == ConnectionState::connected) {
3,648✔
1203
        m_disconnect_time = monotonic_clock_now();
1204
        m_disconnect_has_occurred = true;
1205

1206
        // Sessions that are in the Deactivating state at this time can be
1207
        // immediately discarded, in part because they are no longer enlisted to
1208
        // send. Such sessions will be taken to the Deactivated state by
1209
        // Session::connection_lost(), and then they will be removed from
3,648✔
1210
        // `m_sessions`.
8,150✔
1211
        auto i = m_sessions.begin(), end = m_sessions.end();
1212
        while (i != end) {
4,502✔
1213
            // Prevent invalidation of the main iterator when erasing elements
4,502✔
1214
            auto j = i++;
4,502✔
1215
            Session& sess = *j->second;
4,502✔
1216
            sess.connection_lost(); // Throws
2,196✔
1217
            if (sess.m_state == Session::Unactivated || sess.m_state == Session::Deactivated)
4,502✔
1218
                m_sessions.erase(j);
3,648✔
1219
        }
1220
    }
3,856✔
1221

1222
    change_state_to_disconnected();
3,856✔
1223

3,856✔
1224
    m_ping_delay_in_progress = false;
3,856✔
1225
    m_waiting_for_pong = false;
3,856✔
1226
    m_send_ping = false;
3,856✔
1227
    m_minimize_next_ping_delay = false;
3,856✔
1228
    m_ping_after_scheduled_reset_of_reconnect_info = false;
3,856✔
1229
    m_ping_sent = false;
3,856✔
1230
    m_heartbeat_timer.reset();
1231
    m_previous_ping_rtt = 0;
3,856✔
1232

3,856✔
1233
    m_websocket_sentinel->destroyed = true;
3,856✔
1234
    m_websocket_sentinel.reset();
3,856✔
1235
    m_websocket.reset();
3,856✔
1236
    m_input_body_buffer.reset();
3,856✔
1237
    m_sending_session = nullptr;
3,856✔
1238
    m_sessions_enlisted_to_send.clear();
1239
    m_sending = false;
3,856✔
1240

3,856✔
1241
    report_connection_state_change(ConnectionState::disconnected, info); // Throws
3,856✔
1242
    initiate_reconnect_wait();                                           // Throws
1243
}
1244

113,854✔
1245
bool Connection::is_flx_sync_connection() const noexcept
113,854✔
1246
{
113,854✔
1247
    return m_server_endpoint.server_mode != SyncServerMode::PBS;
1248
}
1249

144✔
1250
void Connection::receive_pong(milliseconds_type timestamp)
144✔
1251
{
1252
    logger.debug("Received: PONG(timestamp=%1)", timestamp);
144✔
1253

144✔
UNCOV
1254
    bool legal_at_this_time = (m_waiting_for_pong && !m_send_ping);
×
UNCOV
1255
    if (REALM_UNLIKELY(!legal_at_this_time)) {
×
1256
        close_due_to_protocol_error(
×
1257
            {ErrorCodes::SyncProtocolInvariantFailed, "Received PONG message when it was not valid"}); // Throws
×
1258
        return;
1259
    }
144✔
UNCOV
1260

×
UNCOV
1261
    if (REALM_UNLIKELY(timestamp != m_last_ping_sent_at)) {
×
1262
        close_due_to_protocol_error(
×
1263
            {ErrorCodes::SyncProtocolInvariantFailed,
×
1264
             util::format("Received PONG message with an invalid timestamp (expected %1, received %2)",
×
1265
                          m_last_ping_sent_at, timestamp)}); // Throws
×
1266
        return;
1267
    }
144✔
1268

144✔
1269
    milliseconds_type now = monotonic_clock_now();
144✔
1270
    milliseconds_type round_trip_time = now - timestamp;
144✔
1271
    logger.debug("Round trip time was %1 milliseconds", round_trip_time);
1272
    m_previous_ping_rtt = round_trip_time;
1273

1274
    // If this PONG message is a response to a PING mesage that was sent after
1275
    // the last invocation of cancel_reconnect_delay(), then the connection is
144✔
1276
    // still good, and we do not have to skip the next reconnect delay.
124✔
1277
    if (m_ping_after_scheduled_reset_of_reconnect_info) {
124✔
1278
        REALM_ASSERT(m_reconnect_info.scheduled_reset);
124✔
1279
        m_ping_after_scheduled_reset_of_reconnect_info = false;
124✔
1280
        m_reconnect_info.scheduled_reset = false;
1281
    }
144✔
1282

144✔
1283
    m_heartbeat_timer.reset();
1284
    m_waiting_for_pong = false;
144✔
1285

1286
    initiate_ping_delay(now); // Throws
144✔
UNCOV
1287

×
1288
    if (m_client.m_roundtrip_time_handler)
144✔
1289
        m_client.m_roundtrip_time_handler(m_previous_ping_rtt); // Throws
1290
}
1291

73,766✔
1292
Session* Connection::find_and_validate_session(session_ident_type session_ident, std::string_view message) noexcept
73,766✔
UNCOV
1293
{
×
UNCOV
1294
    if (session_ident == 0) {
×
1295
        return nullptr;
1296
    }
73,766✔
1297

73,766✔
1298
    auto* sess = get_session(session_ident);
73,762✔
1299
    if (REALM_LIKELY(sess)) {
73,762✔
1300
        return sess;
1301
    }
4✔
UNCOV
1302
    // Check the history to see if the message received was for a previous session
×
UNCOV
1303
    if (auto it = m_session_history.find(session_ident); it == m_session_history.end()) {
×
1304
        logger.error("Bad session identifier in %1 message, session_ident = %2", message, session_ident);
×
1305
        close_due_to_protocol_error(
×
1306
            {ErrorCodes::SyncProtocolInvariantFailed,
×
1307
             util::format("Received message %1 for session iden %2 when that session never existed", message,
×
1308
                          session_ident)});
4✔
1309
    }
4✔
1310
    else {
4✔
1311
        logger.error("Received %1 message for closed session, session_ident = %2", message,
4✔
1312
                     session_ident); // Throws
4✔
1313
    }
73,766✔
1314
    return nullptr;
1315
}
1316

798✔
1317
void Connection::receive_error_message(const ProtocolErrorInfo& info, session_ident_type session_ident)
798✔
1318
{
798✔
1319
    Session* sess = nullptr;
728✔
1320
    if (session_ident != 0) {
728✔
UNCOV
1321
        sess = find_and_validate_session(session_ident, "ERROR");
×
UNCOV
1322
        if (REALM_UNLIKELY(!sess)) {
×
1323
            return;
728✔
1324
        }
×
UNCOV
1325
        if (auto status = sess->receive_error_message(info); !status.is_ok()) {
×
1326
            close_due_to_protocol_error(std::move(status)); // Throws
×
1327
            return;
1328
        }
728✔
UNCOV
1329

×
UNCOV
1330
        if (sess->m_state == Session::Deactivated) {
×
1331
            finish_session_deactivation(sess);
728✔
1332
        }
728✔
1333
        return;
1334
    }
70✔
1335

70✔
1336
    logger.info("Received: ERROR \"%1\" (error_code=%2, is_fatal=%3, session_ident=%4, error_action=%5)",
70✔
1337
                info.message, info.raw_error_code, info.is_fatal, session_ident,
1338
                info.server_requests_action); // Throws
70✔
1339

70✔
1340
    bool known_error_code = bool(get_protocol_error_message(info.raw_error_code));
66✔
1341
    if (REALM_LIKELY(known_error_code)) {
66✔
1342
        ProtocolError error_code = ProtocolError(info.raw_error_code);
66✔
1343
        if (REALM_LIKELY(!is_session_level_error(error_code))) {
66✔
1344
            close_due_to_server_side_error(error_code, info); // Throws
66✔
UNCOV
1345
            return;
×
UNCOV
1346
        }
×
1347
        close_due_to_protocol_error(
×
1348
            {ErrorCodes::SyncProtocolInvariantFailed,
×
1349
             util::format("Received ERROR message with a non-connection-level error code %1 without a session ident",
×
1350
                          info.raw_error_code)});
4✔
1351
    }
4✔
1352
    else {
4✔
1353
        close_due_to_protocol_error(
4✔
1354
            {ErrorCodes::SyncProtocolInvariantFailed,
4✔
1355
             util::format("Received ERROR message with unknown error code %1", info.raw_error_code)});
70✔
1356
    }
1357
}
1358

1359

1360
void Connection::receive_query_error_message(int raw_error_code, std::string_view message, int64_t query_version,
20✔
1361
                                             session_ident_type session_ident)
20✔
UNCOV
1362
{
×
UNCOV
1363
    if (session_ident == 0) {
×
1364
        return close_due_to_protocol_error(
×
1365
            {ErrorCodes::SyncProtocolInvariantFailed, "Received query error message for session ident 0"});
1366
    }
20✔
UNCOV
1367

×
UNCOV
1368
    if (!is_flx_sync_connection()) {
×
1369
        return close_due_to_protocol_error({ErrorCodes::SyncProtocolInvariantFailed,
×
1370
                                            "Received a FLX query error message on a non-FLX sync connection"});
1371
    }
20✔
1372

20✔
1373
    Session* sess = find_and_validate_session(session_ident, "QUERY_ERROR");
20✔
1374
    if (REALM_UNLIKELY(!sess)) {
20✔
1375
        return;
1376
    }
1377

1378
    if (auto status = sess->receive_query_error_message(raw_error_code, message, query_version); !status.is_ok()) {
3,782✔
1379
        close_due_to_protocol_error(std::move(status));
3,782✔
1380
    }
3,782✔
UNCOV
1381
}
×
UNCOV
1382

×
1383

1384
void Connection::receive_ident_message(session_ident_type session_ident, SaltedFileIdent client_file_ident)
3,782✔
UNCOV
1385
{
×
1386
    Session* sess = find_and_validate_session(session_ident, "IDENT");
3,782✔
1387
    if (REALM_UNLIKELY(!sess)) {
1388
        return;
1389
    }
48,460✔
1390

48,460✔
1391
    if (auto status = sess->receive_ident_message(client_file_ident); !status.is_ok())
48,460✔
1392
        close_due_to_protocol_error(std::move(status)); // Throws
×
UNCOV
1393
}
×
1394

1395
void Connection::receive_download_message(session_ident_type session_ident, const DownloadMessage& message)
48,460✔
1396
{
2✔
1397
    Session* sess = find_and_validate_session(session_ident, "DOWNLOAD");
2✔
1398
    if (REALM_UNLIKELY(!sess)) {
48,460✔
1399
        return;
1400
    }
1401

16,404✔
1402
    if (auto status = sess->receive_download_message(message); !status.is_ok()) {
16,404✔
1403
        close_due_to_protocol_error(std::move(status));
16,404✔
UNCOV
1404
    }
×
UNCOV
1405
}
×
1406

1407
void Connection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
16,404✔
1408
{
10✔
1409
    Session* sess = find_and_validate_session(session_ident, "MARK");
16,404✔
1410
    if (REALM_UNLIKELY(!sess)) {
1411
        return;
1412
    }
1413

4,314✔
1414
    if (auto status = sess->receive_mark_message(request_ident); !status.is_ok())
4,314✔
1415
        close_due_to_protocol_error(std::move(status)); // Throws
4,314✔
UNCOV
1416
}
×
UNCOV
1417

×
1418

1419
void Connection::receive_unbound_message(session_ident_type session_ident)
4,314✔
UNCOV
1420
{
×
UNCOV
1421
    Session* sess = find_and_validate_session(session_ident, "UNBOUND");
×
UNCOV
1422
    if (REALM_UNLIKELY(!sess)) {
×
1423
        return;
1424
    }
4,314✔
1425

4,314✔
1426
    if (auto status = sess->receive_unbound_message(); !status.is_ok()) {
4,314✔
1427
        close_due_to_protocol_error(std::move(status)); // Throws
4,314✔
1428
        return;
1429
    }
1430

1431
    if (sess->m_state == Session::Deactivated) {
1432
        finish_session_deactivation(sess);
60✔
1433
    }
60✔
1434
}
60✔
UNCOV
1435

×
UNCOV
1436

×
1437
void Connection::receive_test_command_response(session_ident_type session_ident, request_ident_type request_ident,
1438
                                               std::string_view body)
60✔
UNCOV
1439
{
×
UNCOV
1440
    Session* sess = find_and_validate_session(session_ident, "TEST_COMMAND");
×
1441
    if (REALM_UNLIKELY(!sess)) {
60✔
1442
        return;
1443
    }
1444

1445
    if (auto status = sess->receive_test_command_response(request_ident, body); !status.is_ok()) {
1446
        close_due_to_protocol_error(std::move(status));
6,118✔
1447
    }
6,118✔
1448
}
6,118✔
1449

6,118✔
1450

6,118✔
UNCOV
1451
void Connection::receive_server_log_message(session_ident_type session_ident, util::Logger::Level level,
×
UNCOV
1452
                                            std::string_view message)
×
UNCOV
1453
{
×
1454
    std::string prefix;
1455
    if (REALM_LIKELY(!m_appservices_coid.empty())) {
6,118✔
1456
        prefix = util::format("Server[%1]", m_appservices_coid);
4,054✔
1457
    }
4,032✔
1458
    else {
4,032✔
1459
        prefix = "Server";
4,032✔
1460
    }
1461

22✔
1462
    if (session_ident != 0) {
22✔
1463
        if (auto sess = get_session(session_ident)) {
22✔
1464
            sess->logger.log(LogCategory::session, level, "%1 log: %2", prefix, message);
4,054✔
1465
            return;
1466
        }
2,064✔
1467

2,064✔
1468
        logger.log(util::LogCategory::session, level, "%1 log for unknown session %2: %3", prefix, session_ident,
1469
                   message);
1470
        return;
1471
    }
5,716✔
1472

1473
    logger.log(level, "%1 log: %2", prefix, message);
5,716✔
1474
}
2,530✔
1475

2,530✔
1476

2,530✔
1477
void Connection::receive_appservices_request_id(std::string_view coid)
2,530✔
1478
{
5,716✔
1479
    // Only set once per connection
1480
    if (!coid.empty() && m_appservices_coid.empty()) {
1481
        m_appservices_coid = coid;
UNCOV
1482
        logger.log(util::LogCategory::session, util::LogCategory::Level::info,
×
UNCOV
1483
                   "Connected to app services with request id: \"%1\"", m_appservices_coid);
×
UNCOV
1484
    }
×
1485
}
1486

1487

1488
void Connection::handle_protocol_error(Status status)
1489
{
1490
    close_due_to_protocol_error(std::move(status));
1491
}
1492

1493

1494
// Sessions are guaranteed to be granted the opportunity to send a message in
1495
// the order that they enlist. Note that this is important to ensure
1496
// nonoverlapping communication with the server for consecutive sessions
168,836✔
1497
// associated with the same Realm file.
168,836✔
1498
//
168,836✔
1499
// CAUTION: The specified session may get destroyed before this function
168,836✔
1500
// returns, but only if its Session::send_message() puts it into the Deactivated
65,520✔
1501
// state.
168,836✔
1502
void Connection::enlist_to_send(Session* sess)
1503
{
1504
    REALM_ASSERT_EX(m_state == ConnectionState::connected, m_state);
1505
    m_sessions_enlisted_to_send.push_back(sess); // Throws
72✔
1506
    if (!m_sending)
72✔
1507
        send_next_message(); // Throws
72✔
1508
}
1509

1510

4,426✔
1511
std::string Connection::get_active_appservices_connection_id()
4,426✔
1512
{
1513
    return m_appservices_coid;
4,426✔
1514
}
4,336✔
1515

1516
void Session::cancel_resumption_delay()
90✔
1517
{
1518
    REALM_ASSERT_EX(m_state == Active, m_state);
90✔
1519

1520
    if (!m_suspended)
90✔
1521
        return;
64✔
1522

1523
    m_suspended = false;
90✔
1524

90✔
1525
    logger.debug("Resumed"); // Throws
8✔
1526

8✔
1527
    if (unbind_process_complete())
1528
        initiate_rebind(); // Throws
90✔
1529

90✔
1530
    m_conn.one_more_active_unsuspended_session(); // Throws
1531
    if (m_try_again_activation_timer) {
1532
        m_try_again_activation_timer.reset();
1533
    }
1534

23,702✔
1535
    on_resumed(); // Throws
23,702✔
1536
}
23,658✔
1537

23,658✔
1538

1539
void Session::gather_pending_compensating_writes(util::Span<Changeset> changesets,
44✔
1540
                                                 std::vector<ProtocolErrorInfo>* out)
44✔
1541
{
44✔
1542
    if (m_pending_compensating_write_errors.empty() || changesets.empty()) {
44✔
1543
        return;
44✔
1544
    }
44✔
1545

44✔
1546
#ifdef REALM_DEBUG
44✔
1547
    REALM_ASSERT_DEBUG(
44✔
1548
        std::is_sorted(m_pending_compensating_write_errors.begin(), m_pending_compensating_write_errors.end(),
1549
                       [](const ProtocolErrorInfo& lhs, const ProtocolErrorInfo& rhs) {
88✔
1550
                           REALM_ASSERT_DEBUG(lhs.compensating_write_server_version.has_value());
88✔
1551
                           REALM_ASSERT_DEBUG(rhs.compensating_write_server_version.has_value());
44✔
1552
                           return *lhs.compensating_write_server_version < *rhs.compensating_write_server_version;
44✔
1553
                       }));
44✔
1554
#endif
44✔
1555

44✔
1556
    while (!m_pending_compensating_write_errors.empty() &&
44✔
1557
           *m_pending_compensating_write_errors.front().compensating_write_server_version <=
44✔
1558
               changesets.back().version) {
1559
        auto& cur_error = m_pending_compensating_write_errors.front();
1560
        REALM_ASSERT_3(*cur_error.compensating_write_server_version, >=, changesets.front().version);
1561
        out->push_back(std::move(cur_error));
1562
        m_pending_compensating_write_errors.pop_front();
1563
    }
45,518✔
1564
}
45,518✔
1565

45,518✔
1566

21,792✔
UNCOV
1567
void Session::integrate_changesets(const SyncProgress& progress, std::uint_fast64_t downloadable_bytes,
×
UNCOV
1568
                                   const ReceivedChangesets& received_changesets, VersionInfo& version_info,
×
UNCOV
1569
                                   DownloadBatchState download_batch_state)
×
UNCOV
1570
{
×
1571
    auto& history = get_history();
21,792✔
1572
    if (received_changesets.empty()) {
21,792✔
1573
        if (download_batch_state == DownloadBatchState::MoreToCome) {
21,792✔
1574
            throw IntegrationException(ErrorCodes::SyncProtocolInvariantFailed,
1575
                                       "received empty download message that was not the last in batch",
23,726✔
1576
                                       ProtocolError::bad_progress);
23,726✔
1577
        }
23,726✔
1578
        history.set_sync_progress(progress, downloadable_bytes, version_info); // Throws
23,726✔
1579
        return;
23,726✔
1580
    }
23,702✔
1581

23,702✔
1582
    std::vector<ProtocolErrorInfo> pending_compensating_write_errors;
23,726✔
1583
    auto transact = get_db()->start_read();
15,496✔
1584
    history.integrate_server_changesets(
15,496✔
1585
        progress, downloadable_bytes, received_changesets, version_info, download_batch_state, logger, transact,
15,496✔
1586
        [&](const TransactionRef&, util::Span<Changeset> changesets) {
8,230✔
1587
            gather_pending_compensating_writes(changesets, &pending_compensating_write_errors);
8,230✔
1588
        }); // Throws
8,230✔
1589
    if (received_changesets.size() == 1) {
8,230✔
1590
        logger.debug("1 remote changeset integrated, producing client version %1",
1591
                     version_info.sync_version.version); // Throws
23,726✔
1592
    }
44✔
1593
    else {
44✔
1594
        logger.debug("%2 remote changesets integrated, producing client version %1",
44✔
1595
                     version_info.sync_version.version, received_changesets.size()); // Throws
44✔
1596
    }
44✔
1597

44✔
1598
    for (const auto& pending_error : pending_compensating_write_errors) {
44✔
1599
        logger.info("Reporting compensating write for client version %1 in server version %2: %3",
44✔
1600
                    pending_error.compensating_write_rejected_client_version,
44✔
1601
                    *pending_error.compensating_write_server_version, pending_error.message);
44✔
1602
        try {
44✔
UNCOV
1603
            on_connection_state_changed(
×
UNCOV
1604
                m_conn.get_state(),
×
1605
                SessionErrorInfo{pending_error,
44✔
1606
                                 protocol_error_to_status(static_cast<ProtocolError>(pending_error.raw_error_code),
23,726✔
1607
                                                          pending_error.message)});
1608
        }
1609
        catch (...) {
1610
            logger.error("Exception thrown while reporting compensating write: %1", exception_to_status());
40✔
1611
        }
40✔
1612
    }
40✔
1613
}
40✔
1614

1615

40✔
1616
void Session::on_integration_failure(const IntegrationException& error)
40✔
1617
{
40✔
1618
    REALM_ASSERT_EX(m_state == Active, m_state);
40✔
1619
    REALM_ASSERT(!m_client_error && !m_error_to_send);
1620
    logger.error("Failed to integrate downloaded changesets: %1", error.to_status());
40✔
1621

1622
    m_client_error = util::make_optional<IntegrationException>(error);
1623
    m_error_to_send = true;
1624
    SessionErrorInfo error_info{error.to_status(), IsFatal{false}};
40✔
1625
    error_info.server_requests_action = ProtocolErrorInfo::Action::Warning;
40✔
1626
    // Surface the error to the user otherwise is lost.
36✔
1627
    on_connection_state_changed(m_conn.get_state(), std::move(error_info));
36✔
1628

40✔
1629
    // Since the deactivation process has not been initiated, the UNBIND
1630
    // message cannot have been sent unless an ERROR message was received.
1631
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
47,486✔
1632
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
47,486✔
1633
        ensure_enlisted_to_send(); // Throws
47,486✔
1634
    }
1635
}
47,486✔
1636

47,486✔
1637
void Session::on_changesets_integrated(version_type client_version, const SyncProgress& progress)
1638
{
47,486✔
1639
    REALM_ASSERT_EX(m_state == Active, m_state);
572✔
1640
    REALM_ASSERT_3(progress.download.server_version, >=, m_download_progress.server_version);
1641

47,486✔
1642
    m_download_progress = progress.download;
1643
    m_progress = progress;
47,486✔
1644

1645
    if (progress.upload.client_version > m_upload_progress.client_version)
1646
        m_upload_progress = progress.upload;
47,486✔
1647

3,324✔
1648
    do_recognize_sync_version(client_version); // Allows upload process to resume
3,324✔
1649

3,324✔
1650
    check_for_download_completion(); // Throws
1651

1652
    // If the client migrated from PBS to FLX, create subscriptions when new tables are received from server.
1653
    if (auto migration_store = get_migration_store(); migration_store && m_is_flx_sync_session) {
47,486✔
1654
        auto& flx_subscription_store = *get_flx_subscription_store();
47,486✔
1655
        get_migration_store()->create_subscriptions(flx_subscription_store);
47,476✔
1656
    }
47,476✔
1657

47,486✔
1658
    // Since the deactivation process has not been initiated, the UNBIND
1659
    // message cannot have been sent unless an ERROR message was received.
1660
    REALM_ASSERT(m_suspended || m_error_message_received || !m_unbind_message_sent);
1661
    if (m_ident_message_sent && !m_error_message_received && !m_suspended) {
10,082✔
1662
        ensure_enlisted_to_send(); // Throws
1663
    }
10,082✔
1664
}
1665

1666

1667
Session::~Session()
10,082✔
1668
{
10,082✔
1669
    //    REALM_ASSERT_EX(m_state == Unactivated || m_state == Deactivated, m_state);
10,082✔
1670
}
10,082✔
1671

10,082✔
1672

10,082✔
1673
std::string Session::make_logger_prefix(session_ident_type ident)
1674
{
1675
    std::ostringstream out;
1676
    out.imbue(std::locale::classic());
10,078✔
1677
    out << "Session[" << ident << "]: "; // Throws
10,078✔
1678
    return out.str();                    // Throws
1679
}
10,078✔
1680

1681

10,082✔
1682
void Session::activate()
10,082✔
1683
{
10,082✔
1684
    REALM_ASSERT_EX(m_state == Unactivated, m_state);
1685

10,082✔
1686
    logger.debug("Activating"); // Throws
10,082✔
1687

9,706✔
1688
    if (REALM_LIKELY(!get_client().is_dry_run())) {
9,706✔
1689
        bool file_exists = util::File::exists(get_realm_path());
10,082✔
1690
        m_performing_client_reset = get_client_reset_config().has_value();
10,078✔
1691

10,078✔
1692
        logger.info("client_reset_config = %1, Realm exists = %2 ", m_performing_client_reset, file_exists);
10,078✔
1693
        if (!m_performing_client_reset) {
10,078✔
1694
            get_history().get_status(m_last_version_available, m_client_file_ident, m_progress); // Throws
10,078✔
1695
        }
10,078✔
1696
    }
1697
    logger.debug("client_file_ident = %1, client_file_ident_salt = %2", m_client_file_ident.ident,
10,078✔
1698
                 m_client_file_ident.salt); // Throws
10,078✔
1699
    m_upload_progress = m_progress.upload;
10,078✔
1700
    m_download_progress = m_progress.download;
10,078✔
1701
    REALM_ASSERT_3(m_last_version_available, >=, m_progress.upload.client_version);
10,078✔
1702
    init_progress_handler();
10,078✔
1703

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

10,078✔
1711
    reset_protocol_state();
1712
    m_state = Active;
10,078✔
1713

10,078✔
1714
    call_debug_hook(SyncClientHookEvent::SessionActivating);
10,078✔
1715

10,078✔
UNCOV
1716
    REALM_ASSERT(!m_suspended);
×
UNCOV
1717
    m_conn.one_more_active_unsuspended_session(); // Throws
×
1718

10,078✔
1719
    try {
4✔
1720
        process_pending_flx_bootstrap();
4✔
1721
    }
1722
    catch (const IntegrationException& error) {
1723
        on_integration_failure(error);
10,080✔
1724
    }
10,080✔
1725
    catch (...) {
1726
        on_integration_failure(IntegrationException(exception_to_status()));
1727
    }
1728

1729
    // Checks if there is a pending client reset
1730
    handle_pending_client_reset_acknowledgement();
10,080✔
1731
}
10,080✔
1732

1733

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

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

5,902✔
1742
    m_state = Deactivating;
5,902✔
1743

5,902✔
1744
    if (!m_suspended)
1745
        m_conn.one_less_active_unsuspended_session(); // Throws
1746

1747
    if (m_enlisted_to_send) {
1748
        REALM_ASSERT(!unbind_process_complete());
4,178✔
1749
        return;
894✔
1750
    }
1751

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

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

10,082✔
1768

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

1774
    logger.debug("Deactivation completed"); // Throws
1775
}
1776

1777

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

1797
        // Session life cycle state is Deactivating or the unbinding process has
1798
        // been initiated by a session specific ERROR message
1799
        if (!m_unbind_message_sent)
157,888✔
1800
            send_unbind_message(); // Throws
1801
        return;
157,888✔
1802
    }
9,334✔
1803

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

148✔
1808
    if (!m_bind_message_sent)
148✔
1809
        return send_bind_message(); // Throws
148,554✔
1810

60✔
1811
    if (!m_ident_message_sent) {
60✔
1812
        if (have_client_file_ident())
1813
            send_ident_message(); // Throws
148,494✔
1814
        return;
7,560✔
1815
    }
7,560✔
1816

7,560✔
1817
    const auto has_pending_test_command = std::any_of(m_pending_test_commands.begin(), m_pending_test_commands.end(),
7,560✔
1818
                                                      [](const PendingTestCommand& command) {
1819
                                                          return command.pending;
140,934✔
1820
                                                      });
32✔
1821
    if (has_pending_test_command) {
1822
        return send_test_command_message();
1823
    }
140,902✔
1824

12✔
1825
    if (m_error_to_send)
12✔
1826
        return send_json_error_message(); // Throws
1827

140,890✔
1828
    // Stop sending upload, mark and query messages when the client detects an error.
17,174✔
1829
    if (m_client_error) {
1830
        return;
123,718✔
1831
    }
123,716✔
1832

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

15,278✔
1836
    auto is_upload_allowed = [&]() -> bool {
15,278✔
UNCOV
1837
        if (!m_is_flx_sync_session) {
×
UNCOV
1838
            return true;
×
1839
        }
1840

15,278✔
1841
        auto migration_store = get_migration_store();
15,278✔
1842
        if (!migration_store) {
15,250✔
1843
            return true;
15,250✔
1844
        }
1845

1846
        auto sentinel_query_version = migration_store->get_sentinel_subscription_set_version();
28✔
1847
        if (!sentinel_query_version) {
15,278✔
1848
            return true;
1849
        }
123,716✔
1850

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

123,698✔
1855
    if (!is_upload_allowed()) {
108,436✔
1856
        return;
108,436✔
1857
    }
1858

15,262✔
1859
    auto check_pending_flx_version = [&]() -> bool {
2,536✔
1860
        if (!m_is_flx_sync_session) {
2,536✔
1861
            return false;
1862
        }
12,726✔
1863

1864
        if (!m_allow_upload) {
12,726✔
1865
            return false;
10,662✔
1866
        }
10,662✔
1867

1868
        m_pending_flx_sub_set = get_flx_subscription_store()->get_next_pending_version(m_last_sent_flx_query_version);
2,064✔
1869

12,726✔
1870
        if (!m_pending_flx_sub_set) {
1871
            return false;
123,700✔
1872
        }
1,166✔
1873

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

58,770✔
1877
    if (check_pending_flx_version()) {
58,770✔
1878
        return send_query_change_message(); // throws
122,534✔
1879
    }
1880

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

9,334✔
1886

9,334✔
1887
void Session::send_bind_message()
9,334✔
1888
{
1889
    REALM_ASSERT_EX(m_state == Active, m_state);
9,334✔
1890

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

9,334✔
1895

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

5,356✔
1931
    m_bind_message_sent = true;
9,334✔
1932
    call_debug_hook(SyncClientHookEvent::BindMessageSent);
1933

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

7,560✔
1940

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

1,456✔
1948

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

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

1978
    m_ident_message_sent = true;
1979

1,166✔
1980
    // Other messages may be waiting to be sent
1,166✔
1981
    enlist_to_send(); // Throws
1,166✔
1982
}
1,166✔
1983

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

1,166✔
1992
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
1,166✔
1993
        return;
1,166✔
1994
    }
1,166✔
1995

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

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

2008
    m_last_sent_flx_query_version = latest_sub_set.version();
58,770✔
2009

58,770✔
2010
    request_download_completion_notification();
58,770✔
2011
}
58,770✔
2012

2013
void Session::send_upload_message()
58,770✔
UNCOV
2014
{
×
2015
    REALM_ASSERT_EX(m_state == Active, m_state);
2016
    REALM_ASSERT(m_ident_message_sent);
58,770✔
2017
    REALM_ASSERT(!m_unbind_message_sent);
58,770✔
2018

898✔
2019
    if (REALM_UNLIKELY(get_client().is_dry_run()))
898✔
2020
        return;
898✔
2021

2022
    version_type target_upload_version = m_last_version_available;
58,770✔
2023
    if (m_pending_flx_sub_set) {
58,770✔
2024
        REALM_ASSERT(m_is_flx_sync_session);
58,770✔
2025
        target_upload_version = m_pending_flx_sub_set->snapshot_version;
58,770✔
2026
    }
2027

58,770✔
2028
    std::vector<UploadChangeset> uploadable_changesets;
2029
    version_type locked_server_version = 0;
2030
    get_history().find_uploadable_changesets(m_upload_progress, target_upload_version, uploadable_changesets,
2031
                                             locked_server_version); // Throws
29,326✔
2032

270✔
2033
    if (uploadable_changesets.empty()) {
270✔
2034
        // Nothing more to upload right now
2035
        // If we need to limit upload up to some version other than the last client version available and there are no
270✔
2036
        // changes to upload, then there is no need to send an empty message.
270✔
2037
        if (m_pending_flx_sub_set) {
29,326✔
2038
            logger.debug("Empty UPLOAD was skipped (progress_client_version=%1, progress_server_version=%2)",
2039
                         m_upload_progress.client_version, m_upload_progress.last_integrated_server_version);
58,500✔
2040
            // Other messages may be waiting to be sent
628✔
2041
            return enlist_to_send(); // Throws
628✔
2042
        }
628✔
2043
    }
2044

58,500✔
2045
    if (m_pending_flx_sub_set && target_upload_version < m_last_version_available) {
58,500✔
2046
        logger.trace("Limiting UPLOAD message up to version %1 to send QUERY version %2",
2047
                     m_pending_flx_sub_set->snapshot_version, m_pending_flx_sub_set->query_version);
58,500✔
2048
    }
58,500✔
2049

58,500✔
2050
    version_type progress_client_version = m_upload_progress.client_version;
58,500✔
2051
    version_type progress_server_version = m_upload_progress.last_integrated_server_version;
2052

58,500✔
2053
    logger.debug("Sending: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
58,500✔
2054
                 "locked_server_version=%3, num_changesets=%4)",
2055
                 progress_client_version, progress_server_version, locked_server_version,
58,500✔
2056
                 uploadable_changesets.size()); // Throws
43,014✔
2057

43,014✔
2058
    ClientProtocol& protocol = m_conn.get_client_protocol();
43,014✔
2059
    ClientProtocol::UploadMessageBuilder upload_message_builder = protocol.make_upload_message_builder(); // Throws
43,014✔
2060

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

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

2093
#if 0 // Upload log compaction is currently not implemented
2094
        if (!get_client().m_disable_upload_compaction) {
2095
            ChangesetEncoder::Buffer encode_buffer;
2096

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

2109
                compact_changesets(&changeset, 1);
2110
                encode_changeset(changeset, encode_buffer);
2111

2112
                logger.debug(util::LogCategory::changeset, "Upload compaction: original size = %1, compacted size = %2", uc.changeset.size(),
2113
                             encode_buffer.size()); // Throws
2114
            }
2115

2116
            upload_message_builder.add_changeset(
43,014✔
2117
                uc.progress.client_version, uc.progress.last_integrated_server_version, uc.origin_timestamp,
43,014✔
2118
                uc.origin_file_ident, BinaryData{encode_buffer.data(), encode_buffer.size()}); // Throws
43,014✔
2119
        }
43,014✔
2120
        else
43,014✔
2121
#endif
43,014✔
2122
        {
43,014✔
2123
            upload_message_builder.add_changeset(uc.progress.client_version,
2124
                                                 uc.progress.last_integrated_server_version, uc.origin_timestamp,
58,500✔
2125
                                                 uc.origin_file_ident,
58,500✔
2126
                                                 uc.changeset); // Throws
58,500✔
2127
        }
58,500✔
2128
    }
58,500✔
2129

58,500✔
2130
    int protocol_version = m_conn.get_negotiated_protocol_version();
58,500✔
2131
    OutputBuffer& out = m_conn.get_output_buffer();
2132
    session_ident_type session_ident = get_ident();
2133
    upload_message_builder.make_upload_message(protocol_version, out, session_ident, progress_client_version,
58,500✔
2134
                                               progress_server_version,
58,500✔
2135
                                               locked_server_version); // Throws
2136
    m_conn.initiate_write_message(out, this);                          // Throws
2137

2138
    // Other messages may be waiting to be sent
17,174✔
2139
    enlist_to_send(); // Throws
17,174✔
2140
}
17,174✔
2141

17,174✔
2142

17,174✔
2143
void Session::send_mark_message()
2144
{
17,174✔
2145
    REALM_ASSERT_EX(m_state == Active, m_state);
17,174✔
2146
    REALM_ASSERT(m_ident_message_sent);
2147
    REALM_ASSERT(!m_unbind_message_sent);
17,174✔
2148
    REALM_ASSERT_3(m_target_download_mark, >, m_last_download_mark_sent);
17,174✔
2149

17,174✔
2150
    request_ident_type request_ident = m_target_download_mark;
17,174✔
2151
    logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
17,174✔
2152

2153
    ClientProtocol& protocol = m_conn.get_client_protocol();
17,174✔
2154
    OutputBuffer& out = m_conn.get_output_buffer();
2155
    session_ident_type session_ident = get_ident();
2156
    protocol.make_mark_message(out, session_ident, request_ident); // Throws
17,174✔
2157
    m_conn.initiate_write_message(out, this);                      // Throws
17,174✔
2158

2159
    m_last_download_mark_sent = request_ident;
2160

2161
    // Other messages may be waiting to be sent
6,740✔
2162
    enlist_to_send(); // Throws
6,740✔
2163
}
6,740✔
2164

6,740✔
2165

2166
void Session::send_unbind_message()
6,740✔
2167
{
2168
    REALM_ASSERT_EX(m_state == Deactivating || m_error_message_received || m_suspended, m_state);
6,740✔
2169
    REALM_ASSERT(m_bind_message_sent);
6,740✔
2170
    REALM_ASSERT(!m_unbind_message_sent);
6,740✔
2171

6,740✔
2172
    logger.debug("Sending: UNBIND"); // Throws
6,740✔
2173

2174
    ClientProtocol& protocol = m_conn.get_client_protocol();
6,740✔
2175
    OutputBuffer& out = m_conn.get_output_buffer();
6,740✔
2176
    session_ident_type session_ident = get_ident();
2177
    protocol.make_unbind_message(out, session_ident); // Throws
2178
    m_conn.initiate_write_message(out, this);         // Throws
2179

32✔
2180
    m_unbind_message_sent = true;
32✔
2181
}
32✔
2182

32✔
2183

32✔
2184
void Session::send_json_error_message()
32✔
2185
{
2186
    REALM_ASSERT_EX(m_state == Active, m_state);
32✔
2187
    REALM_ASSERT(m_ident_message_sent);
32✔
2188
    REALM_ASSERT(!m_unbind_message_sent);
32✔
2189
    REALM_ASSERT(m_error_to_send);
32✔
2190
    REALM_ASSERT(m_client_error);
2191

32✔
2192
    ClientProtocol& protocol = m_conn.get_client_protocol();
32✔
2193
    OutputBuffer& out = m_conn.get_output_buffer();
32✔
2194
    session_ident_type session_ident = get_ident();
2195
    auto protocol_error = m_client_error->error_for_server;
32✔
2196

32✔
2197
    auto message = util::format("%1", m_client_error->to_status());
32✔
2198
    logger.info("Sending: ERROR \"%1\" (error_code=%2, session_ident=%3)", message, static_cast<int>(protocol_error),
32✔
2199
                session_ident); // Throws
32✔
2200

2201
    nlohmann::json error_body_json;
32✔
2202
    error_body_json["message"] = std::move(message);
32✔
2203
    protocol.make_json_error_message(out, session_ident, static_cast<int>(protocol_error),
32✔
2204
                                     error_body_json.dump()); // Throws
2205
    m_conn.initiate_write_message(out, this);                 // Throws
2206

2207
    m_error_to_send = false;
60✔
2208
    enlist_to_send(); // Throws
60✔
2209
}
2210

60✔
2211

64✔
2212
void Session::send_test_command_message()
64✔
2213
{
64✔
2214
    REALM_ASSERT_EX(m_state == Active, m_state);
60✔
2215

2216
    auto it = std::find_if(m_pending_test_commands.begin(), m_pending_test_commands.end(),
60✔
2217
                           [](const PendingTestCommand& command) {
60✔
2218
                               return command.pending;
60✔
2219
                           });
2220
    REALM_ASSERT(it != m_pending_test_commands.end());
60✔
2221

60✔
2222
    ClientProtocol& protocol = m_conn.get_client_protocol();
2223
    OutputBuffer& out = m_conn.get_output_buffer();
60✔
2224
    auto session_ident = get_ident();
60✔
2225

2226
    logger.info("Sending: TEST_COMMAND \"%1\" (session_ident=%2, request_ident=%3)", it->body, session_ident, it->id);
60✔
2227
    protocol.make_test_command_message(out, session_ident, it->id, it->body);
60✔
2228

2229
    m_conn.initiate_write_message(out, this); // Throws;
2230
    it->pending = false;
3,734✔
2231

2232
    enlist_to_send();
2233
}
3,734✔
2234

2235
bool Session::client_reset_if_needed()
2236
{
2237
    // Regardless of what happens, once we return from this function we will
3,734✔
2238
    // no longer be in the middle of a client reset
3,734✔
2239
    m_performing_client_reset = false;
3,358✔
2240

3,358✔
2241
    // Even if we end up not actually performing a client reset, consume the
2242
    // config to ensure that the resources it holds are released
376✔
2243
    auto client_reset_config = std::exchange(get_client_reset_config(), std::nullopt);
376✔
2244
    if (!client_reset_config) {
2245
        return false;
376✔
2246
    }
376✔
UNCOV
2247

×
UNCOV
2248
    auto on_flx_version_complete = [this](int64_t version) {
×
2249
        this->on_flx_sync_version_complete(version);
2250
    };
2251
    bool did_reset =
376✔
2252
        client_reset::perform_client_reset(logger, *get_db(), std::move(*client_reset_config), m_client_file_ident,
2253
                                           get_flx_subscription_store(), on_flx_version_complete);
376✔
2254

376✔
2255
    call_debug_hook(SyncClientHookEvent::ClientResetMergeComplete);
376✔
2256
    if (!did_reset) {
376✔
2257
        return false;
376✔
2258
    }
376✔
2259

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

376✔
2263
    SaltedFileIdent client_file_ident;
376✔
2264
    get_history().get_status(m_last_version_available, client_file_ident, m_progress); // Throws
376✔
2265
    REALM_ASSERT_3(m_client_file_ident.ident, ==, client_file_ident.ident);
2266
    REALM_ASSERT_3(m_client_file_ident.salt, ==, client_file_ident.salt);
2267
    REALM_ASSERT_EX(m_progress.download.last_integrated_client_version == 0,
2268
                    m_progress.download.last_integrated_client_version);
376✔
2269
    REALM_ASSERT_EX(m_progress.upload.client_version == 0, m_progress.upload.client_version);
2270
    logger.trace("last_version_available  = %1", m_last_version_available); // Throws
2271

376✔
2272
    m_upload_progress = m_progress.upload;
2273
    m_download_progress = m_progress.download;
2274
    init_progress_handler();
376✔
2275
    // In recovery mode, there may be new changesets to upload and nothing left to download.
268✔
2276
    // In FLX DiscardLocal mode, there may be new commits due to subscription handling.
268✔
2277
    // For both, we want to allow uploads again without needing external changes to download first.
2278
    m_allow_upload = true;
376✔
2279

376✔
2280
    // Checks if there is a pending client reset
2281
    handle_pending_client_reset_acknowledgement();
2282

3,782✔
2283
    update_subscription_version_info();
3,782✔
2284

3,782✔
2285
    // If a migration or rollback is in progress, mark it complete when client reset is completed.
2286
    if (auto migration_store = get_migration_store()) {
2287
        migration_store->complete_migration_or_rollback();
2288
    }
2289

3,782✔
2290
    return true;
48✔
2291
}
2292

3,734✔
2293
Status Session::receive_ident_message(SaltedFileIdent client_file_ident)
3,734✔
2294
{
3,734✔
UNCOV
2295
    logger.debug("Received: IDENT(client_file_ident=%1, client_file_ident_salt=%2)", client_file_ident.ident,
×
UNCOV
2296
                 client_file_ident.salt); // Throws
×
2297

3,734✔
UNCOV
2298
    // Ignore the message if the deactivation process has been initiated,
×
UNCOV
2299
    // because in that case, the associated Realm and SessionWrapper must
×
2300
    // not be accessed any longer.
3,734✔
UNCOV
2301
    if (m_state != Active)
×
UNCOV
2302
        return Status::OK(); // Success
×
2303

2304
    bool legal_at_this_time = (m_bind_message_sent && !have_client_file_ident() && !m_error_message_received &&
3,734✔
2305
                               !m_unbound_message_received);
2306
    if (REALM_UNLIKELY(!legal_at_this_time)) {
3,734✔
2307
        return {ErrorCodes::SyncProtocolInvariantFailed, "Received IDENT message when it was not legal"};
2308
    }
×
UNCOV
2309
    if (REALM_UNLIKELY(client_file_ident.ident < 1)) {
×
2310
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier in IDENT message"};
×
2311
    }
2312
    if (REALM_UNLIKELY(client_file_ident.salt == 0)) {
2313
        return {ErrorCodes::SyncProtocolInvariantFailed, "Bad client file identifier salt in IDENT message"};
2314
    }
3,734✔
2315

2316
    m_client_file_ident = client_file_ident;
2317

3,734✔
2318
    if (REALM_UNLIKELY(get_client().is_dry_run())) {
3,734✔
2319
        // Ready to send the IDENT message
3,734✔
2320
        ensure_enlisted_to_send(); // Throws
376✔
2321
        return Status::OK();       // Success
376✔
2322
    }
376✔
2323

2324
    // if a client reset happens, it will take care of setting the file ident
3,734✔
2325
    // and if not, we do it here
3,734✔
2326
    bool did_client_reset = false;
3,734✔
2327

3,734✔
2328
    // Save some of the client reset info for reporting to the client if an error occurs.
80✔
2329
    Status cr_status(Status::OK()); // Start with no client reset
80✔
2330
    ProtocolErrorInfo::Action cr_action = ProtocolErrorInfo::Action::NoAction;
80✔
2331
    if (auto& cr_config = get_client_reset_config()) {
80✔
2332
        cr_status = cr_config->error;
80✔
2333
        cr_action = cr_config->action;
80✔
2334
    }
80✔
2335

3,654✔
2336
    try {
3,358✔
2337
        did_client_reset = client_reset_if_needed();
3,358✔
2338
    }
3,358✔
2339
    catch (const std::exception& e) {
3,358✔
2340
        auto err_msg = util::format("A fatal error occurred during '%1' client reset for %2: '%3'", cr_action,
3,358✔
2341
                                    cr_status, e.what());
2342
        logger.error(err_msg.c_str());
2343
        SessionErrorInfo err_info(Status{ErrorCodes::AutoClientResetFailed, err_msg}, IsFatal{true});
3,654✔
2344
        suspend(err_info);
3,654✔
2345
        return Status::OK();
3,734✔
2346
    }
2347
    if (!did_client_reset) {
2348
        get_history().set_client_file_ident(client_file_ident,
48,458✔
2349
                                            m_fix_up_object_ids); // Throws
2350
        m_progress.download.last_integrated_client_version = 0;
2351
        m_progress.upload.client_version = 0;
2352
    }
48,458✔
2353

666✔
2354
    // Ready to send the IDENT message
2355
    ensure_enlisted_to_send(); // Throws
47,792✔
2356
    return Status::OK();       // Success
47,792✔
2357
}
2358

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

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

3,604✔
2370
    if (!is_flx || query_version > 0)
3,604✔
2371
        enable_progress_notifications();
3,604✔
2372

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

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

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

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

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

45,516✔
2457
    auto hook_action = call_debug_hook(SyncClientHookEvent::DownloadMessageReceived, progress, query_version,
45,516✔
UNCOV
2458
                                       batch_state, message.changesets.size());
×
UNCOV
2459
    if (hook_action == SyncClientHookAction::EarlyReturn) {
×
2460
        return Status::OK();
45,516✔
2461
    }
2462
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
2463

2464
    if (process_flx_bootstrap_message(progress, batch_state, query_version, message.changesets)) {
45,516✔
2465
        clear_resumption_delay_state();
45,516✔
2466
        return Status::OK();
45,516✔
2467
    }
2468

2469
    initiate_integrate_changesets(message.downloadable.as_bytes(), batch_state, progress,
16,402✔
2470
                                  message.changesets); // Throws
16,402✔
2471

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

16,338✔
2479
    // When we receive a DOWNLOAD message successfully, we can clear the backoff timer value used to reconnect
16,336✔
2480
    // after a retryable session error.
10✔
2481
    clear_resumption_delay_state();
10✔
2482
    return Status::OK();
16,326✔
2483
}
16,328✔
2484

16,326✔
UNCOV
2485
Status Session::receive_mark_message(request_ident_type request_ident)
×
UNCOV
2486
{
×
UNCOV
2487
    logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
×
UNCOV
2488

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

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

×
UNCOV
2509
    m_server_version_at_last_download_mark = m_progress.download.server_version;
×
2510
    m_last_download_mark_received = request_ident;
2511
    check_for_download_completion(); // Throws
2512

2513
    return Status::OK(); // Success
2514
}
2515

4,314!
2516

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

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

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

20✔
2534
    m_unbound_message_received = true;
20✔
2535

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

2544
    return Status::OK(); // Success
740✔
2545
}
740✔
UNCOV
2546

×
UNCOV
2547

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

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

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

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

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

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

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

×
2614
    m_error_message_received = true;
UNCOV
2615
    suspend(SessionErrorInfo{info, std::move(status)});
×
2616
    return Status::OK();
2617
}
2618

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

2625
    m_suspended = true;
700✔
2626

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

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

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

60✔
2648
    if (!info.is_fatal) {
2649
        begin_resumption_delay(info);
60✔
2650
    }
60✔
2651

2652
    // Ready to send the UNBIND message, if it has not been sent already
2653
    if (!m_unbind_message_sent)
88✔
2654
        ensure_enlisted_to_send(); // Throws
88✔
2655
}
2656

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

14✔
2669
    it->promise.emplace_value(std::string{body});
74✔
UNCOV
2670
    m_pending_test_commands.erase(it);
×
2671

2672
    return Status::OK();
74✔
2673
}
74✔
2674

74✔
2675
void Session::begin_resumption_delay(const ProtocolErrorInfo& error_info)
88✔
2676
{
2677
    REALM_ASSERT(!m_try_again_activation_timer);
2678

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

×
2695
        m_try_again_activation_timer.reset();
47,792✔
UNCOV
2696
        cancel_resumption_delay();
×
UNCOV
2697
    });
×
UNCOV
2698
}
×
UNCOV
2699

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

×
UNCOV
2708
Status Session::check_received_sync_progress(const SyncProgress& progress) noexcept
×
UNCOV
2709
{
×
2710
    const SyncProgress& a = m_progress;
47,792✔
UNCOV
2711
    const SyncProgress& b = progress;
×
UNCOV
2712
    std::string message;
×
UNCOV
2713
    if (b.latest_server_version.version < a.latest_server_version.version) {
×
2714
        message = util::format("Latest server version in download messages must be weakly increasing throughout a "
×
2715
                               "session (current: %1, received: %2)",
47,792✔
2716
                               a.latest_server_version.version, b.latest_server_version.version);
×
2717
    }
×
UNCOV
2718
    if (b.upload.client_version < a.upload.client_version) {
×
2719
        message = util::format("Last integrated client version in download messages must be weakly increasing "
×
2720
                               "throughout a session (current: %1, received: %2)",
×
2721
                               a.upload.client_version, b.upload.client_version);
47,792✔
2722
    }
×
UNCOV
2723
    if (b.upload.client_version > m_last_version_available) {
×
2724
        message = util::format("Last integrated client version on server cannot be greater than the latest client "
×
2725
                               "version in existence (current: %1, received: %2)",
×
2726
                               m_last_version_available, b.upload.client_version);
×
2727
    }
47,792✔
UNCOV
2728
    if (b.download.server_version < a.download.server_version) {
×
2729
        message =
×
2730
            util::format("Download cursor must be weakly increasing throughout a session (current: %1, received: %2)",
×
2731
                         a.download.server_version, b.download.server_version);
×
2732
    }
×
2733
    if (b.download.server_version > b.latest_server_version.version) {
2734
        message = util::format(
47,792✔
2735
            "Download cursor cannot be greater than the latest server version in existence (cursor: %1, latest: %2)",
47,792✔
2736
            b.download.server_version, b.latest_server_version.version);
47,792✔
2737
    }
×
2738
    if (b.download.last_integrated_client_version < a.download.last_integrated_client_version) {
47,792✔
2739
        message = util::format(
2740
            "Last integrated client version on the server at the position in the server's history of the download "
2741
            "cursor must be weakly increasing throughout a session (current: %1, received: %2)",
2742
            a.download.last_integrated_client_version, b.download.last_integrated_client_version);
63,814✔
2743
    }
63,814✔
2744
    if (b.download.last_integrated_client_version > b.upload.client_version) {
63,814✔
2745
        message = util::format("Last integrated client version on the server in the position at the server's history "
63,814✔
2746
                               "of the download cursor cannot be greater than the latest client version integrated "
47,272✔
2747
                               "on the server (download: %1, upload: %2)",
16,542✔
2748
                               b.download.last_integrated_client_version, b.upload.client_version);
298✔
2749
    }
16,244✔
UNCOV
2750
    if (b.download.server_version < b.upload.last_integrated_server_version) {
×
2751
        message = util::format(
16,244✔
2752
            "The server version of the download cursor cannot be less than the server version integrated in the "
16,244✔
2753
            "latest client version acknowledged by the server (download: %1, upload: %2)",
2754
            b.download.server_version, b.upload.last_integrated_server_version);
2755
    }
4,548✔
2756

4,548✔
2757
    if (message.empty()) {
4,548✔
2758
        return Status::OK();
16,244✔
2759
    }
16,244✔
2760
    return {ErrorCodes::SyncProtocolInvariantFailed, std::move(message)};
2761
}
2762

2763

2764
void Session::check_for_download_completion()
2765
{
2766
    REALM_ASSERT_3(m_target_download_mark, >=, m_last_download_mark_received);
2767
    REALM_ASSERT_3(m_last_download_mark_received, >=, m_last_triggering_download_mark);
2768
    if (m_last_download_mark_received == m_last_triggering_download_mark)
2769
        return;
2770
    if (m_last_download_mark_received < m_target_download_mark)
2771
        return;
2772
    if (m_download_progress.server_version < m_server_version_at_last_download_mark)
2773
        return;
2774
    m_last_triggering_download_mark = m_target_download_mark;
2775
    if (REALM_UNLIKELY(!m_allow_upload)) {
2776
        // Activate the upload process now, and enable immediate reactivation
2777
        // after a subsequent fast reconnect.
2778
        m_allow_upload = true;
2779
        ensure_enlisted_to_send(); // Throws
2780
    }
2781
    on_download_completion(); // Throws
2782
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc