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

realm / realm-core / michael.wilkersonbarker_1128

31 May 2024 12:31AM UTC coverage: 90.825% (-0.02%) from 90.846%
michael.wilkersonbarker_1128

Pull #7649

Evergreen

michael-wb
Merge branch 'master' of github.com:realm/realm-core into mwb/add-extra-client-reset-fields
Pull Request #7649: RCORE-1386 Track client reset reason in table that detects client reset cycles

101648 of 179968 branches covered (56.48%)

598 of 636 new or added lines in 17 files covered. (94.03%)

120 existing lines in 17 files now uncovered.

214684 of 236371 relevant lines covered (90.83%)

5828091.73 hits per line

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

91.3
/src/realm/sync/client.cpp
1
#include <realm/sync/client.hpp>
2

3
#include <realm/sync/config.hpp>
4
#include <realm/sync/noinst/client_impl_base.hpp>
5
#include <realm/sync/noinst/client_reset.hpp>
6
#include <realm/sync/noinst/pending_bootstrap_store.hpp>
7
#include <realm/sync/noinst/pending_reset_store.hpp>
8
#include <realm/sync/protocol.hpp>
9
#include <realm/sync/subscriptions.hpp>
10
#include <realm/util/bind_ptr.hpp>
11

12
namespace realm::sync {
13
namespace {
14
using namespace realm::util;
15

16

17
// clang-format off
18
using SessionImpl                     = ClientImpl::Session;
19
using SyncTransactCallback            = Session::SyncTransactCallback;
20
using ProgressHandler                 = Session::ProgressHandler;
21
using WaitOperCompletionHandler       = Session::WaitOperCompletionHandler;
22
using ConnectionStateChangeListener   = Session::ConnectionStateChangeListener;
23
using port_type                       = Session::port_type;
24
using connection_ident_type           = std::int_fast64_t;
25
using ProxyConfig                     = SyncConfig::ProxyConfig;
26
// clang-format on
27

28
} // unnamed namespace
29

30

31
// Life cycle states of a session wrapper:
32
//
33
// The session wrapper begins life with an associated Client, but no underlying
34
// SessionImpl. On construction, it begins the actualization process by posting
35
// a job to the client's event loop. That job will set `m_sess` to a session impl
36
// and then set `m_actualized = true`. Once this happens `m_actualized` will
37
// never change again.
38
//
39
// When the external reference to the session (`sync::Session`, which in
40
// non-test code is always owned by a `SyncSession`) is destroyed, the wrapper
41
// begins finalization. If the wrapper has not yet been actualized this takes
42
// place immediately and `m_finalized = true` is set directly on the calling
43
// thread. If it has been actualized, a job is posted to the client's event loop
44
// which will tear down the session and then set `m_finalized = true`. Regardless
45
// of whether or not the session has been actualized, `m_abandoned = true` is
46
// immediately set when the external reference is released.
47
//
48
// When the associated Client is destroyed it calls force_close() on all
49
// actualized wrappers from its event loop. This causes the wrapper to tear down
50
// the session, but not not make it proceed to the finalized state. In normal
51
// usage the client will outlive all sessions, but in tests getting the teardown
52
// correct and race-free can be tricky so we permit either order.
53
//
54
// The wrapper will exist with `m_abandoned = true` and `m_finalized = false`
55
// only while waiting for finalization to happen. It will exist with
56
// `m_finalized = true` only while there are pending post handlers yet to be
57
// executed.
58
class SessionWrapper final : public util::AtomicRefCountBase, DB::CommitListener {
59
public:
60
    SessionWrapper(ClientImpl&, DBRef db, std::shared_ptr<SubscriptionStore>, std::shared_ptr<MigrationStore>,
61
                   Session::Config&&);
62
    ~SessionWrapper() noexcept;
63

64
    ClientReplication& get_replication() noexcept;
65
    ClientImpl& get_client() noexcept;
66

67
    bool has_flx_subscription_store() const;
68
    SubscriptionStore* get_flx_subscription_store();
69
    PendingBootstrapStore* get_flx_pending_bootstrap_store();
70

71
    MigrationStore* get_migration_store();
72

73
    // Immediately initiate deactivation of the wrapped session. Sets m_closed
74
    // but *not* m_finalized.
75
    // Must be called from event loop thread.
76
    void force_close();
77

78
    // Can be called from any thread.
79
    void on_commit(version_type new_version) override;
80
    // Can be called from any thread.
81
    void cancel_reconnect_delay();
82

83
    // Can be called from any thread.
84
    void async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler);
85
    // Can be called from any thread.
86
    bool wait_for_upload_complete_or_client_stopped();
87
    // Can be called from any thread.
88
    bool wait_for_download_complete_or_client_stopped();
89

90
    // Can be called from any thread.
91
    void refresh(std::string_view signed_access_token);
92

93
    // Can be called from any thread.
94
    static void abandon(util::bind_ptr<SessionWrapper>) noexcept;
95

96
    // These are called from ClientImpl
97
    // Must be called from event loop thread.
98
    void actualize();
99
    void finalize();
100
    void finalize_before_actualization() noexcept;
101

102
    // Can be called from any thread.
103
    util::Future<std::string> send_test_command(std::string body);
104

105
    void handle_pending_client_reset_acknowledgement();
106

107
    void update_subscription_version_info();
108

109
    // Can be called from any thread.
110
    std::string get_appservices_connection_id();
111

112
    // Can be called from any thread, but inherently cannot be called
113
    // concurrently with calls to any of the other non-confined functions.
114
    bool mark_abandoned();
115

116
private:
117
    ClientImpl& m_client;
118
    DBRef m_db;
119
    Replication* m_replication;
120

121
    const ProtocolEnvelope m_protocol_envelope;
122
    const std::string m_server_address;
123
    const port_type m_server_port;
124
    const bool m_server_verified;
125
    const std::string m_user_id;
126
    const SyncServerMode m_sync_mode;
127
    const std::string m_authorization_header_name;
128
    const std::map<std::string, std::string> m_custom_http_headers;
129
    const bool m_verify_servers_ssl_certificate;
130
    const bool m_simulate_integration_error;
131
    const std::optional<std::string> m_ssl_trust_certificate_path;
132
    const std::function<SyncConfig::SSLVerifyCallback> m_ssl_verify_callback;
133
    const size_t m_flx_bootstrap_batch_size_bytes;
134
    const std::string m_http_request_path_prefix;
135
    const std::string m_virt_path;
136
    const std::optional<ProxyConfig> m_proxy_config;
137

138
    // This one is different from null when, and only when the session wrapper
139
    // is in ClientImpl::m_abandoned_session_wrappers.
140
    SessionWrapper* m_next = nullptr;
141

142
    // These may only be accessed by the event loop thread.
143
    std::string m_signed_access_token;
144
    std::optional<ClientReset> m_client_reset_config;
145

146
    struct ReportedProgress {
147
        uint64_t snapshot = 0;
148
        uint64_t uploaded = 0;
149
        uint64_t uploadable = 0;
150
        uint64_t downloaded = 0;
151
        uint64_t downloadable = 0;
152
        uint64_t final_uploaded = 0;
153
        uint64_t final_downloaded = 0;
154
    } m_reported_progress;
155

156
    const util::UniqueFunction<ProgressHandler> m_progress_handler;
157
    util::UniqueFunction<ConnectionStateChangeListener> m_connection_state_change_listener;
158

159
    const util::UniqueFunction<SyncClientHookAction(SyncClientHookData const&)> m_debug_hook;
160
    bool m_in_debug_hook = false;
161

162
    const SessionReason m_session_reason;
163

164
    const uint64_t m_schema_version;
165

166
    std::shared_ptr<SubscriptionStore> m_flx_subscription_store;
167
    int64_t m_flx_active_version = 0;
168
    int64_t m_flx_last_seen_version = 0;
169
    int64_t m_flx_pending_mark_version = 0;
170
    std::unique_ptr<PendingBootstrapStore> m_flx_pending_bootstrap_store;
171

172
    std::shared_ptr<MigrationStore> m_migration_store;
173

174
    // Set to true when this session wrapper is actualized (i.e. the wrapped
175
    // session is created), or when the wrapper is finalized before actualization.
176
    // It is then never modified again.
177
    //
178
    // Actualization is scheduled during the construction of SessionWrapper, and
179
    // so a session specific post handler will always find that `m_actualized`
180
    // is true as the handler will always be run after the actualization job.
181
    // This holds even if the wrapper is finalized or closed before actualization.
182
    bool m_actualized = false;
183

184
    // Set to true when session deactivation is begun, either via force_close()
185
    // or finalize().
186
    bool m_closed = false;
187

188
    // Set to true in on_suspended() and then false in on_resumed(). Used to
189
    // suppress spurious connection state and error reporting while the session
190
    // is already in an error state.
191
    bool m_suspended = false;
192

193
    // Set when the session has been abandoned. After this point none of the
194
    // public API functions should be called again.
195
    bool m_abandoned = false;
196
    // Has the SessionWrapper been finalized?
197
    bool m_finalized = false;
198

199
    // Set to true when the first DOWNLOAD message is received to indicate that
200
    // the byte-level download progress parameters can be considered reasonable
201
    // reliable. Before that, a lot of time may have passed, so our record of
202
    // the download progress is likely completely out of date.
203
    bool m_reliable_download_progress = false;
204

205
    std::optional<double> m_download_estimate;
206
    std::optional<uint64_t> m_bootstrap_store_bytes;
207

208
    // Set to point to an activated session object during actualization of the
209
    // session wrapper. Set to null during finalization of the session
210
    // wrapper. Both modifications are guaranteed to be performed by the event
211
    // loop thread.
212
    //
213
    // If a session specific post handler, that is submitted after the
214
    // initiation of the session wrapper, sees that `m_sess` is null, it can
215
    // conclude that the session wrapper has either been force closed or has
216
    // been both abandoned and finalized.
217
    //
218
    // Must only be accessed from the event loop thread.
219
    SessionImpl* m_sess = nullptr;
220

221
    // These must only be accessed from the event loop thread.
222
    std::vector<WaitOperCompletionHandler> m_upload_completion_handlers;
223
    std::vector<WaitOperCompletionHandler> m_download_completion_handlers;
224
    std::vector<WaitOperCompletionHandler> m_sync_completion_handlers;
225

226
    // `m_target_*load_mark` and `m_reached_*load_mark` are protected by
227
    // `m_client.m_mutex`. `m_staged_*load_mark` must only be accessed by the
228
    // event loop thread.
229
    std::int_fast64_t m_target_upload_mark = 0, m_target_download_mark = 0;
230
    std::int_fast64_t m_staged_upload_mark = 0, m_staged_download_mark = 0;
231
    std::int_fast64_t m_reached_upload_mark = 0, m_reached_download_mark = 0;
232

233
    void on_upload_progress(bool only_if_new_uploadable_data = false);
234
    void on_download_progress(const std::optional<uint64_t>& bootstrap_store_bytes = {});
235
    void on_upload_completion();
236
    void on_download_completion();
237
    void on_suspended(const SessionErrorInfo& error_info);
238
    void on_resumed();
239
    void on_connection_state_changed(ConnectionState, const std::optional<SessionErrorInfo>&);
240
    void on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state);
241
    void on_flx_sync_error(int64_t version, std::string_view err_msg);
242
    void on_flx_sync_version_complete(int64_t version);
243

244
    void init_progress_handler();
245
    // only_if_new_uploadable_data can be true only if is_download is false
246
    void report_progress(bool is_download, bool only_if_new_uploadable_data = false);
247

248
    friend class SessionWrapperStack;
249
    friend class ClientImpl::Session;
250
};
251

252

253
// ################ SessionWrapperStack ################
254

255
inline bool SessionWrapperStack::empty() const noexcept
256
{
19,812✔
257
    return !m_back;
19,812✔
258
}
19,812✔
259

260

261
inline void SessionWrapperStack::push(util::bind_ptr<SessionWrapper> w) noexcept
262
{
20,136✔
263
    REALM_ASSERT(!w->m_next);
20,136✔
264
    w->m_next = m_back;
20,136✔
265
    m_back = w.release();
20,136✔
266
}
20,136✔
267

268

269
inline util::bind_ptr<SessionWrapper> SessionWrapperStack::pop() noexcept
270
{
58,398✔
271
    util::bind_ptr<SessionWrapper> w{m_back, util::bind_ptr_base::adopt_tag{}};
58,398✔
272
    if (m_back) {
58,398✔
273
        m_back = m_back->m_next;
20,054✔
274
        w->m_next = nullptr;
20,054✔
275
    }
20,054✔
276
    return w;
58,398✔
277
}
58,398✔
278

279

280
inline void SessionWrapperStack::clear() noexcept
281
{
19,812✔
282
    while (m_back) {
19,812✔
283
        util::bind_ptr<SessionWrapper> w{m_back, util::bind_ptr_base::adopt_tag{}};
×
284
        m_back = w->m_next;
×
285
    }
×
286
}
19,812✔
287

288

289
inline bool SessionWrapperStack::erase(SessionWrapper* w) noexcept
290
{
10,100✔
291
    SessionWrapper** p = &m_back;
10,100✔
292
    while (*p && *p != w) {
10,268✔
293
        p = &(*p)->m_next;
168✔
294
    }
168✔
295
    if (!*p) {
10,100✔
296
        return false;
10,032✔
297
    }
10,032✔
298
    *p = w->m_next;
68✔
299
    util::bind_ptr<SessionWrapper>{w, util::bind_ptr_base::adopt_tag{}};
68✔
300
    return true;
68✔
301
}
10,100✔
302

303

304
SessionWrapperStack::~SessionWrapperStack()
305
{
19,812✔
306
    clear();
19,812✔
307
}
19,812✔
308

309

310
// ################ ClientImpl ################
311

312
ClientImpl::~ClientImpl()
313
{
9,918✔
314
    // Since no other thread is allowed to be accessing this client or any of
315
    // its subobjects at this time, no mutex locking is necessary.
316

317
    shutdown_and_wait();
9,918✔
318
    // Session wrappers are removed from m_unactualized_session_wrappers as they
319
    // are abandoned.
320
    REALM_ASSERT(m_stopped);
9,918✔
321
    REALM_ASSERT(m_unactualized_session_wrappers.empty());
9,918✔
322
    REALM_ASSERT(m_abandoned_session_wrappers.empty());
9,918✔
323
}
9,918✔
324

325

326
void ClientImpl::cancel_reconnect_delay()
327
{
1,968✔
328
    // Thread safety required
329
    post([this] {
1,968✔
330
        for (auto& p : m_server_slots) {
1,968✔
331
            ServerSlot& slot = p.second;
1,968✔
332
            if (m_one_connection_per_session) {
1,968✔
333
                REALM_ASSERT(!slot.connection);
×
334
                for (const auto& p : slot.alt_connections) {
×
335
                    ClientImpl::Connection& conn = *p.second;
×
336
                    conn.resume_active_sessions(); // Throws
×
337
                    conn.cancel_reconnect_delay(); // Throws
×
338
                }
×
339
            }
×
340
            else {
1,968✔
341
                REALM_ASSERT(slot.alt_connections.empty());
1,968✔
342
                if (slot.connection) {
1,968✔
343
                    ClientImpl::Connection& conn = *slot.connection;
1,964✔
344
                    conn.resume_active_sessions(); // Throws
1,964✔
345
                    conn.cancel_reconnect_delay(); // Throws
1,964✔
346
                }
1,964✔
347
                else {
4✔
348
                    slot.reconnect_info.reset();
4✔
349
                }
4✔
350
            }
1,968✔
351
        }
1,968✔
352
    }); // Throws
1,968✔
353
}
1,968✔
354

355

356
void ClientImpl::voluntary_disconnect_all_connections()
357
{
12✔
358
    auto done_pf = util::make_promise_future<void>();
12✔
359
    post([this, promise = std::move(done_pf.promise)]() mutable {
12✔
360
        try {
12✔
361
            for (auto& p : m_server_slots) {
12✔
362
                ServerSlot& slot = p.second;
12✔
363
                if (m_one_connection_per_session) {
12✔
364
                    REALM_ASSERT(!slot.connection);
×
365
                    for (const auto& [_, conn] : slot.alt_connections) {
×
366
                        conn->voluntary_disconnect();
×
367
                    }
×
368
                }
×
369
                else {
12✔
370
                    REALM_ASSERT(slot.alt_connections.empty());
12✔
371
                    if (slot.connection) {
12✔
372
                        slot.connection->voluntary_disconnect();
12✔
373
                    }
12✔
374
                }
12✔
375
            }
12✔
376
        }
12✔
377
        catch (...) {
12✔
378
            promise.set_error(exception_to_status());
×
379
            return;
×
380
        }
×
381
        promise.emplace_value();
12✔
382
    });
12✔
383
    done_pf.future.get();
12✔
384
}
12✔
385

386

387
bool ClientImpl::wait_for_session_terminations_or_client_stopped()
388
{
9,488✔
389
    // Thread safety required
390

391
    {
9,488✔
392
        util::CheckedLockGuard lock{m_mutex};
9,488✔
393
        m_sessions_terminated = false;
9,488✔
394
    }
9,488✔
395

396
    // The technique employed here relies on the fact that
397
    // actualize_and_finalize_session_wrappers() must get to execute at least
398
    // once before the post handler submitted below gets to execute, but still
399
    // at a time where all session wrappers, that are abandoned prior to the
400
    // execution of wait_for_session_terminations_or_client_stopped(), have been
401
    // added to `m_abandoned_session_wrappers`.
402
    //
403
    // To see that this is the case, consider a session wrapper that was
404
    // abandoned before wait_for_session_terminations_or_client_stopped() was
405
    // invoked. Then the session wrapper will have been added to
406
    // `m_abandoned_session_wrappers`, and an invocation of
407
    // actualize_and_finalize_session_wrappers() will have been scheduled. The
408
    // guarantees mentioned in the documentation of Trigger then ensure
409
    // that at least one execution of actualize_and_finalize_session_wrappers()
410
    // will happen after the session wrapper has been added to
411
    // `m_abandoned_session_wrappers`, but before the post handler submitted
412
    // below gets to execute.
413
    post([this] {
9,488✔
414
        {
9,488✔
415
            util::CheckedLockGuard lock{m_mutex};
9,488✔
416
            m_sessions_terminated = true;
9,488✔
417
        }
9,488✔
418
        m_wait_or_client_stopped_cond.notify_all();
9,488✔
419
    }); // Throws
9,488✔
420

421
    bool completion_condition_was_satisfied;
9,488✔
422
    {
9,488✔
423
        util::CheckedUniqueLock lock{m_mutex};
9,488✔
424
        m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_mutex) {
18,954✔
425
            return m_sessions_terminated || m_stopped;
18,954✔
426
        });
18,954✔
427
        completion_condition_was_satisfied = !m_stopped;
9,488✔
428
    }
9,488✔
429
    return completion_condition_was_satisfied;
9,488✔
430
}
9,488✔
431

432

433
// This relies on the same assumptions and guarantees as wait_for_session_terminations_or_client_stopped().
434
util::Future<void> ClientImpl::notify_session_terminated()
435
{
56✔
436
    auto pf = util::make_promise_future<void>();
56✔
437
    post([promise = std::move(pf.promise)](Status status) mutable {
56✔
438
        // Includes operation_aborted
439
        if (!status.is_ok()) {
56✔
440
            promise.set_error(status);
×
441
            return;
×
442
        }
×
443

444
        promise.emplace_value();
56✔
445
    });
56✔
446

447
    return std::move(pf.future);
56✔
448
}
56✔
449

450
void ClientImpl::drain_connections_on_loop()
451
{
9,918✔
452
    post([this](Status status) {
9,918✔
453
        REALM_ASSERT(status.is_ok());
9,904✔
454
        drain_connections();
9,904✔
455
    });
9,904✔
456
}
9,918✔
457

458
void ClientImpl::shutdown_and_wait()
459
{
10,686✔
460
    shutdown();
10,686✔
461
    util::CheckedUniqueLock lock{m_drain_mutex};
10,686✔
462
    if (m_drained) {
10,686✔
463
        return;
768✔
464
    }
768✔
465

466
    logger.debug("Waiting for %1 connections to drain", m_num_connections);
9,918✔
467
    m_drain_cv.wait(lock.native_handle(), [&]() REQUIRES(m_drain_mutex) {
15,832✔
468
        return m_num_connections == 0 && m_outstanding_posts == 0;
15,832✔
469
    });
15,832✔
470

471
    m_drained = true;
9,918✔
472
}
9,918✔
473

474
void ClientImpl::shutdown() noexcept
475
{
20,686✔
476
    {
20,686✔
477
        util::CheckedLockGuard lock{m_mutex};
20,686✔
478
        if (m_stopped)
20,686✔
479
            return;
10,768✔
480
        m_stopped = true;
9,918✔
481
    }
9,918✔
482
    m_wait_or_client_stopped_cond.notify_all();
×
483

484
    drain_connections_on_loop();
9,918✔
485
}
9,918✔
486

487

488
void ClientImpl::register_unactualized_session_wrapper(SessionWrapper* wrapper)
489
{
10,104✔
490
    // Thread safety required.
491
    {
10,104✔
492
        util::CheckedLockGuard lock{m_mutex};
10,104✔
493
        // We can't actualize the session if we've already been stopped, so
494
        // just finalize it immediately.
495
        if (m_stopped) {
10,104✔
496
            wrapper->finalize_before_actualization();
×
497
            return;
×
498
        }
×
499

500
        REALM_ASSERT(m_actualize_and_finalize);
10,104✔
501
        m_unactualized_session_wrappers.push(util::bind_ptr(wrapper));
10,104✔
502
    }
10,104✔
503
    m_actualize_and_finalize->trigger();
×
504
}
10,104✔
505

506

507
void ClientImpl::register_abandoned_session_wrapper(util::bind_ptr<SessionWrapper> wrapper) noexcept
508
{
10,104✔
509
    // Thread safety required.
510
    {
10,104✔
511
        util::CheckedLockGuard lock{m_mutex};
10,104✔
512
        REALM_ASSERT(m_actualize_and_finalize);
10,104✔
513
        // The wrapper may have already been finalized before being abandoned
514
        // if we were stopped when it was created.
515
        if (wrapper->mark_abandoned())
10,104✔
516
            return;
4✔
517

518
        // If the session wrapper has not yet been actualized (on the event loop
519
        // thread), it can be immediately finalized. This ensures that we will
520
        // generally not actualize a session wrapper that has already been
521
        // abandoned.
522
        if (m_unactualized_session_wrappers.erase(wrapper.get())) {
10,100✔
523
            wrapper->finalize_before_actualization();
68✔
524
            return;
68✔
525
        }
68✔
526
        m_abandoned_session_wrappers.push(std::move(wrapper));
10,032✔
527
    }
10,032✔
528
    m_actualize_and_finalize->trigger();
×
529
}
10,032✔
530

531

532
// Must be called from the event loop thread.
533
void ClientImpl::actualize_and_finalize_session_wrappers()
534
{
14,166✔
535
    // We need to pop from the wrapper stacks while holding the lock to ensure
536
    // that all updates to `SessionWrapper:m_next` are thread-safe, but then
537
    // release the lock before finalizing or actualizing because those functions
538
    // invoke user callbacks which may try to access the client and reacquire
539
    // the lock.
540
    //
541
    // Finalization must always happen before actualization because we may be
542
    // finalizing and actualizing sessions for the same Realm file, and
543
    // actualizing first would result in overlapping sessions. Because we're
544
    // releasing the lock new sessions may come in as we're looping, so we need
545
    // a single loop that checks both fields.
546
    while (true) {
34,228✔
547
        bool finalize = true;
34,216✔
548
        bool stopped;
34,216✔
549
        util::bind_ptr<SessionWrapper> wrapper;
34,216✔
550
        {
34,216✔
551
            util::CheckedLockGuard lock{m_mutex};
34,216✔
552
            wrapper = m_abandoned_session_wrappers.pop();
34,216✔
553
            if (!wrapper) {
34,216✔
554
                wrapper = m_unactualized_session_wrappers.pop();
24,192✔
555
                finalize = false;
24,192✔
556
            }
24,192✔
557
            stopped = m_stopped;
34,216✔
558
        }
34,216✔
559
        if (!wrapper)
34,216✔
560
            break;
14,154✔
561
        if (finalize)
20,062✔
562
            wrapper->finalize(); // Throws
10,020✔
563
        else if (stopped)
10,042✔
564
            wrapper->finalize_before_actualization();
4✔
565
        else
10,038✔
566
            wrapper->actualize(); // Throws
10,038✔
567
    }
20,062✔
568
}
14,166✔
569

570

571
ClientImpl::Connection& ClientImpl::get_connection(ServerEndpoint endpoint,
572
                                                   const std::string& authorization_header_name,
573
                                                   const std::map<std::string, std::string>& custom_http_headers,
574
                                                   bool verify_servers_ssl_certificate,
575
                                                   Optional<std::string> ssl_trust_certificate_path,
576
                                                   std::function<SyncConfig::SSLVerifyCallback> ssl_verify_callback,
577
                                                   Optional<ProxyConfig> proxy_config, bool& was_created)
578
{
10,026✔
579
    auto&& [server_slot_it, inserted] =
10,026✔
580
        m_server_slots.try_emplace(endpoint, ReconnectInfo(m_reconnect_mode, m_reconnect_backoff_info, get_random()));
10,026✔
581
    ServerSlot& server_slot = server_slot_it->second; // Throws
10,026✔
582

583
    // TODO: enable multiplexing with proxies
584
    if (server_slot.connection && !m_one_connection_per_session && !proxy_config) {
10,026✔
585
        // Use preexisting connection
586
        REALM_ASSERT(server_slot.alt_connections.empty());
7,250✔
587
        return *server_slot.connection;
7,250✔
588
    }
7,250✔
589

590
    // Create a new connection
591
    REALM_ASSERT(!server_slot.connection);
2,776✔
592
    connection_ident_type ident = m_prev_connection_ident + 1;
2,776✔
593
    std::unique_ptr<ClientImpl::Connection> conn_2 = std::make_unique<ClientImpl::Connection>(
2,776✔
594
        *this, ident, std::move(endpoint), authorization_header_name, custom_http_headers,
2,776✔
595
        verify_servers_ssl_certificate, std::move(ssl_trust_certificate_path), std::move(ssl_verify_callback),
2,776✔
596
        std::move(proxy_config), server_slot.reconnect_info); // Throws
2,776✔
597
    ClientImpl::Connection& conn = *conn_2;
2,776✔
598
    if (!m_one_connection_per_session) {
2,776✔
599
        server_slot.connection = std::move(conn_2);
2,766✔
600
    }
2,766✔
601
    else {
10✔
602
        server_slot.alt_connections[ident] = std::move(conn_2); // Throws
10✔
603
    }
10✔
604
    m_prev_connection_ident = ident;
2,776✔
605
    was_created = true;
2,776✔
606
    {
2,776✔
607
        util::CheckedLockGuard lk(m_drain_mutex);
2,776✔
608
        ++m_num_connections;
2,776✔
609
    }
2,776✔
610
    return conn;
2,776✔
611
}
10,026✔
612

613

614
void ClientImpl::remove_connection(ClientImpl::Connection& conn) noexcept
615
{
2,764✔
616
    const ServerEndpoint& endpoint = conn.get_server_endpoint();
2,764✔
617
    auto i = m_server_slots.find(endpoint);
2,764✔
618
    REALM_ASSERT(i != m_server_slots.end()); // Must be found
2,764✔
619
    ServerSlot& server_slot = i->second;
2,764✔
620
    if (!m_one_connection_per_session) {
2,764✔
621
        REALM_ASSERT(server_slot.alt_connections.empty());
2,750✔
622
        REALM_ASSERT(&*server_slot.connection == &conn);
2,750✔
623
        server_slot.reconnect_info = conn.get_reconnect_info();
2,750✔
624
        server_slot.connection.reset();
2,750✔
625
    }
2,750✔
626
    else {
14✔
627
        REALM_ASSERT(!server_slot.connection);
14✔
628
        connection_ident_type ident = conn.get_ident();
14✔
629
        auto j = server_slot.alt_connections.find(ident);
14✔
630
        REALM_ASSERT(j != server_slot.alt_connections.end()); // Must be found
14✔
631
        REALM_ASSERT(&*j->second == &conn);
14✔
632
        server_slot.alt_connections.erase(j);
14✔
633
    }
14✔
634

635
    bool notify;
2,764✔
636
    {
2,764✔
637
        util::CheckedLockGuard lk(m_drain_mutex);
2,764✔
638
        REALM_ASSERT(m_num_connections);
2,764✔
639
        notify = --m_num_connections <= 0;
2,764✔
640
    }
2,764✔
641
    if (notify) {
2,764✔
642
        m_drain_cv.notify_all();
2,156✔
643
    }
2,156✔
644
}
2,764✔
645

646

647
// ################ SessionImpl ################
648

649
void SessionImpl::force_close()
650
{
102✔
651
    // Allow force_close() if session is active or hasn't been activated yet.
652
    if (m_state == SessionImpl::Active || m_state == SessionImpl::Unactivated) {
102!
653
        m_wrapper.force_close();
102✔
654
    }
102✔
655
}
102✔
656

657
void SessionImpl::on_connection_state_changed(ConnectionState state,
658
                                              const std::optional<SessionErrorInfo>& error_info)
659
{
12,040✔
660
    // Only used to report errors back to the SyncSession while the Session is active
661
    if (m_state == SessionImpl::Active) {
12,040✔
662
        m_wrapper.on_connection_state_changed(state, error_info); // Throws
12,040✔
663
    }
12,040✔
664
}
12,040✔
665

666

667
const std::string& SessionImpl::get_virt_path() const noexcept
668
{
7,206✔
669
    // Can only be called if the session is active or being activated
670
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
7,206!
671
    return m_wrapper.m_virt_path;
7,206✔
672
}
7,206✔
673

674
const std::string& SessionImpl::get_realm_path() const noexcept
675
{
10,324✔
676
    // Can only be called if the session is active or being activated
677
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
10,324✔
678
    return m_wrapper.m_db->get_path();
10,324✔
679
}
10,324✔
680

681
DBRef SessionImpl::get_db() const noexcept
682
{
26,060✔
683
    // Can only be called if the session is active or being activated
684
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
26,060✔
685
    return m_wrapper.m_db;
26,060✔
686
}
26,060✔
687

688
ClientReplication& SessionImpl::get_repl() const noexcept
689
{
119,456✔
690
    // Can only be called if the session is active or being activated
691
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
119,456✔
692
    return m_wrapper.get_replication();
119,456✔
693
}
119,456✔
694

695
ClientHistory& SessionImpl::get_history() const noexcept
696
{
117,508✔
697
    return get_repl().get_history();
117,508✔
698
}
117,508✔
699

700
std::optional<ClientReset>& SessionImpl::get_client_reset_config() noexcept
701
{
13,686✔
702
    // Can only be called if the session is active or being activated
703
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
13,686✔
704
    return m_wrapper.m_client_reset_config;
13,686✔
705
}
13,686✔
706

707
SessionReason SessionImpl::get_session_reason() noexcept
708
{
1,468✔
709
    // Can only be called if the session is active or being activated
710
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
1,468!
711
    return m_wrapper.m_session_reason;
1,468✔
712
}
1,468✔
713

714
uint64_t SessionImpl::get_schema_version() noexcept
715
{
1,468✔
716
    // Can only be called if the session is active or being activated
717
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
1,468!
718
    return m_wrapper.m_schema_version;
1,468✔
719
}
1,468✔
720

721
void SessionImpl::initiate_integrate_changesets(std::uint_fast64_t downloadable_bytes, DownloadBatchState batch_state,
722
                                                const SyncProgress& progress, const ReceivedChangesets& changesets)
723
{
45,314✔
724
    // Ignore the call if the session is not active
725
    if (m_state != State::Active) {
45,314✔
726
        return;
×
727
    }
×
728

729
    try {
45,314✔
730
        bool simulate_integration_error = (m_wrapper.m_simulate_integration_error && !changesets.empty());
45,314!
731
        if (simulate_integration_error) {
45,314✔
732
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
×
733
        }
×
734
        version_type client_version;
45,314✔
735
        if (REALM_LIKELY(!get_client().is_dry_run())) {
45,314✔
736
            VersionInfo version_info;
45,314✔
737
            integrate_changesets(progress, downloadable_bytes, changesets, version_info, batch_state); // Throws
45,314✔
738
            client_version = version_info.realm_version;
45,314✔
739
        }
45,314✔
UNCOV
740
        else {
×
741
            // Fake it for "dry run" mode
UNCOV
742
            client_version = m_last_version_available + 1;
×
UNCOV
743
        }
×
744
        on_changesets_integrated(client_version, progress, !changesets.empty()); // Throws
45,314✔
745
    }
45,314✔
746
    catch (const IntegrationException& e) {
45,314✔
747
        on_integration_failure(e);
24✔
748
    }
24✔
749
}
45,314✔
750

751

752
void SessionImpl::on_upload_completion()
753
{
14,794✔
754
    // Ignore the call if the session is not active
755
    if (m_state == State::Active) {
14,794✔
756
        m_wrapper.on_upload_completion(); // Throws
14,794✔
757
    }
14,794✔
758
}
14,794✔
759

760

761
void SessionImpl::on_download_completion()
762
{
16,112✔
763
    // Ignore the call if the session is not active
764
    if (m_state == State::Active) {
16,112✔
765
        m_wrapper.on_download_completion(); // Throws
16,112✔
766
    }
16,112✔
767
}
16,112✔
768

769

770
void SessionImpl::on_suspended(const SessionErrorInfo& error_info)
771
{
670✔
772
    // Ignore the call if the session is not active
773
    if (m_state == State::Active) {
670✔
774
        m_wrapper.on_suspended(error_info); // Throws
670✔
775
    }
670✔
776
}
670✔
777

778

779
void SessionImpl::on_resumed()
780
{
62✔
781
    // Ignore the call if the session is not active
782
    if (m_state == State::Active) {
62✔
783
        m_wrapper.on_resumed(); // Throws
62✔
784
    }
62✔
785
}
62✔
786

787
void SessionImpl::handle_pending_client_reset_acknowledgement()
788
{
10,324✔
789
    // Ignore the call if the session is not active
790
    if (m_state == State::Active) {
10,324✔
791
        m_wrapper.handle_pending_client_reset_acknowledgement();
10,324✔
792
    }
10,324✔
793
}
10,324✔
794

795
void SessionImpl::update_subscription_version_info()
796
{
296✔
797
    // Ignore the call if the session is not active
798
    if (m_state == State::Active) {
296✔
799
        m_wrapper.update_subscription_version_info();
296✔
800
    }
296✔
801
}
296✔
802

803
bool SessionImpl::process_flx_bootstrap_message(const SyncProgress& progress, DownloadBatchState batch_state,
804
                                                int64_t query_version, const ReceivedChangesets& received_changesets)
805
{
47,450✔
806
    // Ignore the call if the session is not active
807
    if (m_state != State::Active) {
47,450✔
808
        return false;
×
809
    }
×
810

811
    if (is_steady_state_download_message(batch_state, query_version)) {
47,450✔
812
        return false;
45,314✔
813
    }
45,314✔
814

815
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
2,136✔
816
    std::optional<SyncProgress> maybe_progress;
2,136✔
817
    if (batch_state == DownloadBatchState::LastInBatch) {
2,136✔
818
        maybe_progress = progress;
1,936✔
819
    }
1,936✔
820

821
    bool new_batch = false;
2,136✔
822
    try {
2,136✔
823
        bootstrap_store->add_batch(query_version, std::move(maybe_progress), received_changesets, &new_batch);
2,136✔
824
    }
2,136✔
825
    catch (const LogicError& ex) {
2,136✔
826
        if (ex.code() == ErrorCodes::LimitExceeded) {
×
827
            IntegrationException ex(ErrorCodes::LimitExceeded,
×
828
                                    "bootstrap changeset too large to store in pending bootstrap store",
×
829
                                    ProtocolError::bad_changeset_size);
×
830
            on_integration_failure(ex);
×
831
            return true;
×
832
        }
×
833
        throw;
×
834
    }
×
835

836
    // If we've started a new batch and there is more to come, call on_flx_sync_progress to mark the subscription as
837
    // bootstrapping.
838
    if (new_batch && batch_state == DownloadBatchState::MoreToCome) {
2,136✔
839
        on_flx_sync_progress(query_version, DownloadBatchState::MoreToCome);
48✔
840
    }
48✔
841

842
    auto hook_action = call_debug_hook(SyncClientHookEvent::BootstrapMessageProcessed, progress, query_version,
2,136✔
843
                                       batch_state, received_changesets.size());
2,136✔
844
    if (hook_action == SyncClientHookAction::EarlyReturn) {
2,136✔
845
        return true;
12✔
846
    }
12✔
847
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
2,124✔
848

849
    if (batch_state == DownloadBatchState::MoreToCome) {
2,124✔
850
        notify_download_progress(bootstrap_store->pending_stats().pending_changeset_bytes);
196✔
851
        return true;
196✔
852
    }
196✔
853
    else {
1,928✔
854
        // FIXME (#7451) this variable is not needed in principle, and bootstrap store bytes could be passed just
855
        // through notify_download_progress, but since it is needed in report_progress, and it is also called on
856
        // upload progress for now until progress is reported separately. As soon as we understand here that there
857
        // are no more changesets for bootstrap store, and we want to process bootstrap, we don't need to notify
858
        // intermediate progress - so reset these bytes to not accidentally double report them.
859
        m_wrapper.m_bootstrap_store_bytes.reset();
1,928✔
860
    }
1,928✔
861

862
    try {
1,928✔
863
        process_pending_flx_bootstrap();
1,928✔
864
    }
1,928✔
865
    catch (const IntegrationException& e) {
1,928✔
866
        on_integration_failure(e);
12✔
867
    }
12✔
868
    catch (...) {
1,928✔
869
        on_integration_failure(IntegrationException(exception_to_status()));
×
870
    }
×
871

872
    return true;
1,928✔
873
}
1,928✔
874

875

876
void SessionImpl::process_pending_flx_bootstrap()
877
{
11,956✔
878
    // Ignore the call if not a flx session or session is not active
879
    if (!m_is_flx_sync_session || m_state != State::Active) {
11,956✔
880
        return;
8,534✔
881
    }
8,534✔
882
    // Should never be called if session is not active
883
    REALM_ASSERT_EX(m_state == SessionImpl::Active, m_state);
3,422✔
884
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
3,422✔
885
    if (!bootstrap_store->has_pending()) {
3,422✔
886
        return;
1,474✔
887
    }
1,474✔
888

889
    auto pending_batch_stats = bootstrap_store->pending_stats();
1,948✔
890
    logger.info("Begin processing pending FLX bootstrap for query version %1. (changesets: %2, original total "
1,948✔
891
                "changeset size: %3)",
1,948✔
892
                pending_batch_stats.query_version, pending_batch_stats.pending_changesets,
1,948✔
893
                pending_batch_stats.pending_changeset_bytes);
1,948✔
894
    auto& history = get_repl().get_history();
1,948✔
895
    VersionInfo new_version;
1,948✔
896
    SyncProgress progress;
1,948✔
897
    int64_t query_version = -1;
1,948✔
898
    size_t changesets_processed = 0;
1,948✔
899

900
    // Used to commit each batch after it was transformed.
901
    TransactionRef transact = get_db()->start_write();
1,948✔
902
    while (bootstrap_store->has_pending()) {
4,056✔
903
        auto start_time = std::chrono::steady_clock::now();
2,120✔
904
        auto pending_batch = bootstrap_store->peek_pending(m_wrapper.m_flx_bootstrap_batch_size_bytes);
2,120✔
905
        if (!pending_batch.progress) {
2,120✔
906
            logger.info("Incomplete pending bootstrap found for query version %1", pending_batch.query_version);
8✔
907
            // Close the write transation before clearing the bootstrap store to avoid a deadlock because the
908
            // bootstrap store requires a write transaction itself.
909
            transact->close();
8✔
910
            bootstrap_store->clear();
8✔
911
            return;
8✔
912
        }
8✔
913

914
        auto batch_state =
2,112✔
915
            pending_batch.remaining_changesets > 0 ? DownloadBatchState::MoreToCome : DownloadBatchState::LastInBatch;
2,112✔
916
        uint64_t downloadable_bytes = 0;
2,112✔
917
        query_version = pending_batch.query_version;
2,112✔
918
        bool simulate_integration_error =
2,112✔
919
            (m_wrapper.m_simulate_integration_error && !pending_batch.changesets.empty());
2,112✔
920
        if (simulate_integration_error) {
2,112✔
921
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
4✔
922
        }
4✔
923

924
        call_debug_hook(SyncClientHookEvent::BootstrapBatchAboutToProcess, *pending_batch.progress, query_version,
2,108✔
925
                        batch_state, pending_batch.changesets.size());
2,108✔
926

927
        history.integrate_server_changesets(
2,108✔
928
            *pending_batch.progress, &downloadable_bytes, pending_batch.changesets, new_version, batch_state, logger,
2,108✔
929
            transact, [&](const TransactionRef& tr, util::Span<Changeset> changesets_applied) {
2,108✔
930
                REALM_ASSERT_3(changesets_applied.size(), <=, pending_batch.changesets.size());
2,096✔
931
                bootstrap_store->pop_front_pending(tr, changesets_applied.size());
2,096✔
932
            });
2,096✔
933
        progress = *pending_batch.progress;
2,108✔
934
        changesets_processed += pending_batch.changesets.size();
2,108✔
935
        auto duration = std::chrono::steady_clock::now() - start_time;
2,108✔
936

937
        auto action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
2,108✔
938
                                      batch_state, pending_batch.changesets.size());
2,108✔
939
        REALM_ASSERT_EX(action == SyncClientHookAction::NoAction, action);
2,108✔
940

941
        logger.info("Integrated %1 changesets from pending bootstrap for query version %2, producing client version "
2,108✔
942
                    "%3 in %4 ms. %5 changesets remaining in bootstrap",
2,108✔
943
                    pending_batch.changesets.size(), pending_batch.query_version, new_version.realm_version,
2,108✔
944
                    std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(),
2,108✔
945
                    pending_batch.remaining_changesets);
2,108✔
946
    }
2,108✔
947

948
    REALM_ASSERT_3(query_version, !=, -1);
1,936✔
949
    on_flx_sync_progress(query_version, DownloadBatchState::LastInBatch);
1,936✔
950

951
    on_changesets_integrated(new_version.realm_version, progress, changesets_processed > 0);
1,936✔
952
    auto action = call_debug_hook(SyncClientHookEvent::BootstrapProcessed, progress, query_version,
1,936✔
953
                                  DownloadBatchState::LastInBatch, changesets_processed);
1,936✔
954
    // NoAction/EarlyReturn are both valid no-op actions to take here.
955
    REALM_ASSERT_EX(action == SyncClientHookAction::NoAction || action == SyncClientHookAction::EarlyReturn, action);
1,936✔
956
}
1,936✔
957

958
void SessionImpl::on_flx_sync_error(int64_t version, std::string_view err_msg)
959
{
20✔
960
    // Ignore the call if the session is not active
961
    if (m_state == State::Active) {
20✔
962
        m_wrapper.on_flx_sync_error(version, err_msg);
20✔
963
    }
20✔
964
}
20✔
965

966
void SessionImpl::on_flx_sync_progress(int64_t version, DownloadBatchState batch_state)
967
{
1,972✔
968
    // Ignore the call if the session is not active
969
    if (m_state == State::Active) {
1,972✔
970
        m_wrapper.on_flx_sync_progress(version, batch_state);
1,972✔
971
    }
1,972✔
972
}
1,972✔
973

974
SubscriptionStore* SessionImpl::get_flx_subscription_store()
975
{
18,226✔
976
    // Should never be called if session is not active
977
    REALM_ASSERT_EX(m_state == State::Active, m_state);
18,226✔
978
    return m_wrapper.get_flx_subscription_store();
18,226✔
979
}
18,226✔
980

981
MigrationStore* SessionImpl::get_migration_store()
982
{
67,400✔
983
    // Should never be called if session is not active
984
    REALM_ASSERT_EX(m_state == State::Active, m_state);
67,400✔
985
    return m_wrapper.get_migration_store();
67,400✔
986
}
67,400✔
987

988
void SessionImpl::on_flx_sync_version_complete(int64_t version)
989
{
300✔
990
    // Ignore the call if the session is not active
991
    if (m_state == State::Active) {
300✔
992
        m_wrapper.on_flx_sync_version_complete(version);
300✔
993
    }
300✔
994
}
300✔
995

996
SyncClientHookAction SessionImpl::call_debug_hook(const SyncClientHookData& data)
997
{
2,152✔
998
    // Should never be called if session is not active
999
    REALM_ASSERT_EX(m_state == State::Active, m_state);
2,152✔
1000

1001
    // Make sure we don't call the debug hook recursively.
1002
    if (m_wrapper.m_in_debug_hook) {
2,152✔
1003
        return SyncClientHookAction::NoAction;
24✔
1004
    }
24✔
1005
    m_wrapper.m_in_debug_hook = true;
2,128✔
1006
    auto in_hook_guard = util::make_scope_exit([&]() noexcept {
2,128✔
1007
        m_wrapper.m_in_debug_hook = false;
2,128✔
1008
    });
2,128✔
1009

1010
    auto action = m_wrapper.m_debug_hook(data);
2,128✔
1011
    switch (action) {
2,128✔
1012
        case realm::SyncClientHookAction::SuspendWithRetryableError: {
12✔
1013
            SessionErrorInfo err_info(Status{ErrorCodes::RuntimeError, "hook requested error"}, IsFatal{false});
12✔
1014
            err_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
12✔
1015

1016
            auto err_processing_err = receive_error_message(err_info);
12✔
1017
            REALM_ASSERT_EX(err_processing_err.is_ok(), err_processing_err);
12✔
1018
            return SyncClientHookAction::EarlyReturn;
12✔
1019
        }
×
1020
        case realm::SyncClientHookAction::TriggerReconnect: {
24✔
1021
            get_connection().voluntary_disconnect();
24✔
1022
            return SyncClientHookAction::EarlyReturn;
24✔
1023
        }
×
1024
        default:
2,084✔
1025
            return action;
2,084✔
1026
    }
2,128✔
1027
}
2,128✔
1028

1029
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const SyncProgress& progress,
1030
                                                  int64_t query_version, DownloadBatchState batch_state,
1031
                                                  size_t num_changesets)
1032
{
119,744✔
1033
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
119,744✔
1034
        return SyncClientHookAction::NoAction;
117,758✔
1035
    }
117,758✔
1036
    if (REALM_UNLIKELY(m_state != State::Active)) {
1,986✔
1037
        return SyncClientHookAction::NoAction;
×
1038
    }
×
1039

1040
    SyncClientHookData data;
1,986✔
1041
    data.event = event;
1,986✔
1042
    data.batch_state = batch_state;
1,986✔
1043
    data.progress = progress;
1,986✔
1044
    data.num_changesets = num_changesets;
1,986✔
1045
    data.query_version = query_version;
1,986✔
1046

1047
    return call_debug_hook(data);
1,986✔
1048
}
1,986✔
1049

1050
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const ProtocolErrorInfo& error_info)
1051
{
1,380✔
1052
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
1,380✔
1053
        return SyncClientHookAction::NoAction;
1,212✔
1054
    }
1,212✔
1055
    if (REALM_UNLIKELY(m_state != State::Active)) {
168✔
1056
        return SyncClientHookAction::NoAction;
×
1057
    }
×
1058

1059
    SyncClientHookData data;
168✔
1060
    data.event = event;
168✔
1061
    data.batch_state = DownloadBatchState::SteadyState;
168✔
1062
    data.progress = m_progress;
168✔
1063
    data.num_changesets = 0;
168✔
1064
    data.query_version = 0;
168✔
1065
    data.error_info = &error_info;
168✔
1066

1067
    return call_debug_hook(data);
168✔
1068
}
168✔
1069

1070
bool SessionImpl::is_steady_state_download_message(DownloadBatchState batch_state, int64_t query_version)
1071
{
94,916✔
1072
    // Should never be called if session is not active
1073
    REALM_ASSERT_EX(m_state == State::Active, m_state);
94,916✔
1074
    if (batch_state == DownloadBatchState::SteadyState) {
94,916✔
1075
        return true;
45,314✔
1076
    }
45,314✔
1077

1078
    if (!m_is_flx_sync_session) {
49,602✔
1079
        return true;
44,000✔
1080
    }
44,000✔
1081

1082
    // If this is a steady state DOWNLOAD, no need for special handling.
1083
    if (batch_state == DownloadBatchState::LastInBatch && query_version == m_wrapper.m_flx_active_version) {
5,602✔
1084
        return true;
1,322✔
1085
    }
1,322✔
1086

1087
    return false;
4,280✔
1088
}
5,602✔
1089

1090
void SessionImpl::init_progress_handler()
1091
{
10,324✔
1092
    if (m_state != State::Unactivated && m_state != State::Active)
10,324✔
1093
        return;
×
1094

1095
    m_wrapper.init_progress_handler();
10,324✔
1096
}
10,324✔
1097

1098
void SessionImpl::enable_progress_notifications()
1099
{
45,856✔
1100
    m_wrapper.m_reliable_download_progress = true;
45,856✔
1101
}
45,856✔
1102

1103
void SessionImpl::notify_upload_progress()
1104
{
34,014✔
1105
    if (m_state != State::Active)
34,014✔
1106
        return;
×
1107

1108
    m_wrapper.on_upload_progress();
34,014✔
1109
}
34,014✔
1110

1111
void SessionImpl::update_download_estimate(double download_estimate)
1112
{
3,454✔
1113
    if (m_state != State::Active)
3,454✔
1114
        return;
×
1115

1116
    m_wrapper.m_download_estimate = download_estimate;
3,454✔
1117
}
3,454✔
1118

1119
void SessionImpl::notify_download_progress(const std::optional<uint64_t>& bootstrap_store_bytes)
1120
{
27,730✔
1121
    if (m_state != State::Active)
27,730✔
1122
        return;
×
1123

1124
    m_wrapper.on_download_progress(bootstrap_store_bytes); // Throws
27,730✔
1125
}
27,730✔
1126

1127
util::Future<std::string> SessionImpl::send_test_command(std::string body)
1128
{
60✔
1129
    if (m_state != State::Active) {
60✔
1130
        return Status{ErrorCodes::RuntimeError, "Cannot send a test command for a session that is not active"};
×
1131
    }
×
1132

1133
    try {
60✔
1134
        auto json_body = nlohmann::json::parse(body.begin(), body.end());
60✔
1135
        if (auto it = json_body.find("command"); it == json_body.end() || !it->is_string()) {
60✔
1136
            return Status{ErrorCodes::LogicError,
4✔
1137
                          "Must supply command name in \"command\" field of test command json object"};
4✔
1138
        }
4✔
1139
        if (json_body.size() > 1 && json_body.find("args") == json_body.end()) {
56✔
1140
            return Status{ErrorCodes::LogicError, "Only valid fields in a test command are \"command\" and \"args\""};
×
1141
        }
×
1142
    }
56✔
1143
    catch (const nlohmann::json::parse_error& e) {
60✔
1144
        return Status{ErrorCodes::LogicError, util::format("Invalid json input to send_test_command: %1", e.what())};
4✔
1145
    }
4✔
1146

1147
    auto pf = util::make_promise_future<std::string>();
52✔
1148
    get_client().post([this, promise = std::move(pf.promise), body = std::move(body)](Status status) mutable {
52✔
1149
        // Includes operation_aborted
1150
        if (!status.is_ok()) {
52✔
1151
            promise.set_error(status);
×
1152
            return;
×
1153
        }
×
1154

1155
        auto id = ++m_last_pending_test_command_ident;
52✔
1156
        m_pending_test_commands.push_back(PendingTestCommand{id, std::move(body), std::move(promise)});
52✔
1157
        ensure_enlisted_to_send();
52✔
1158
    });
52✔
1159

1160
    return std::move(pf.future);
52✔
1161
}
60✔
1162

1163
// ################ SessionWrapper ################
1164

1165
// The SessionWrapper class is held by a sync::Session (which is owned by the SyncSession instance) and
1166
// provides a link to the ClientImpl::Session that creates and receives messages with the server with
1167
// the ClientImpl::Connection that owns the ClientImpl::Session.
1168
SessionWrapper::SessionWrapper(ClientImpl& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1169
                               std::shared_ptr<MigrationStore> migration_store, Session::Config&& config)
1170
    : m_client{client}
4,880✔
1171
    , m_db(std::move(db))
4,880✔
1172
    , m_replication(m_db->get_replication())
4,880✔
1173
    , m_protocol_envelope{config.protocol_envelope}
4,880✔
1174
    , m_server_address{std::move(config.server_address)}
4,880✔
1175
    , m_server_port{config.server_port}
4,880✔
1176
    , m_server_verified{config.server_verified}
4,880✔
1177
    , m_user_id(std::move(config.user_id))
4,880✔
1178
    , m_sync_mode(flx_sub_store ? SyncServerMode::FLX : SyncServerMode::PBS)
4,880✔
1179
    , m_authorization_header_name{config.authorization_header_name}
4,880✔
1180
    , m_custom_http_headers{std::move(config.custom_http_headers)}
4,880✔
1181
    , m_verify_servers_ssl_certificate{config.verify_servers_ssl_certificate}
4,880✔
1182
    , m_simulate_integration_error{config.simulate_integration_error}
4,880✔
1183
    , m_ssl_trust_certificate_path{std::move(config.ssl_trust_certificate_path)}
4,880✔
1184
    , m_ssl_verify_callback{std::move(config.ssl_verify_callback)}
4,880✔
1185
    , m_flx_bootstrap_batch_size_bytes(config.flx_bootstrap_batch_size_bytes)
4,880✔
1186
    , m_http_request_path_prefix{std::move(config.service_identifier)}
4,880✔
1187
    , m_virt_path{std::move(config.realm_identifier)}
4,880✔
1188
    , m_proxy_config{std::move(config.proxy_config)}
4,880✔
1189
    , m_signed_access_token{std::move(config.signed_user_token)}
4,880✔
1190
    , m_client_reset_config{std::move(config.client_reset_config)}
4,880✔
1191
    , m_progress_handler(std::move(config.progress_handler))
4,880✔
1192
    , m_connection_state_change_listener(std::move(config.connection_state_change_listener))
4,880✔
1193
    , m_debug_hook(std::move(config.on_sync_client_event_hook))
4,880✔
1194
    , m_session_reason(m_client_reset_config ? SessionReason::ClientReset : config.session_reason)
4,880✔
1195
    , m_schema_version(config.schema_version)
4,880✔
1196
    , m_flx_subscription_store(std::move(flx_sub_store))
4,880✔
1197
    , m_migration_store(std::move(migration_store))
4,880✔
1198
{
10,104✔
1199
    REALM_ASSERT(m_db);
10,104✔
1200
    REALM_ASSERT(m_db->get_replication());
10,104✔
1201
    REALM_ASSERT(dynamic_cast<ClientReplication*>(m_db->get_replication()));
10,104✔
1202

1203
    // SessionWrapper begins at +1 retain count because Client retains and
1204
    // releases it while performing async operations, and these need to not
1205
    // take it to 0 or it could be deleted before the caller can retain it.
1206
    bind_ptr();
10,104✔
1207
    m_client.register_unactualized_session_wrapper(this);
10,104✔
1208
}
10,104✔
1209

1210
SessionWrapper::~SessionWrapper() noexcept
1211
{
10,092✔
1212
    // We begin actualization in the constructor and do not delete the wrapper
1213
    // until both the Client is done with it and the Session has abandoned it,
1214
    // so at this point we must have actualized, finalized, and been abandoned.
1215
    REALM_ASSERT(m_actualized);
10,092✔
1216
    REALM_ASSERT(m_abandoned);
10,092✔
1217
    REALM_ASSERT(m_finalized);
10,092✔
1218
    REALM_ASSERT(m_closed);
10,092✔
1219
    REALM_ASSERT(!m_db);
10,092✔
1220
}
10,092✔
1221

1222

1223
inline ClientReplication& SessionWrapper::get_replication() noexcept
1224
{
119,456✔
1225
    REALM_ASSERT(m_db);
119,456✔
1226
    return static_cast<ClientReplication&>(*m_replication);
119,456✔
1227
}
119,456✔
1228

1229

1230
inline ClientImpl& SessionWrapper::get_client() noexcept
1231
{
×
1232
    return m_client;
×
1233
}
×
1234

1235
bool SessionWrapper::has_flx_subscription_store() const
1236
{
1,972✔
1237
    return static_cast<bool>(m_flx_subscription_store);
1,972✔
1238
}
1,972✔
1239

1240
void SessionWrapper::on_flx_sync_error(int64_t version, std::string_view err_msg)
1241
{
20✔
1242
    REALM_ASSERT(!m_finalized);
20✔
1243
    get_flx_subscription_store()->update_state(version, SubscriptionSet::State::Error, err_msg);
20✔
1244
}
20✔
1245

1246
void SessionWrapper::on_flx_sync_version_complete(int64_t version)
1247
{
2,224✔
1248
    REALM_ASSERT(!m_finalized);
2,224✔
1249
    m_flx_last_seen_version = version;
2,224✔
1250
    m_flx_active_version = version;
2,224✔
1251
}
2,224✔
1252

1253
void SessionWrapper::on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state)
1254
{
1,972✔
1255
    if (!has_flx_subscription_store()) {
1,972✔
1256
        return;
×
1257
    }
×
1258
    REALM_ASSERT(!m_finalized);
1,972✔
1259
    REALM_ASSERT(new_version >= m_flx_last_seen_version);
1,972✔
1260
    REALM_ASSERT(new_version >= m_flx_active_version);
1,972✔
1261
    REALM_ASSERT(batch_state != DownloadBatchState::SteadyState);
1,972✔
1262

1263
    SubscriptionSet::State new_state = SubscriptionSet::State::Uncommitted; // Initialize to make compiler happy
1,972✔
1264

1265
    switch (batch_state) {
1,972✔
1266
        case DownloadBatchState::SteadyState:
✔
1267
            // Cannot be called with this value.
1268
            REALM_UNREACHABLE();
1269
        case DownloadBatchState::LastInBatch:
1,924✔
1270
            if (m_flx_active_version == new_version) {
1,924✔
1271
                return;
×
1272
            }
×
1273
            on_flx_sync_version_complete(new_version);
1,924✔
1274
            if (new_version == 0) {
1,924✔
1275
                new_state = SubscriptionSet::State::Complete;
912✔
1276
            }
912✔
1277
            else {
1,012✔
1278
                new_state = SubscriptionSet::State::AwaitingMark;
1,012✔
1279
                m_flx_pending_mark_version = new_version;
1,012✔
1280
            }
1,012✔
1281
            break;
1,924✔
1282
        case DownloadBatchState::MoreToCome:
48✔
1283
            if (m_flx_last_seen_version == new_version) {
48✔
1284
                return;
×
1285
            }
×
1286

1287
            m_flx_last_seen_version = new_version;
48✔
1288
            new_state = SubscriptionSet::State::Bootstrapping;
48✔
1289
            break;
48✔
1290
    }
1,972✔
1291

1292
    get_flx_subscription_store()->update_state(new_version, new_state);
1,972✔
1293
}
1,972✔
1294

1295
SubscriptionStore* SessionWrapper::get_flx_subscription_store()
1296
{
20,218✔
1297
    REALM_ASSERT(!m_finalized);
20,218✔
1298
    return m_flx_subscription_store.get();
20,218✔
1299
}
20,218✔
1300

1301
PendingBootstrapStore* SessionWrapper::get_flx_pending_bootstrap_store()
1302
{
5,558✔
1303
    REALM_ASSERT(!m_finalized);
5,558✔
1304
    return m_flx_pending_bootstrap_store.get();
5,558✔
1305
}
5,558✔
1306

1307
MigrationStore* SessionWrapper::get_migration_store()
1308
{
67,400✔
1309
    REALM_ASSERT(!m_finalized);
67,400✔
1310
    return m_migration_store.get();
67,400✔
1311
}
67,400✔
1312

1313
inline bool SessionWrapper::mark_abandoned()
1314
{
10,104✔
1315
    REALM_ASSERT(!m_abandoned);
10,104✔
1316
    m_abandoned = true;
10,104✔
1317
    return m_finalized;
10,104✔
1318
}
10,104✔
1319

1320

1321
void SessionWrapper::on_commit(version_type new_version)
1322
{
113,714✔
1323
    // Thread safety required
1324
    m_client.post([self = util::bind_ptr{this}, new_version] {
113,714✔
1325
        REALM_ASSERT(self->m_actualized);
113,712✔
1326
        if (REALM_UNLIKELY(!self->m_sess))
113,712✔
1327
            return; // Already finalized
948✔
1328
        SessionImpl& sess = *self->m_sess;
112,764✔
1329
        sess.recognize_sync_version(new_version);                           // Throws
112,764✔
1330
        self->on_upload_progress(/* only_if_new_uploadable_data = */ true); // Throws
112,764✔
1331
    });
112,764✔
1332
}
113,714✔
1333

1334

1335
void SessionWrapper::cancel_reconnect_delay()
1336
{
20✔
1337
    // Thread safety required
1338

1339
    m_client.post([self = util::bind_ptr{this}] {
20✔
1340
        REALM_ASSERT(self->m_actualized);
20✔
1341
        if (REALM_UNLIKELY(self->m_closed)) {
20✔
1342
            return;
×
1343
        }
×
1344

1345
        if (REALM_UNLIKELY(!self->m_sess))
20✔
1346
            return; // Already finalized
×
1347
        SessionImpl& sess = *self->m_sess;
20✔
1348
        sess.cancel_resumption_delay(); // Throws
20✔
1349
        ClientImpl::Connection& conn = sess.get_connection();
20✔
1350
        conn.cancel_reconnect_delay(); // Throws
20✔
1351
    });                                // Throws
20✔
1352
}
20✔
1353

1354
void SessionWrapper::async_wait_for(bool upload_completion, bool download_completion,
1355
                                    WaitOperCompletionHandler handler)
1356
{
5,178✔
1357
    REALM_ASSERT(upload_completion || download_completion);
5,178✔
1358

1359
    m_client.post([self = util::bind_ptr{this}, handler = std::move(handler), upload_completion,
5,178✔
1360
                   download_completion]() mutable {
5,178✔
1361
        REALM_ASSERT(self->m_actualized);
5,178✔
1362
        if (REALM_UNLIKELY(!self->m_sess)) {
5,178✔
1363
            // Already finalized
1364
            handler({ErrorCodes::OperationAborted, "Session finalized before callback could run"}); // Throws
104✔
1365
            return;
104✔
1366
        }
104✔
1367
        if (upload_completion) {
5,074✔
1368
            if (download_completion) {
2,602✔
1369
                // Wait for upload and download completion
1370
                self->m_sync_completion_handlers.push_back(std::move(handler)); // Throws
314✔
1371
            }
314✔
1372
            else {
2,288✔
1373
                // Wait for upload completion only
1374
                self->m_upload_completion_handlers.push_back(std::move(handler)); // Throws
2,288✔
1375
            }
2,288✔
1376
        }
2,602✔
1377
        else {
2,472✔
1378
            // Wait for download completion only
1379
            self->m_download_completion_handlers.push_back(std::move(handler)); // Throws
2,472✔
1380
        }
2,472✔
1381
        SessionImpl& sess = *self->m_sess;
5,074✔
1382
        if (upload_completion)
5,074✔
1383
            sess.request_upload_completion_notification(); // Throws
2,602✔
1384
        if (download_completion)
5,074✔
1385
            sess.request_download_completion_notification(); // Throws
2,786✔
1386
    });                                                      // Throws
5,074✔
1387
}
5,178✔
1388

1389

1390
bool SessionWrapper::wait_for_upload_complete_or_client_stopped()
1391
{
12,900✔
1392
    // Thread safety required
1393
    REALM_ASSERT(!m_abandoned);
12,900✔
1394

1395
    std::int_fast64_t target_mark;
12,900✔
1396
    {
12,900✔
1397
        util::CheckedLockGuard lock{m_client.m_mutex};
12,900✔
1398
        target_mark = ++m_target_upload_mark;
12,900✔
1399
    }
12,900✔
1400

1401
    m_client.post([self = util::bind_ptr{this}, target_mark] {
12,900✔
1402
        REALM_ASSERT(self->m_actualized);
12,898✔
1403
        // The session wrapper may already have been finalized. This can only
1404
        // happen if it was abandoned, but in that case, the call of
1405
        // wait_for_upload_complete_or_client_stopped() must have returned
1406
        // already.
1407
        if (REALM_UNLIKELY(!self->m_sess))
12,898✔
1408
            return;
24✔
1409
        if (target_mark > self->m_staged_upload_mark) {
12,874✔
1410
            self->m_staged_upload_mark = target_mark;
12,874✔
1411
            SessionImpl& sess = *self->m_sess;
12,874✔
1412
            sess.request_upload_completion_notification(); // Throws
12,874✔
1413
        }
12,874✔
1414
    }); // Throws
12,874✔
1415

1416
    bool completion_condition_was_satisfied;
12,900✔
1417
    {
12,900✔
1418
        util::CheckedUniqueLock lock{m_client.m_mutex};
12,900✔
1419
        m_client.m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_client.m_mutex) {
32,832✔
1420
            return m_reached_upload_mark >= target_mark || m_client.m_stopped;
32,832✔
1421
        });
32,832✔
1422
        completion_condition_was_satisfied = !m_client.m_stopped;
12,900✔
1423
    }
12,900✔
1424
    return completion_condition_was_satisfied;
12,900✔
1425
}
12,900✔
1426

1427

1428
bool SessionWrapper::wait_for_download_complete_or_client_stopped()
1429
{
9,988✔
1430
    // Thread safety required
1431
    REALM_ASSERT(!m_abandoned);
9,988✔
1432

1433
    std::int_fast64_t target_mark;
9,988✔
1434
    {
9,988✔
1435
        util::CheckedLockGuard lock{m_client.m_mutex};
9,988✔
1436
        target_mark = ++m_target_download_mark;
9,988✔
1437
    }
9,988✔
1438

1439
    m_client.post([self = util::bind_ptr{this}, target_mark] {
9,988✔
1440
        REALM_ASSERT(self->m_actualized);
9,988✔
1441
        // The session wrapper may already have been finalized. This can only
1442
        // happen if it was abandoned, but in that case, the call of
1443
        // wait_for_download_complete_or_client_stopped() must have returned
1444
        // already.
1445
        if (REALM_UNLIKELY(!self->m_sess))
9,988✔
1446
            return;
60✔
1447
        if (target_mark > self->m_staged_download_mark) {
9,928✔
1448
            self->m_staged_download_mark = target_mark;
9,928✔
1449
            SessionImpl& sess = *self->m_sess;
9,928✔
1450
            sess.request_download_completion_notification(); // Throws
9,928✔
1451
        }
9,928✔
1452
    }); // Throws
9,928✔
1453

1454
    bool completion_condition_was_satisfied;
9,988✔
1455
    {
9,988✔
1456
        util::CheckedUniqueLock lock{m_client.m_mutex};
9,988✔
1457
        m_client.m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_client.m_mutex) {
20,244✔
1458
            return m_reached_download_mark >= target_mark || m_client.m_stopped;
20,244✔
1459
        });
20,244✔
1460
        completion_condition_was_satisfied = !m_client.m_stopped;
9,988✔
1461
    }
9,988✔
1462
    return completion_condition_was_satisfied;
9,988✔
1463
}
9,988✔
1464

1465

1466
void SessionWrapper::refresh(std::string_view signed_access_token)
1467
{
216✔
1468
    // Thread safety required
1469
    REALM_ASSERT(!m_abandoned);
216✔
1470

1471
    m_client.post([self = util::bind_ptr{this}, token = std::string(signed_access_token)] {
216✔
1472
        REALM_ASSERT(self->m_actualized);
216✔
1473
        if (REALM_UNLIKELY(!self->m_sess))
216✔
1474
            return; // Already finalized
4✔
1475
        self->m_signed_access_token = std::move(token);
212✔
1476
        SessionImpl& sess = *self->m_sess;
212✔
1477
        ClientImpl::Connection& conn = sess.get_connection();
212✔
1478
        // FIXME: This only makes sense when each session uses a separate connection.
1479
        conn.update_connect_info(self->m_http_request_path_prefix, self->m_signed_access_token); // Throws
212✔
1480
        sess.cancel_resumption_delay();                                                          // Throws
212✔
1481
        conn.cancel_reconnect_delay();                                                           // Throws
212✔
1482
    });
212✔
1483
}
216✔
1484

1485

1486
void SessionWrapper::abandon(util::bind_ptr<SessionWrapper> wrapper) noexcept
1487
{
10,102✔
1488
    ClientImpl& client = wrapper->m_client;
10,102✔
1489
    client.register_abandoned_session_wrapper(std::move(wrapper));
10,102✔
1490
}
10,102✔
1491

1492

1493
// Must be called from event loop thread
1494
void SessionWrapper::actualize()
1495
{
10,030✔
1496
    // actualize() can only ever be called once
1497
    REALM_ASSERT(!m_actualized);
10,030✔
1498
    REALM_ASSERT(!m_sess);
10,030✔
1499
    // The client should have removed this wrapper from those pending
1500
    // actualization if it called force_close() or finalize_before_actualize()
1501
    REALM_ASSERT(!m_finalized);
10,030✔
1502
    REALM_ASSERT(!m_closed);
10,030✔
1503

1504
    m_actualized = true;
10,030✔
1505

1506
    ScopeExitFail close_on_error([&]() noexcept {
10,030✔
1507
        m_closed = true;
4✔
1508
    });
4✔
1509

1510
    m_db->claim_sync_agent();
10,030✔
1511
    m_db->add_commit_listener(this);
10,030✔
1512
    ScopeExitFail remove_commit_listener([&]() noexcept {
10,030✔
1513
        m_db->remove_commit_listener(this);
×
1514
    });
×
1515

1516
    ServerEndpoint endpoint{m_protocol_envelope, m_server_address, m_server_port,
10,030✔
1517
                            m_user_id,           m_sync_mode,      m_server_verified};
10,030✔
1518
    bool was_created = false;
10,030✔
1519
    ClientImpl::Connection& conn = m_client.get_connection(
10,030✔
1520
        std::move(endpoint), m_authorization_header_name, m_custom_http_headers, m_verify_servers_ssl_certificate,
10,030✔
1521
        m_ssl_trust_certificate_path, m_ssl_verify_callback, m_proxy_config,
10,030✔
1522
        was_created); // Throws
10,030✔
1523
    ScopeExitFail remove_connection([&]() noexcept {
10,030✔
1524
        if (was_created)
×
1525
            m_client.remove_connection(conn);
×
1526
    });
×
1527

1528
    // FIXME: This only makes sense when each session uses a separate connection.
1529
    conn.update_connect_info(m_http_request_path_prefix, m_signed_access_token);    // Throws
10,030✔
1530
    std::unique_ptr<SessionImpl> sess = std::make_unique<SessionImpl>(*this, conn); // Throws
10,030✔
1531
    if (m_sync_mode == SyncServerMode::FLX) {
10,030✔
1532
        m_flx_pending_bootstrap_store = std::make_unique<PendingBootstrapStore>(m_db, sess->logger);
1,494✔
1533
    }
1,494✔
1534

1535
    sess->logger.info("Binding '%1' to '%2'", m_db->get_path(), m_virt_path); // Throws
10,030✔
1536
    m_sess = sess.get();
10,030✔
1537
    ScopeExitFail clear_sess([&]() noexcept {
10,030✔
1538
        m_sess = nullptr;
×
1539
    });
×
1540
    conn.activate_session(std::move(sess)); // Throws
10,030✔
1541

1542
    // Initialize the variables relying on the bootstrap store from the event loop to guarantee that a previous
1543
    // session cannot change the state of the bootstrap store at the same time.
1544
    update_subscription_version_info();
10,030✔
1545

1546
    if (was_created)
10,030✔
1547
        conn.activate(); // Throws
2,776✔
1548

1549
    if (m_connection_state_change_listener) {
10,030✔
1550
        ConnectionState state = conn.get_state();
10,020✔
1551
        if (state != ConnectionState::disconnected) {
10,020✔
1552
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,098✔
1553
            if (state == ConnectionState::connected)
7,098✔
1554
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
6,794✔
1555
        }
7,098✔
1556
    }
10,020✔
1557

1558
    if (!m_client_reset_config)
10,030✔
1559
        on_upload_progress(/* only_if_new_uploadable_data = */ true); // Throws
9,650✔
1560
}
10,030✔
1561

1562
void SessionWrapper::force_close()
1563
{
10,122✔
1564
    if (m_closed) {
10,122✔
1565
        return;
106✔
1566
    }
106✔
1567
    REALM_ASSERT(m_actualized);
10,016✔
1568
    REALM_ASSERT(m_sess);
10,016✔
1569
    m_closed = true;
10,016✔
1570

1571
    ClientImpl::Connection& conn = m_sess->get_connection();
10,016✔
1572
    conn.initiate_session_deactivation(m_sess); // Throws
10,016✔
1573

1574
    // We need to keep the DB open until finalization, but we no longer want to
1575
    // know when commits are made
1576
    m_db->remove_commit_listener(this);
10,016✔
1577

1578
    // Delete the pending bootstrap store since it uses a reference to the logger in m_sess
1579
    m_flx_pending_bootstrap_store.reset();
10,016✔
1580
    // Clear the subscription and migration store refs since they are owned by SyncSession
1581
    m_flx_subscription_store.reset();
10,016✔
1582
    m_migration_store.reset();
10,016✔
1583
    m_sess = nullptr;
10,016✔
1584
    // Everything is being torn down, no need to report connection state anymore
1585
    m_connection_state_change_listener = {};
10,016✔
1586
}
10,016✔
1587

1588
// Must be called from event loop thread
1589
//
1590
// `m_client.m_mutex` is not held while this is called, but it is guaranteed to
1591
// have been acquired at some point in between the final read or write ever made
1592
// from a different thread and when this is called.
1593
void SessionWrapper::finalize()
1594
{
10,020✔
1595
    REALM_ASSERT(m_actualized);
10,020✔
1596
    REALM_ASSERT(m_abandoned);
10,020✔
1597
    REALM_ASSERT(!m_finalized);
10,020✔
1598

1599
    force_close();
10,020✔
1600

1601
    m_finalized = true;
10,020✔
1602

1603
    // The Realm file can be closed now, as no access to the Realm file is
1604
    // supposed to happen on behalf of a session after initiation of
1605
    // deactivation.
1606
    m_db->release_sync_agent();
10,020✔
1607
    m_db = nullptr;
10,020✔
1608

1609
    // All outstanding wait operations must be canceled
1610
    while (!m_upload_completion_handlers.empty()) {
10,458✔
1611
        auto handler = std::move(m_upload_completion_handlers.back());
438✔
1612
        m_upload_completion_handlers.pop_back();
438✔
1613
        handler(
438✔
1614
            {ErrorCodes::OperationAborted, "Sync session is being finalized before upload was complete"}); // Throws
438✔
1615
    }
438✔
1616
    while (!m_download_completion_handlers.empty()) {
10,242✔
1617
        auto handler = std::move(m_download_completion_handlers.back());
222✔
1618
        m_download_completion_handlers.pop_back();
222✔
1619
        handler(
222✔
1620
            {ErrorCodes::OperationAborted, "Sync session is being finalized before download was complete"}); // Throws
222✔
1621
    }
222✔
1622
    while (!m_sync_completion_handlers.empty()) {
10,040✔
1623
        auto handler = std::move(m_sync_completion_handlers.back());
20✔
1624
        m_sync_completion_handlers.pop_back();
20✔
1625
        handler({ErrorCodes::OperationAborted, "Sync session is being finalized before sync was complete"}); // Throws
20✔
1626
    }
20✔
1627
}
10,020✔
1628

1629

1630
// Must be called only when an unactualized session wrapper becomes abandoned.
1631
//
1632
// Called with a lock on `m_client.m_mutex`.
1633
inline void SessionWrapper::finalize_before_actualization() noexcept
1634
{
72✔
1635
    REALM_ASSERT(!m_finalized);
72✔
1636
    REALM_ASSERT(!m_sess);
72✔
1637
    m_actualized = true;
72✔
1638
    m_finalized = true;
72✔
1639
    m_closed = true;
72✔
1640
    m_db->remove_commit_listener(this);
72✔
1641
    m_db->release_sync_agent();
72✔
1642
    m_db = nullptr;
72✔
1643
}
72✔
1644

1645
inline void SessionWrapper::on_upload_progress(bool only_if_new_uploadable_data)
1646
{
156,430✔
1647
    REALM_ASSERT(!m_finalized);
156,430✔
1648
    report_progress(/* is_download = */ false, only_if_new_uploadable_data); // Throws
156,430✔
1649
}
156,430✔
1650

1651
inline void SessionWrapper::on_download_progress(const std::optional<uint64_t>& bootstrap_store_bytes)
1652
{
27,730✔
1653
    REALM_ASSERT(!m_finalized);
27,730✔
1654
    m_bootstrap_store_bytes = bootstrap_store_bytes;
27,730✔
1655
    report_progress(/* is_download = */ true); // Throws
27,730✔
1656
}
27,730✔
1657

1658

1659
void SessionWrapper::on_upload_completion()
1660
{
14,794✔
1661
    REALM_ASSERT(!m_finalized);
14,794✔
1662
    while (!m_upload_completion_handlers.empty()) {
16,740✔
1663
        auto handler = std::move(m_upload_completion_handlers.back());
1,946✔
1664
        m_upload_completion_handlers.pop_back();
1,946✔
1665
        handler(Status::OK()); // Throws
1,946✔
1666
    }
1,946✔
1667
    while (!m_sync_completion_handlers.empty()) {
14,992✔
1668
        auto handler = std::move(m_sync_completion_handlers.back());
198✔
1669
        m_download_completion_handlers.push_back(std::move(handler)); // Throws
198✔
1670
        m_sync_completion_handlers.pop_back();
198✔
1671
    }
198✔
1672
    util::CheckedLockGuard lock{m_client.m_mutex};
14,794✔
1673
    if (m_staged_upload_mark > m_reached_upload_mark) {
14,794✔
1674
        m_reached_upload_mark = m_staged_upload_mark;
12,862✔
1675
        m_client.m_wait_or_client_stopped_cond.notify_all();
12,862✔
1676
    }
12,862✔
1677
}
14,794✔
1678

1679

1680
void SessionWrapper::on_download_completion()
1681
{
16,112✔
1682
    while (!m_download_completion_handlers.empty()) {
18,548✔
1683
        auto handler = std::move(m_download_completion_handlers.back());
2,436✔
1684
        m_download_completion_handlers.pop_back();
2,436✔
1685
        handler(Status::OK()); // Throws
2,436✔
1686
    }
2,436✔
1687
    while (!m_sync_completion_handlers.empty()) {
16,208✔
1688
        auto handler = std::move(m_sync_completion_handlers.back());
96✔
1689
        m_upload_completion_handlers.push_back(std::move(handler)); // Throws
96✔
1690
        m_sync_completion_handlers.pop_back();
96✔
1691
    }
96✔
1692

1693
    if (m_flx_subscription_store && m_flx_pending_mark_version != SubscriptionSet::EmptyVersion) {
16,112✔
1694
        m_sess->logger.debug("Marking query version %1 as complete after receiving MARK message",
880✔
1695
                             m_flx_pending_mark_version);
880✔
1696
        m_flx_subscription_store->update_state(m_flx_pending_mark_version, SubscriptionSet::State::Complete);
880✔
1697
        m_flx_pending_mark_version = SubscriptionSet::EmptyVersion;
880✔
1698
    }
880✔
1699

1700
    util::CheckedLockGuard lock{m_client.m_mutex};
16,112✔
1701
    if (m_staged_download_mark > m_reached_download_mark) {
16,112✔
1702
        m_reached_download_mark = m_staged_download_mark;
9,858✔
1703
        m_client.m_wait_or_client_stopped_cond.notify_all();
9,858✔
1704
    }
9,858✔
1705
}
16,112✔
1706

1707

1708
void SessionWrapper::on_suspended(const SessionErrorInfo& error_info)
1709
{
670✔
1710
    REALM_ASSERT(!m_finalized);
670✔
1711
    m_suspended = true;
670✔
1712
    if (m_connection_state_change_listener) {
670✔
1713
        m_connection_state_change_listener(ConnectionState::disconnected, error_info); // Throws
670✔
1714
    }
670✔
1715
}
670✔
1716

1717

1718
void SessionWrapper::on_resumed()
1719
{
62✔
1720
    REALM_ASSERT(!m_finalized);
62✔
1721
    m_suspended = false;
62✔
1722
    if (m_connection_state_change_listener) {
62✔
1723
        ClientImpl::Connection& conn = m_sess->get_connection();
62✔
1724
        if (conn.get_state() != ConnectionState::disconnected) {
62✔
1725
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
52✔
1726
            if (conn.get_state() == ConnectionState::connected)
52✔
1727
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
50✔
1728
        }
52✔
1729
    }
62✔
1730
}
62✔
1731

1732

1733
void SessionWrapper::on_connection_state_changed(ConnectionState state,
1734
                                                 const std::optional<SessionErrorInfo>& error_info)
1735
{
12,040✔
1736
    if (m_connection_state_change_listener && !m_suspended) {
12,040✔
1737
        m_connection_state_change_listener(state, error_info); // Throws
12,008✔
1738
    }
12,008✔
1739
}
12,040✔
1740

1741
void SessionWrapper::init_progress_handler()
1742
{
10,324✔
1743
    uint64_t unused = 0;
10,324✔
1744
    ClientHistory::get_upload_download_bytes(m_db.get(), m_reported_progress.final_downloaded, unused,
10,324✔
1745
                                             m_reported_progress.final_uploaded, unused, unused);
10,324✔
1746
}
10,324✔
1747

1748
void SessionWrapper::report_progress(bool is_download, bool only_if_new_uploadable_data)
1749
{
184,158✔
1750
    REALM_ASSERT(!m_finalized);
184,158✔
1751
    REALM_ASSERT(m_sess);
184,158✔
1752
    REALM_ASSERT(!(only_if_new_uploadable_data && is_download));
184,158✔
1753

1754
    if (!m_progress_handler)
184,158✔
1755
        return;
129,628✔
1756

1757
    // Ignore progress messages from before we first receive a DOWNLOAD message
1758
    if (!m_reliable_download_progress)
54,530✔
1759
        return;
27,490✔
1760

1761
    ReportedProgress p = m_reported_progress;
27,040✔
1762
    ClientHistory::get_upload_download_bytes(m_db.get(), p.downloaded, p.downloadable, p.uploaded, p.uploadable,
27,040✔
1763
                                             p.snapshot);
27,040✔
1764

1765
    // If this progress notification was triggered by a commit being made we
1766
    // only want to send it if the uploadable bytes has actually increased,
1767
    // and not if it was an empty commit.
1768
    if (only_if_new_uploadable_data && m_reported_progress.uploadable == p.uploadable)
27,040✔
1769
        return;
18,388✔
1770

1771
    // uploadable_bytes is uploaded + remaining to upload, while downloadable_bytes
1772
    // is only the remaining to download. This is confusing, so make them use
1773
    // the same units.
1774
    p.downloadable += p.downloaded;
8,652✔
1775

1776
    bool is_completed = false;
8,652✔
1777
    if (is_download) {
8,652✔
1778
        if (m_download_estimate)
3,374✔
1779
            is_completed = *m_download_estimate >= 1.0;
1,298✔
1780
        else
2,076✔
1781
            is_completed = p.downloaded == p.downloadable;
2,076✔
1782
    }
3,374✔
1783
    else {
5,278✔
1784
        is_completed = p.uploaded == p.uploadable;
5,278✔
1785
    }
5,278✔
1786

1787
    auto calculate_progress = [](uint64_t transferred, uint64_t transferable, uint64_t final_transferred) {
9,516✔
1788
        REALM_ASSERT_DEBUG_EX(final_transferred <= transferred, final_transferred, transferred, transferable);
9,516✔
1789
        REALM_ASSERT_DEBUG_EX(transferred <= transferable, final_transferred, transferred, transferable);
9,516✔
1790

1791
        // The effect of this calculation is that if new bytes are added for download/upload,
1792
        // the progress estimate doesn't go back to zero, but it goes back to some non-zero percentage.
1793
        // This calculation allows a clean progression from 0 to 1.0 even if the new data is added for the sync
1794
        // before progress has reached 1.0.
1795
        // Then once it is at 1.0 the next batch of changes will restart the estimate at 0.
1796
        // Example for upload progress reported:
1797
        // 0 -> 1.0 -> new data added -> 0.0 -> 0.1 ...sync... -> 0.4 -> new data added -> 0.3 ...sync.. -> 1.0
1798

1799
        double progress_estimate = 1.0;
9,516✔
1800
        if (final_transferred < transferable && transferred < transferable)
9,516✔
1801
            progress_estimate = (transferred - final_transferred) / double(transferable - final_transferred);
4,022✔
1802
        return progress_estimate;
9,516✔
1803
    };
9,516✔
1804

1805
    double upload_estimate = 1.0, download_estimate = 1.0;
8,652✔
1806

1807
    // calculate estimate for both download/upload since the progress is reported all at once
1808
    if (!is_completed || is_download)
8,652✔
1809
        upload_estimate = calculate_progress(p.uploaded, p.uploadable, p.final_uploaded);
5,848✔
1810

1811
    // download estimate only known for flx
1812
    if (m_download_estimate) {
8,652✔
1813
        download_estimate = *m_download_estimate;
2,938✔
1814

1815
        // ... bootstrap store bytes should be null after initial sync when every changeset integrated immediately
1816
        if (m_bootstrap_store_bytes)
2,938✔
1817
            p.downloaded += *m_bootstrap_store_bytes;
196✔
1818

1819
        // FIXME for flx with download estimate these bytes are not known
1820
        // provide some sensible value for non-streaming version of object-store callbacks
1821
        // until these field are completely removed from the api after pbs deprecation
1822
        p.downloadable = p.downloaded;
2,938✔
1823
        if (0.01 <= download_estimate && download_estimate <= 0.99)
2,938✔
1824
            if (p.downloaded > p.final_downloaded)
160✔
1825
                p.downloadable =
160✔
1826
                    p.final_downloaded + uint64_t((p.downloaded - p.final_downloaded) / download_estimate);
160✔
1827
    }
2,938✔
1828
    else {
5,714✔
1829
        if (!is_completed || !is_download)
5,714✔
1830
            download_estimate = calculate_progress(p.downloaded, p.downloadable, p.final_downloaded);
3,668✔
1831
    }
5,714✔
1832

1833
    if (is_completed) {
8,652✔
1834
        if (is_download)
5,948✔
1835
            p.final_downloaded = p.downloaded;
3,146✔
1836
        else
2,802✔
1837
            p.final_uploaded = p.uploaded;
2,802✔
1838
    }
5,948✔
1839

1840
    m_reported_progress = p;
8,652✔
1841

1842
    if (m_sess->logger.would_log(Logger::Level::debug)) {
8,652✔
1843
        auto to_str = [](double d) {
16,788✔
1844
            std::ostringstream ss;
16,788✔
1845
            // progress estimate string in the DOWNLOAD message isn't expected to have more than 4 digits of precision
1846
            ss << std::fixed << std::setprecision(4) << d;
16,788✔
1847
            return ss.str();
16,788✔
1848
        };
16,788✔
1849
        m_sess->logger.debug(
8,394✔
1850
            "Progress handler called, downloaded = %1, downloadable = %2, estimate = %3, "
8,394✔
1851
            "uploaded = %4, uploadable = %5, estimate = %6, snapshot version = %7, query_version = %8",
8,394✔
1852
            p.downloaded, p.downloadable, to_str(download_estimate), p.uploaded, p.uploadable,
8,394✔
1853
            to_str(upload_estimate), p.snapshot, m_flx_active_version);
8,394✔
1854
    }
8,394✔
1855

1856
    m_progress_handler(p.downloaded, p.downloadable, p.uploaded, p.uploadable, p.snapshot, download_estimate,
8,652✔
1857
                       upload_estimate, m_flx_last_seen_version);
8,652✔
1858
}
8,652✔
1859

1860
util::Future<std::string> SessionWrapper::send_test_command(std::string body)
1861
{
60✔
1862
    if (!m_sess) {
60✔
1863
        return Status{ErrorCodes::RuntimeError, "session must be activated to send a test command"};
×
1864
    }
×
1865

1866
    return m_sess->send_test_command(std::move(body));
60✔
1867
}
60✔
1868

1869
void SessionWrapper::handle_pending_client_reset_acknowledgement()
1870
{
10,324✔
1871
    REALM_ASSERT(!m_finalized);
10,324✔
1872

1873
    auto has_pending_reset = PendingResetStore::has_pending_reset(m_db->start_frozen());
10,324✔
1874
    if (!has_pending_reset) {
10,324✔
1875
        return; // nothing to do
9,998✔
1876
    }
9,998✔
1877

1878
    m_sess->logger.info(util::LogCategory::reset, "Tracking %1", *has_pending_reset);
326✔
1879

1880
    // Now that the client reset merge is complete, wait for the changes to synchronize with the server
1881
    async_wait_for(
326✔
1882
        true, true, [self = util::bind_ptr(this), pending_reset = std::move(*has_pending_reset)](Status status) {
326✔
1883
            if (status == ErrorCodes::OperationAborted) {
322✔
1884
                return;
148✔
1885
            }
148✔
1886
            auto& logger = self->m_sess->logger;
174✔
1887
            if (!status.is_ok()) {
174✔
NEW
1888
                logger.error(util::LogCategory::reset, "Error while tracking client reset acknowledgement: %1",
×
NEW
1889
                             status);
×
NEW
1890
                return;
×
NEW
1891
            }
×
1892

1893
            logger.debug(util::LogCategory::reset, "Server has acknowledged %1", pending_reset);
174✔
1894

1895
            auto tr = self->m_db->start_write();
174✔
1896
            auto cur_pending_reset = PendingResetStore::has_pending_reset(tr);
174✔
1897
            if (!cur_pending_reset) {
174✔
NEW
1898
                logger.debug(util::LogCategory::reset, "Client reset cycle detection tracker already removed.");
×
NEW
1899
                return;
×
NEW
1900
            }
×
1901
            if (*cur_pending_reset == pending_reset) {
174✔
1902
                logger.debug(util::LogCategory::reset, "Removing client reset cycle detection tracker.");
174✔
1903
            }
174✔
NEW
1904
            else {
×
NEW
1905
                logger.info(util::LogCategory::reset, "Found new %1", cur_pending_reset);
×
NEW
1906
            }
×
1907
            PendingResetStore::clear_pending_reset(tr);
174✔
1908
            tr->commit();
174✔
1909
        });
174✔
1910
}
326✔
1911

1912
void SessionWrapper::update_subscription_version_info()
1913
{
10,320✔
1914
    if (!m_flx_subscription_store)
10,320✔
1915
        return;
8,712✔
1916
    auto versions_info = m_flx_subscription_store->get_version_info();
1,608✔
1917
    m_flx_active_version = versions_info.active;
1,608✔
1918
    m_flx_pending_mark_version = versions_info.pending_mark;
1,608✔
1919
}
1,608✔
1920

1921
std::string SessionWrapper::get_appservices_connection_id()
1922
{
72✔
1923
    auto pf = util::make_promise_future<std::string>();
72✔
1924

1925
    m_client.post([self = util::bind_ptr{this}, promise = std::move(pf.promise)](Status status) mutable {
72✔
1926
        if (!status.is_ok()) {
72✔
1927
            promise.set_error(status);
×
1928
            return;
×
1929
        }
×
1930

1931
        if (!self->m_sess) {
72✔
1932
            promise.set_error({ErrorCodes::RuntimeError, "session already finalized"});
×
1933
            return;
×
1934
        }
×
1935

1936
        promise.emplace_value(self->m_sess->get_connection().get_active_appservices_connection_id());
72✔
1937
    });
72✔
1938

1939
    return pf.future.get();
72✔
1940
}
72✔
1941

1942
// ################ ClientImpl::Connection ################
1943

1944
ClientImpl::Connection::Connection(ClientImpl& client, connection_ident_type ident, ServerEndpoint endpoint,
1945
                                   const std::string& authorization_header_name,
1946
                                   const std::map<std::string, std::string>& custom_http_headers,
1947
                                   bool verify_servers_ssl_certificate,
1948
                                   Optional<std::string> ssl_trust_certificate_path,
1949
                                   std::function<SSLVerifyCallback> ssl_verify_callback,
1950
                                   Optional<ProxyConfig> proxy_config, ReconnectInfo reconnect_info)
1951
    : logger_ptr{std::make_shared<util::PrefixLogger>(util::LogCategory::session, make_logger_prefix(ident),
1,322✔
1952
                                                      client.logger_ptr)} // Throws
1,322✔
1953
    , logger{*logger_ptr}
1,322✔
1954
    , m_client{client}
1,322✔
1955
    , m_verify_servers_ssl_certificate{verify_servers_ssl_certificate}    // DEPRECATED
1,322✔
1956
    , m_ssl_trust_certificate_path{std::move(ssl_trust_certificate_path)} // DEPRECATED
1,322✔
1957
    , m_ssl_verify_callback{std::move(ssl_verify_callback)}               // DEPRECATED
1,322✔
1958
    , m_proxy_config{std::move(proxy_config)}                             // DEPRECATED
1,322✔
1959
    , m_reconnect_info{reconnect_info}
1,322✔
1960
    , m_ident{ident}
1,322✔
1961
    , m_server_endpoint{std::move(endpoint)}
1,322✔
1962
    , m_authorization_header_name{authorization_header_name} // DEPRECATED
1,322✔
1963
    , m_custom_http_headers{custom_http_headers}             // DEPRECATED
1,322✔
1964
{
2,778✔
1965
    m_on_idle = m_client.create_trigger([this](Status status) {
2,778✔
1966
        if (status == ErrorCodes::OperationAborted)
2,770✔
1967
            return;
×
1968
        else if (!status.is_ok())
2,770✔
1969
            throw Exception(status);
×
1970

1971
        REALM_ASSERT(m_activated);
2,770✔
1972
        if (m_state == ConnectionState::disconnected && m_num_active_sessions == 0) {
2,774✔
1973
            on_idle(); // Throws
2,766✔
1974
            // Connection object may be destroyed now.
1975
        }
2,766✔
1976
    });
2,770✔
1977
}
2,778✔
1978

1979
inline connection_ident_type ClientImpl::Connection::get_ident() const noexcept
1980
{
12✔
1981
    return m_ident;
12✔
1982
}
12✔
1983

1984

1985
inline const ServerEndpoint& ClientImpl::Connection::get_server_endpoint() const noexcept
1986
{
2,762✔
1987
    return m_server_endpoint;
2,762✔
1988
}
2,762✔
1989

1990
inline void ClientImpl::Connection::update_connect_info(const std::string& http_request_path_prefix,
1991
                                                        const std::string& signed_access_token)
1992
{
10,240✔
1993
    m_http_request_path_prefix = http_request_path_prefix; // Throws (copy)
10,240✔
1994
    m_signed_access_token = signed_access_token;           // Throws (copy)
10,240✔
1995
}
10,240✔
1996

1997

1998
void ClientImpl::Connection::resume_active_sessions()
1999
{
1,964✔
2000
    auto handler = [=](ClientImpl::Session& sess) {
3,924✔
2001
        sess.cancel_resumption_delay(); // Throws
3,924✔
2002
    };
3,924✔
2003
    for_each_active_session(std::move(handler)); // Throws
1,964✔
2004
}
1,964✔
2005

2006
void ClientImpl::Connection::on_idle()
2007
{
2,764✔
2008
    logger.debug(util::LogCategory::session, "Destroying connection object");
2,764✔
2009
    ClientImpl& client = get_client();
2,764✔
2010
    client.remove_connection(*this);
2,764✔
2011
    // NOTE: This connection object is now destroyed!
2012
}
2,764✔
2013

2014

2015
std::string ClientImpl::Connection::get_http_request_path() const
2016
{
3,776✔
2017
    using namespace std::string_view_literals;
3,776✔
2018
    const auto param = m_http_request_path_prefix.find('?') == std::string::npos ? "?baas_at="sv : "&baas_at="sv;
3,776✔
2019

2020
    std::string path;
3,776✔
2021
    path.reserve(m_http_request_path_prefix.size() + param.size() + m_signed_access_token.size());
3,776✔
2022
    path += m_http_request_path_prefix;
3,776✔
2023
    path += param;
3,776✔
2024
    path += m_signed_access_token;
3,776✔
2025

2026
    return path;
3,776✔
2027
}
3,776✔
2028

2029

2030
std::string ClientImpl::Connection::make_logger_prefix(connection_ident_type ident)
2031
{
2,774✔
2032
    return util::format("Connection[%1] ", ident);
2,774✔
2033
}
2,774✔
2034

2035

2036
void ClientImpl::Connection::report_connection_state_change(ConnectionState state,
2037
                                                            std::optional<SessionErrorInfo> error_info)
2038
{
11,118✔
2039
    if (m_force_closed) {
11,118✔
2040
        return;
2,406✔
2041
    }
2,406✔
2042
    auto handler = [=](ClientImpl::Session& sess) {
11,886✔
2043
        SessionImpl& sess_2 = static_cast<SessionImpl&>(sess);
11,886✔
2044
        sess_2.on_connection_state_changed(state, error_info); // Throws
11,886✔
2045
    };
11,886✔
2046
    for_each_active_session(std::move(handler)); // Throws
8,712✔
2047
}
8,712✔
2048

2049

2050
Client::Client(Config config)
2051
    : m_impl{new ClientImpl{std::move(config)}} // Throws
4,890✔
2052
{
9,918✔
2053
}
9,918✔
2054

2055

2056
Client::Client(Client&& client) noexcept
2057
    : m_impl{std::move(client.m_impl)}
2058
{
×
2059
}
×
2060

2061

2062
Client::~Client() noexcept {}
9,918✔
2063

2064

2065
void Client::shutdown() noexcept
2066
{
10,000✔
2067
    m_impl->shutdown();
10,000✔
2068
}
10,000✔
2069

2070
void Client::shutdown_and_wait()
2071
{
768✔
2072
    m_impl->shutdown_and_wait();
768✔
2073
}
768✔
2074

2075
void Client::cancel_reconnect_delay()
2076
{
1,968✔
2077
    m_impl->cancel_reconnect_delay();
1,968✔
2078
}
1,968✔
2079

2080
void Client::voluntary_disconnect_all_connections()
2081
{
12✔
2082
    m_impl->voluntary_disconnect_all_connections();
12✔
2083
}
12✔
2084

2085
bool Client::wait_for_session_terminations_or_client_stopped()
2086
{
9,488✔
2087
    return m_impl->wait_for_session_terminations_or_client_stopped();
9,488✔
2088
}
9,488✔
2089

2090
util::Future<void> Client::notify_session_terminated()
2091
{
56✔
2092
    return m_impl->notify_session_terminated();
56✔
2093
}
56✔
2094

2095
bool Client::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
2096
                                  port_type& port, std::string& path) const
2097
{
4,016✔
2098
    return m_impl->decompose_server_url(url, protocol, address, port, path); // Throws
4,016✔
2099
}
4,016✔
2100

2101

2102
Session::Session(Client& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
2103
                 std::shared_ptr<MigrationStore> migration_store, Config&& config)
2104
{
10,104✔
2105
    m_impl = new SessionWrapper{*client.m_impl, std::move(db), std::move(flx_sub_store), std::move(migration_store),
10,104✔
2106
                                std::move(config)}; // Throws
10,104✔
2107
}
10,104✔
2108

2109

2110
void Session::nonsync_transact_notify(version_type new_version)
2111
{
17,722✔
2112
    m_impl->on_commit(new_version); // Throws
17,722✔
2113
}
17,722✔
2114

2115

2116
void Session::cancel_reconnect_delay()
2117
{
20✔
2118
    m_impl->cancel_reconnect_delay(); // Throws
20✔
2119
}
20✔
2120

2121

2122
void Session::async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler handler)
2123
{
4,856✔
2124
    m_impl->async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws
4,856✔
2125
}
4,856✔
2126

2127

2128
bool Session::wait_for_upload_complete_or_client_stopped()
2129
{
12,900✔
2130
    return m_impl->wait_for_upload_complete_or_client_stopped(); // Throws
12,900✔
2131
}
12,900✔
2132

2133

2134
bool Session::wait_for_download_complete_or_client_stopped()
2135
{
9,988✔
2136
    return m_impl->wait_for_download_complete_or_client_stopped(); // Throws
9,988✔
2137
}
9,988✔
2138

2139

2140
void Session::refresh(std::string_view signed_access_token)
2141
{
216✔
2142
    m_impl->refresh(signed_access_token); // Throws
216✔
2143
}
216✔
2144

2145

2146
void Session::abandon() noexcept
2147
{
10,104✔
2148
    REALM_ASSERT(m_impl);
10,104✔
2149
    // Reabsorb the ownership assigned to the applications naked pointer by
2150
    // Session constructor
2151
    util::bind_ptr<SessionWrapper> wrapper{m_impl, util::bind_ptr_base::adopt_tag{}};
10,104✔
2152
    SessionWrapper::abandon(std::move(wrapper));
10,104✔
2153
}
10,104✔
2154

2155
util::Future<std::string> Session::send_test_command(std::string body)
2156
{
60✔
2157
    return m_impl->send_test_command(std::move(body));
60✔
2158
}
60✔
2159

2160
std::string Session::get_appservices_connection_id()
2161
{
72✔
2162
    return m_impl->get_appservices_connection_id();
72✔
2163
}
72✔
2164

2165
std::ostream& operator<<(std::ostream& os, ProxyConfig::Type proxyType)
2166
{
×
2167
    switch (proxyType) {
×
2168
        case ProxyConfig::Type::HTTP:
×
2169
            return os << "HTTP";
×
2170
        case ProxyConfig::Type::HTTPS:
×
2171
            return os << "HTTPS";
×
2172
    }
×
2173
    REALM_TERMINATE("Invalid Proxy Type object.");
2174
}
×
2175

2176
} // namespace realm::sync
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