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

realm / realm-core / 2425

17 Jun 2024 06:46PM UTC coverage: 90.961% (-0.02%) from 90.98%
2425

push

Evergreen

web-flow
New changelog section to prepare for vNext (#7817)

Co-authored-by: ironage <2826060+ironage@users.noreply.github.com>

102170 of 180444 branches covered (56.62%)

214750 of 236090 relevant lines covered (90.96%)

5682786.14 hits per line

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

91.78
/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,828✔
257
    return !m_back;
19,828✔
258
}
19,828✔
259

260

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

268

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

279

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

288

289
inline bool SessionWrapperStack::erase(SessionWrapper* w) noexcept
290
{
10,122✔
291
    SessionWrapper** p = &m_back;
10,122✔
292
    while (*p && *p != w) {
10,254✔
293
        p = &(*p)->m_next;
132✔
294
    }
132✔
295
    if (!*p) {
10,122✔
296
        return false;
10,054✔
297
    }
10,054✔
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,122✔
302

303

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

309

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

312
ClientImpl::~ClientImpl()
313
{
9,926✔
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,926✔
318
    // Session wrappers are removed from m_unactualized_session_wrappers as they
319
    // are abandoned.
320
    REALM_ASSERT(m_stopped);
9,926✔
321
    REALM_ASSERT(m_unactualized_session_wrappers.empty());
9,926✔
322
    REALM_ASSERT(m_abandoned_session_wrappers.empty());
9,926✔
323
}
9,926✔
324

325

326
void ClientImpl::cancel_reconnect_delay()
327
{
1,912✔
328
    // Thread safety required
329
    post([this] {
1,912✔
330
        for (auto& p : m_server_slots) {
1,912✔
331
            ServerSlot& slot = p.second;
1,912✔
332
            if (m_one_connection_per_session) {
1,912✔
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,912✔
341
                REALM_ASSERT(slot.alt_connections.empty());
1,912✔
342
                if (slot.connection) {
1,912✔
343
                    ClientImpl::Connection& conn = *slot.connection;
1,908✔
344
                    conn.resume_active_sessions(); // Throws
1,908✔
345
                    conn.cancel_reconnect_delay(); // Throws
1,908✔
346
                }
1,908✔
347
                else {
4✔
348
                    slot.reconnect_info.reset();
4✔
349
                }
4✔
350
            }
1,912✔
351
        }
1,912✔
352
    }); // Throws
1,912✔
353
}
1,912✔
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,528✔
389
    // Thread safety required
390

391
    {
9,528✔
392
        util::CheckedLockGuard lock{m_mutex};
9,528✔
393
        m_sessions_terminated = false;
9,528✔
394
    }
9,528✔
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,528✔
414
        {
9,528✔
415
            util::CheckedLockGuard lock{m_mutex};
9,528✔
416
            m_sessions_terminated = true;
9,528✔
417
        }
9,528✔
418
        m_wait_or_client_stopped_cond.notify_all();
9,528✔
419
    }); // Throws
9,528✔
420

421
    bool completion_condition_was_satisfied;
9,528✔
422
    {
9,528✔
423
        util::CheckedUniqueLock lock{m_mutex};
9,528✔
424
        m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_mutex) {
19,040✔
425
            return m_sessions_terminated || m_stopped;
19,040✔
426
        });
19,040✔
427
        completion_condition_was_satisfied = !m_stopped;
9,528✔
428
    }
9,528✔
429
    return completion_condition_was_satisfied;
9,528✔
430
}
9,528✔
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,926✔
452
    post([this](Status status) {
9,926✔
453
        REALM_ASSERT(status.is_ok());
9,914✔
454
        drain_connections();
9,914✔
455
    });
9,914✔
456
}
9,926✔
457

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

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

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

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

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

487

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

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

506

507
void ClientImpl::register_abandoned_session_wrapper(util::bind_ptr<SessionWrapper> wrapper) noexcept
508
{
10,126✔
509
    // Thread safety required.
510
    {
10,126✔
511
        util::CheckedLockGuard lock{m_mutex};
10,126✔
512
        REALM_ASSERT(m_actualize_and_finalize);
10,126✔
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,126✔
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,122✔
523
            wrapper->finalize_before_actualization();
68✔
524
            return;
68✔
525
        }
68✔
526
        m_abandoned_session_wrappers.push(std::move(wrapper));
10,054✔
527
    }
10,054✔
528
    m_actualize_and_finalize->trigger();
×
529
}
10,054✔
530

531

532
// Must be called from the event loop thread.
533
void ClientImpl::actualize_and_finalize_session_wrappers()
534
{
14,356✔
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,460✔
547
        bool finalize = true;
34,452✔
548
        bool stopped;
34,452✔
549
        util::bind_ptr<SessionWrapper> wrapper;
34,452✔
550
        {
34,452✔
551
            util::CheckedLockGuard lock{m_mutex};
34,452✔
552
            wrapper = m_abandoned_session_wrappers.pop();
34,452✔
553
            if (!wrapper) {
34,452✔
554
                wrapper = m_unactualized_session_wrappers.pop();
24,412✔
555
                finalize = false;
24,412✔
556
            }
24,412✔
557
            stopped = m_stopped;
34,452✔
558
        }
34,452✔
559
        if (!wrapper)
34,452✔
560
            break;
14,348✔
561
        if (finalize)
20,104✔
562
            wrapper->finalize(); // Throws
10,042✔
563
        else if (stopped)
10,062✔
564
            wrapper->finalize_before_actualization();
4✔
565
        else
10,058✔
566
            wrapper->actualize(); // Throws
10,058✔
567
    }
20,104✔
568
}
14,356✔
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,050✔
579
    auto&& [server_slot_it, inserted] =
10,050✔
580
        m_server_slots.try_emplace(endpoint, ReconnectInfo(m_reconnect_mode, m_reconnect_backoff_info, get_random()));
10,050✔
581
    ServerSlot& server_slot = server_slot_it->second; // Throws
10,050✔
582

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

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

613

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

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

646

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

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

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

666

667
const std::string& SessionImpl::get_virt_path() const noexcept
668
{
7,160✔
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,160!
671
    return m_wrapper.m_virt_path;
7,160✔
672
}
7,160✔
673

674
const std::string& SessionImpl::get_realm_path() const noexcept
675
{
10,346✔
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,346✔
678
    return m_wrapper.m_db->get_path();
10,346✔
679
}
10,346✔
680

681
DBRef SessionImpl::get_db() const noexcept
682
{
26,028✔
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,028✔
685
    return m_wrapper.m_db;
26,028✔
686
}
26,028✔
687

688
ClientReplication& SessionImpl::get_repl() const noexcept
689
{
119,544✔
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,544✔
692
    return m_wrapper.get_replication();
119,544✔
693
}
119,544✔
694

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

700
std::optional<ClientReset>& SessionImpl::get_client_reset_config() noexcept
701
{
17,418✔
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);
17,418✔
704
    return m_wrapper.m_client_reset_config;
17,418✔
705
}
17,418✔
706

707
SessionReason SessionImpl::get_session_reason() noexcept
708
{
1,482✔
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,482!
711
    return m_wrapper.m_session_reason;
1,482✔
712
}
1,482✔
713

714
uint64_t SessionImpl::get_schema_version() noexcept
715
{
1,482✔
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,482!
718
    return m_wrapper.m_schema_version;
1,482✔
719
}
1,482✔
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,142✔
724
    // Ignore the call if the session is not active
725
    if (m_state != State::Active) {
45,142✔
726
        return;
×
727
    }
×
728

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

751

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

760

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

769

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

778

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

787
void SessionImpl::handle_pending_client_reset_acknowledgement()
788
{
10,346✔
789
    // Ignore the call if the session is not active
790
    if (m_state == State::Active) {
10,346✔
791
        m_wrapper.handle_pending_client_reset_acknowledgement();
10,346✔
792
    }
10,346✔
793
}
10,346✔
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,306✔
806
    // Ignore the call if the session is not active
807
    if (m_state != State::Active) {
47,306✔
808
        return false;
×
809
    }
×
810

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

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

821
    bool new_batch = false;
2,164✔
822
    try {
2,164✔
823
        bootstrap_store->add_batch(query_version, std::move(maybe_progress), received_changesets, &new_batch);
2,164✔
824
    }
2,164✔
825
    catch (const LogicError& ex) {
2,164✔
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,164✔
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,164✔
843
                                       batch_state, received_changesets.size());
2,164✔
844
    if (hook_action == SyncClientHookAction::EarlyReturn) {
2,164✔
845
        return true;
12✔
846
    }
12✔
847
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
2,152✔
848

849
    if (batch_state == DownloadBatchState::MoreToCome) {
2,152✔
850
        notify_download_progress(bootstrap_store->pending_stats().pending_changeset_bytes);
196✔
851
        return true;
196✔
852
    }
196✔
853
    else {
1,956✔
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,956✔
860
    }
1,956✔
861

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

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

875

876
void SessionImpl::process_pending_flx_bootstrap()
877
{
12,006✔
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) {
12,006✔
880
        return;
8,540✔
881
    }
8,540✔
882
    // Should never be called if session is not active
883
    REALM_ASSERT_EX(m_state == SessionImpl::Active, m_state);
3,466✔
884
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
3,466✔
885
    if (!bootstrap_store->has_pending()) {
3,466✔
886
        return;
1,490✔
887
    }
1,490✔
888

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

900
    // Used to commit each batch after it was transformed.
901
    TransactionRef transact = get_db()->start_write();
1,976✔
902
    while (bootstrap_store->has_pending()) {
4,112✔
903
        auto start_time = std::chrono::steady_clock::now();
2,148✔
904
        auto pending_batch = bootstrap_store->peek_pending(m_wrapper.m_flx_bootstrap_batch_size_bytes);
2,148✔
905
        if (!pending_batch.progress) {
2,148✔
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,140✔
915
            pending_batch.remaining_changesets > 0 ? DownloadBatchState::MoreToCome : DownloadBatchState::LastInBatch;
2,140✔
916
        uint64_t downloadable_bytes = 0;
2,140✔
917
        query_version = pending_batch.query_version;
2,140✔
918
        bool simulate_integration_error =
2,140✔
919
            (m_wrapper.m_simulate_integration_error && !pending_batch.changesets.empty());
2,140✔
920
        if (simulate_integration_error) {
2,140✔
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,136✔
925
                        batch_state, pending_batch.changesets.size());
2,136✔
926

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

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

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

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

951
    on_changesets_integrated(new_version.realm_version, progress, changesets_processed > 0);
1,964✔
952
    auto action = call_debug_hook(SyncClientHookEvent::BootstrapProcessed, progress, query_version,
1,964✔
953
                                  DownloadBatchState::LastInBatch, changesets_processed);
1,964✔
954
    // NoAction/EarlyReturn are both valid no-op actions to take here.
955
    REALM_ASSERT_EX(action == SyncClientHookAction::NoAction || action == SyncClientHookAction::EarlyReturn, action);
1,964✔
956
}
1,964✔
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
{
2,000✔
968
    // Ignore the call if the session is not active
969
    if (m_state == State::Active) {
2,000✔
970
        m_wrapper.on_flx_sync_progress(version, batch_state);
2,000✔
971
    }
2,000✔
972
}
2,000✔
973

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

981
MigrationStore* SessionImpl::get_migration_store()
982
{
67,416✔
983
    // Should never be called if session is not active
984
    REALM_ASSERT_EX(m_state == State::Active, m_state);
67,416✔
985
    return m_wrapper.get_migration_store();
67,416✔
986
}
67,416✔
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,492✔
998
    // Should never be called if session is not active
999
    REALM_ASSERT_EX(m_state == State::Active, m_state);
2,492✔
1000

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

1010
    auto action = m_wrapper.m_debug_hook(data);
2,468✔
1011
    switch (action) {
2,468✔
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,424✔
1025
            return action;
2,424✔
1026
    }
2,468✔
1027
}
2,468✔
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,828✔
1033
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
119,828✔
1034
        return SyncClientHookAction::NoAction;
117,534✔
1035
    }
117,534✔
1036
    if (REALM_UNLIKELY(m_state != State::Active)) {
2,294✔
1037
        return SyncClientHookAction::NoAction;
×
1038
    }
×
1039

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

1047
    return call_debug_hook(data);
2,294✔
1048
}
2,294✔
1049

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

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

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

1070
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event)
1071
{
18,988✔
1072
    return call_debug_hook(event, m_progress, m_last_sent_flx_query_version, DownloadBatchState::SteadyState, 0);
18,988✔
1073
}
18,988✔
1074

1075
bool SessionImpl::is_steady_state_download_message(DownloadBatchState batch_state, int64_t query_version)
1076
{
94,628✔
1077
    // Should never be called if session is not active
1078
    REALM_ASSERT_EX(m_state == State::Active, m_state);
94,628✔
1079
    if (batch_state == DownloadBatchState::SteadyState) {
94,628✔
1080
        return true;
45,142✔
1081
    }
45,142✔
1082

1083
    if (!m_is_flx_sync_session) {
49,486✔
1084
        return true;
43,820✔
1085
    }
43,820✔
1086

1087
    // If this is a steady state DOWNLOAD, no need for special handling.
1088
    if (batch_state == DownloadBatchState::LastInBatch && query_version == m_wrapper.m_flx_active_version) {
5,666✔
1089
        return true;
1,330✔
1090
    }
1,330✔
1091

1092
    return false;
4,336✔
1093
}
5,666✔
1094

1095
void SessionImpl::init_progress_handler()
1096
{
10,346✔
1097
    if (m_state != State::Unactivated && m_state != State::Active)
10,346✔
1098
        return;
×
1099

1100
    m_wrapper.init_progress_handler();
10,346✔
1101
}
10,346✔
1102

1103
void SessionImpl::enable_progress_notifications()
1104
{
45,682✔
1105
    m_wrapper.m_reliable_download_progress = true;
45,682✔
1106
}
45,682✔
1107

1108
void SessionImpl::notify_upload_progress()
1109
{
33,656✔
1110
    if (m_state != State::Active)
33,656✔
1111
        return;
×
1112

1113
    m_wrapper.on_upload_progress();
33,656✔
1114
}
33,656✔
1115

1116
void SessionImpl::update_download_estimate(double download_estimate)
1117
{
3,490✔
1118
    if (m_state != State::Active)
3,490✔
1119
        return;
×
1120

1121
    m_wrapper.m_download_estimate = download_estimate;
3,490✔
1122
}
3,490✔
1123

1124
void SessionImpl::notify_download_progress(const std::optional<uint64_t>& bootstrap_store_bytes)
1125
{
27,702✔
1126
    if (m_state != State::Active)
27,702✔
1127
        return;
×
1128

1129
    m_wrapper.on_download_progress(bootstrap_store_bytes); // Throws
27,702✔
1130
}
27,702✔
1131

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

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

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

1160
        auto id = ++m_last_pending_test_command_ident;
52✔
1161
        m_pending_test_commands.push_back(PendingTestCommand{id, std::move(body), std::move(promise)});
52✔
1162
        ensure_enlisted_to_send();
52✔
1163
    });
52✔
1164

1165
    return std::move(pf.future);
52✔
1166
}
60✔
1167

1168
// ################ SessionWrapper ################
1169

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

1208
    // SessionWrapper begins at +1 retain count because Client retains and
1209
    // releases it while performing async operations, and these need to not
1210
    // take it to 0 or it could be deleted before the caller can retain it.
1211
    bind_ptr();
10,126✔
1212
    m_client.register_unactualized_session_wrapper(this);
10,126✔
1213
}
10,126✔
1214

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

1227

1228
inline ClientReplication& SessionWrapper::get_replication() noexcept
1229
{
119,544✔
1230
    REALM_ASSERT(m_db);
119,544✔
1231
    return static_cast<ClientReplication&>(*m_replication);
119,544✔
1232
}
119,544✔
1233

1234

1235
inline ClientImpl& SessionWrapper::get_client() noexcept
1236
{
×
1237
    return m_client;
×
1238
}
×
1239

1240
bool SessionWrapper::has_flx_subscription_store() const
1241
{
2,000✔
1242
    return static_cast<bool>(m_flx_subscription_store);
2,000✔
1243
}
2,000✔
1244

1245
void SessionWrapper::on_flx_sync_error(int64_t version, std::string_view err_msg)
1246
{
20✔
1247
    REALM_ASSERT(!m_finalized);
20✔
1248
    get_flx_subscription_store()->update_state(version, SubscriptionSet::State::Error, err_msg);
20✔
1249
}
20✔
1250

1251
void SessionWrapper::on_flx_sync_version_complete(int64_t version)
1252
{
2,252✔
1253
    REALM_ASSERT(!m_finalized);
2,252✔
1254
    m_flx_last_seen_version = version;
2,252✔
1255
    m_flx_active_version = version;
2,252✔
1256
}
2,252✔
1257

1258
void SessionWrapper::on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state)
1259
{
2,000✔
1260
    if (!has_flx_subscription_store()) {
2,000✔
1261
        return;
×
1262
    }
×
1263
    REALM_ASSERT(!m_finalized);
2,000✔
1264
    REALM_ASSERT(new_version >= m_flx_last_seen_version);
2,000✔
1265
    REALM_ASSERT(new_version >= m_flx_active_version);
2,000✔
1266
    REALM_ASSERT(batch_state != DownloadBatchState::SteadyState);
2,000✔
1267

1268
    SubscriptionSet::State new_state = SubscriptionSet::State::Uncommitted; // Initialize to make compiler happy
2,000✔
1269

1270
    switch (batch_state) {
2,000✔
1271
        case DownloadBatchState::SteadyState:
✔
1272
            // Cannot be called with this value.
1273
            REALM_UNREACHABLE();
1274
        case DownloadBatchState::LastInBatch:
1,952✔
1275
            if (m_flx_active_version == new_version) {
1,952✔
1276
                return;
×
1277
            }
×
1278
            on_flx_sync_version_complete(new_version);
1,952✔
1279
            if (new_version == 0) {
1,952✔
1280
                new_state = SubscriptionSet::State::Complete;
924✔
1281
            }
924✔
1282
            else {
1,028✔
1283
                new_state = SubscriptionSet::State::AwaitingMark;
1,028✔
1284
                m_flx_pending_mark_version = new_version;
1,028✔
1285
            }
1,028✔
1286
            break;
1,952✔
1287
        case DownloadBatchState::MoreToCome:
48✔
1288
            if (m_flx_last_seen_version == new_version) {
48✔
1289
                return;
×
1290
            }
×
1291

1292
            m_flx_last_seen_version = new_version;
48✔
1293
            new_state = SubscriptionSet::State::Bootstrapping;
48✔
1294
            break;
48✔
1295
    }
2,000✔
1296

1297
    get_flx_subscription_store()->update_state(new_version, new_state);
2,000✔
1298
}
2,000✔
1299

1300
SubscriptionStore* SessionWrapper::get_flx_subscription_store()
1301
{
20,364✔
1302
    REALM_ASSERT(!m_finalized);
20,364✔
1303
    return m_flx_subscription_store.get();
20,364✔
1304
}
20,364✔
1305

1306
PendingBootstrapStore* SessionWrapper::get_flx_pending_bootstrap_store()
1307
{
5,630✔
1308
    REALM_ASSERT(!m_finalized);
5,630✔
1309
    return m_flx_pending_bootstrap_store.get();
5,630✔
1310
}
5,630✔
1311

1312
MigrationStore* SessionWrapper::get_migration_store()
1313
{
67,416✔
1314
    REALM_ASSERT(!m_finalized);
67,416✔
1315
    return m_migration_store.get();
67,416✔
1316
}
67,416✔
1317

1318
inline bool SessionWrapper::mark_abandoned()
1319
{
10,126✔
1320
    REALM_ASSERT(!m_abandoned);
10,126✔
1321
    m_abandoned = true;
10,126✔
1322
    return m_finalized;
10,126✔
1323
}
10,126✔
1324

1325

1326
void SessionWrapper::on_commit(version_type new_version)
1327
{
113,834✔
1328
    // Thread safety required
1329
    m_client.post([self = util::bind_ptr{this}, new_version] {
113,834✔
1330
        REALM_ASSERT(self->m_actualized);
113,832✔
1331
        if (REALM_UNLIKELY(!self->m_sess))
113,832✔
1332
            return; // Already finalized
852✔
1333
        SessionImpl& sess = *self->m_sess;
112,980✔
1334
        sess.recognize_sync_version(new_version);                           // Throws
112,980✔
1335
        self->on_upload_progress(/* only_if_new_uploadable_data = */ true); // Throws
112,980✔
1336
    });
112,980✔
1337
}
113,834✔
1338

1339

1340
void SessionWrapper::cancel_reconnect_delay()
1341
{
28✔
1342
    // Thread safety required
1343

1344
    m_client.post([self = util::bind_ptr{this}] {
28✔
1345
        REALM_ASSERT(self->m_actualized);
28✔
1346
        if (REALM_UNLIKELY(self->m_closed)) {
28✔
1347
            return;
×
1348
        }
×
1349

1350
        if (REALM_UNLIKELY(!self->m_sess))
28✔
1351
            return; // Already finalized
×
1352
        SessionImpl& sess = *self->m_sess;
28✔
1353
        sess.cancel_resumption_delay(); // Throws
28✔
1354
        ClientImpl::Connection& conn = sess.get_connection();
28✔
1355
        conn.cancel_reconnect_delay(); // Throws
28✔
1356
    });                                // Throws
28✔
1357
}
28✔
1358

1359
void SessionWrapper::async_wait_for(bool upload_completion, bool download_completion,
1360
                                    WaitOperCompletionHandler handler)
1361
{
5,206✔
1362
    REALM_ASSERT(upload_completion || download_completion);
5,206✔
1363

1364
    m_client.post([self = util::bind_ptr{this}, handler = std::move(handler), upload_completion,
5,206✔
1365
                   download_completion]() mutable {
5,206✔
1366
        REALM_ASSERT(self->m_actualized);
5,206✔
1367
        if (REALM_UNLIKELY(!self->m_sess)) {
5,206✔
1368
            // Already finalized
1369
            handler({ErrorCodes::OperationAborted, "Session finalized before callback could run"}); // Throws
104✔
1370
            return;
104✔
1371
        }
104✔
1372
        if (upload_completion) {
5,102✔
1373
            if (download_completion) {
2,608✔
1374
                // Wait for upload and download completion
1375
                self->m_sync_completion_handlers.push_back(std::move(handler)); // Throws
318✔
1376
            }
318✔
1377
            else {
2,290✔
1378
                // Wait for upload completion only
1379
                self->m_upload_completion_handlers.push_back(std::move(handler)); // Throws
2,290✔
1380
            }
2,290✔
1381
        }
2,608✔
1382
        else {
2,494✔
1383
            // Wait for download completion only
1384
            self->m_download_completion_handlers.push_back(std::move(handler)); // Throws
2,494✔
1385
        }
2,494✔
1386
        SessionImpl& sess = *self->m_sess;
5,102✔
1387
        if (upload_completion)
5,102✔
1388
            sess.request_upload_completion_notification(); // Throws
2,608✔
1389
        if (download_completion)
5,102✔
1390
            sess.request_download_completion_notification(); // Throws
2,812✔
1391
    });                                                      // Throws
5,102✔
1392
}
5,206✔
1393

1394

1395
bool SessionWrapper::wait_for_upload_complete_or_client_stopped()
1396
{
12,900✔
1397
    // Thread safety required
1398
    REALM_ASSERT(!m_abandoned);
12,900✔
1399

1400
    std::int_fast64_t target_mark;
12,900✔
1401
    {
12,900✔
1402
        util::CheckedLockGuard lock{m_client.m_mutex};
12,900✔
1403
        target_mark = ++m_target_upload_mark;
12,900✔
1404
    }
12,900✔
1405

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

1421
    bool completion_condition_was_satisfied;
12,900✔
1422
    {
12,900✔
1423
        util::CheckedUniqueLock lock{m_client.m_mutex};
12,900✔
1424
        m_client.m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_client.m_mutex) {
32,928✔
1425
            return m_reached_upload_mark >= target_mark || m_client.m_stopped;
32,928✔
1426
        });
32,928✔
1427
        completion_condition_was_satisfied = !m_client.m_stopped;
12,900✔
1428
    }
12,900✔
1429
    return completion_condition_was_satisfied;
12,900✔
1430
}
12,900✔
1431

1432

1433
bool SessionWrapper::wait_for_download_complete_or_client_stopped()
1434
{
9,988✔
1435
    // Thread safety required
1436
    REALM_ASSERT(!m_abandoned);
9,988✔
1437

1438
    std::int_fast64_t target_mark;
9,988✔
1439
    {
9,988✔
1440
        util::CheckedLockGuard lock{m_client.m_mutex};
9,988✔
1441
        target_mark = ++m_target_download_mark;
9,988✔
1442
    }
9,988✔
1443

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

1459
    bool completion_condition_was_satisfied;
9,988✔
1460
    {
9,988✔
1461
        util::CheckedUniqueLock lock{m_client.m_mutex};
9,988✔
1462
        m_client.m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_client.m_mutex) {
20,280✔
1463
            return m_reached_download_mark >= target_mark || m_client.m_stopped;
20,280✔
1464
        });
20,280✔
1465
        completion_condition_was_satisfied = !m_client.m_stopped;
9,988✔
1466
    }
9,988✔
1467
    return completion_condition_was_satisfied;
9,988✔
1468
}
9,988✔
1469

1470

1471
void SessionWrapper::refresh(std::string_view signed_access_token)
1472
{
216✔
1473
    // Thread safety required
1474
    REALM_ASSERT(!m_abandoned);
216✔
1475

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

1490

1491
void SessionWrapper::abandon(util::bind_ptr<SessionWrapper> wrapper) noexcept
1492
{
10,126✔
1493
    ClientImpl& client = wrapper->m_client;
10,126✔
1494
    client.register_abandoned_session_wrapper(std::move(wrapper));
10,126✔
1495
}
10,126✔
1496

1497

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

1509
    m_actualized = true;
10,050✔
1510

1511
    ScopeExitFail close_on_error([&]() noexcept {
10,050✔
1512
        m_closed = true;
4✔
1513
    });
4✔
1514

1515
    m_db->claim_sync_agent();
10,050✔
1516
    m_db->add_commit_listener(this);
10,050✔
1517
    ScopeExitFail remove_commit_listener([&]() noexcept {
10,050✔
1518
        m_db->remove_commit_listener(this);
×
1519
    });
×
1520

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

1533
    // FIXME: This only makes sense when each session uses a separate connection.
1534
    conn.update_connect_info(m_http_request_path_prefix, m_signed_access_token);    // Throws
10,050✔
1535
    std::unique_ptr<SessionImpl> sess = std::make_unique<SessionImpl>(*this, conn); // Throws
10,050✔
1536
    if (m_sync_mode == SyncServerMode::FLX) {
10,050✔
1537
        m_flx_pending_bootstrap_store = std::make_unique<PendingBootstrapStore>(m_db, sess->logger);
1,510✔
1538
    }
1,510✔
1539

1540
    sess->logger.info("Binding '%1' to '%2'", m_db->get_path(), m_virt_path); // Throws
10,050✔
1541
    m_sess = sess.get();
10,050✔
1542
    ScopeExitFail clear_sess([&]() noexcept {
10,050✔
1543
        m_sess = nullptr;
×
1544
    });
×
1545
    conn.activate_session(std::move(sess)); // Throws
10,050✔
1546

1547
    // Initialize the variables relying on the bootstrap store from the event loop to guarantee that a previous
1548
    // session cannot change the state of the bootstrap store at the same time.
1549
    update_subscription_version_info();
10,050✔
1550

1551
    if (was_created)
10,050✔
1552
        conn.activate(); // Throws
2,786✔
1553

1554
    if (m_connection_state_change_listener) {
10,050✔
1555
        ConnectionState state = conn.get_state();
10,042✔
1556
        if (state != ConnectionState::disconnected) {
10,042✔
1557
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,084✔
1558
            if (state == ConnectionState::connected)
7,084✔
1559
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
6,916✔
1560
        }
7,084✔
1561
    }
10,042✔
1562

1563
    if (!m_client_reset_config)
10,050✔
1564
        on_upload_progress(/* only_if_new_uploadable_data = */ true); // Throws
9,672✔
1565
}
10,050✔
1566

1567
void SessionWrapper::force_close()
1568
{
10,142✔
1569
    if (m_closed) {
10,142✔
1570
        return;
104✔
1571
    }
104✔
1572
    REALM_ASSERT(m_actualized);
10,038✔
1573
    REALM_ASSERT(m_sess);
10,038✔
1574
    m_closed = true;
10,038✔
1575

1576
    ClientImpl::Connection& conn = m_sess->get_connection();
10,038✔
1577
    conn.initiate_session_deactivation(m_sess); // Throws
10,038✔
1578

1579
    // We need to keep the DB open until finalization, but we no longer want to
1580
    // know when commits are made
1581
    m_db->remove_commit_listener(this);
10,038✔
1582

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

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

1604
    force_close();
10,042✔
1605

1606
    m_finalized = true;
10,042✔
1607

1608
    // The Realm file can be closed now, as no access to the Realm file is
1609
    // supposed to happen on behalf of a session after initiation of
1610
    // deactivation.
1611
    m_db->release_sync_agent();
10,042✔
1612
    m_db = nullptr;
10,042✔
1613

1614
    // All outstanding wait operations must be canceled
1615
    while (!m_upload_completion_handlers.empty()) {
10,474✔
1616
        auto handler = std::move(m_upload_completion_handlers.back());
432✔
1617
        m_upload_completion_handlers.pop_back();
432✔
1618
        handler(
432✔
1619
            {ErrorCodes::OperationAborted, "Sync session is being finalized before upload was complete"}); // Throws
432✔
1620
    }
432✔
1621
    while (!m_download_completion_handlers.empty()) {
10,272✔
1622
        auto handler = std::move(m_download_completion_handlers.back());
230✔
1623
        m_download_completion_handlers.pop_back();
230✔
1624
        handler(
230✔
1625
            {ErrorCodes::OperationAborted, "Sync session is being finalized before download was complete"}); // Throws
230✔
1626
    }
230✔
1627
    while (!m_sync_completion_handlers.empty()) {
10,062✔
1628
        auto handler = std::move(m_sync_completion_handlers.back());
20✔
1629
        m_sync_completion_handlers.pop_back();
20✔
1630
        handler({ErrorCodes::OperationAborted, "Sync session is being finalized before sync was complete"}); // Throws
20✔
1631
    }
20✔
1632
}
10,042✔
1633

1634

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

1650
inline void SessionWrapper::on_upload_progress(bool only_if_new_uploadable_data)
1651
{
156,310✔
1652
    REALM_ASSERT(!m_finalized);
156,310✔
1653
    report_progress(/* is_download = */ false, only_if_new_uploadable_data); // Throws
156,310✔
1654
}
156,310✔
1655

1656
inline void SessionWrapper::on_download_progress(const std::optional<uint64_t>& bootstrap_store_bytes)
1657
{
27,702✔
1658
    REALM_ASSERT(!m_finalized);
27,702✔
1659
    m_bootstrap_store_bytes = bootstrap_store_bytes;
27,702✔
1660
    report_progress(/* is_download = */ true); // Throws
27,702✔
1661
}
27,702✔
1662

1663

1664
void SessionWrapper::on_upload_completion()
1665
{
14,802✔
1666
    REALM_ASSERT(!m_finalized);
14,802✔
1667
    while (!m_upload_completion_handlers.empty()) {
16,758✔
1668
        auto handler = std::move(m_upload_completion_handlers.back());
1,956✔
1669
        m_upload_completion_handlers.pop_back();
1,956✔
1670
        handler(Status::OK()); // Throws
1,956✔
1671
    }
1,956✔
1672
    while (!m_sync_completion_handlers.empty()) {
15,002✔
1673
        auto handler = std::move(m_sync_completion_handlers.back());
200✔
1674
        m_download_completion_handlers.push_back(std::move(handler)); // Throws
200✔
1675
        m_sync_completion_handlers.pop_back();
200✔
1676
    }
200✔
1677
    util::CheckedLockGuard lock{m_client.m_mutex};
14,802✔
1678
    if (m_staged_upload_mark > m_reached_upload_mark) {
14,802✔
1679
        m_reached_upload_mark = m_staged_upload_mark;
12,862✔
1680
        m_client.m_wait_or_client_stopped_cond.notify_all();
12,862✔
1681
    }
12,862✔
1682
}
14,802✔
1683

1684

1685
void SessionWrapper::on_download_completion()
1686
{
16,158✔
1687
    while (!m_download_completion_handlers.empty()) {
18,610✔
1688
        auto handler = std::move(m_download_completion_handlers.back());
2,452✔
1689
        m_download_completion_handlers.pop_back();
2,452✔
1690
        handler(Status::OK()); // Throws
2,452✔
1691
    }
2,452✔
1692
    while (!m_sync_completion_handlers.empty()) {
16,256✔
1693
        auto handler = std::move(m_sync_completion_handlers.back());
98✔
1694
        m_upload_completion_handlers.push_back(std::move(handler)); // Throws
98✔
1695
        m_sync_completion_handlers.pop_back();
98✔
1696
    }
98✔
1697

1698
    if (m_flx_subscription_store && m_flx_pending_mark_version != SubscriptionSet::EmptyVersion) {
16,158✔
1699
        m_sess->logger.debug("Marking query version %1 as complete after receiving MARK message",
900✔
1700
                             m_flx_pending_mark_version);
900✔
1701
        m_flx_subscription_store->update_state(m_flx_pending_mark_version, SubscriptionSet::State::Complete);
900✔
1702
        m_flx_pending_mark_version = SubscriptionSet::EmptyVersion;
900✔
1703
    }
900✔
1704

1705
    util::CheckedLockGuard lock{m_client.m_mutex};
16,158✔
1706
    if (m_staged_download_mark > m_reached_download_mark) {
16,158✔
1707
        m_reached_download_mark = m_staged_download_mark;
9,858✔
1708
        m_client.m_wait_or_client_stopped_cond.notify_all();
9,858✔
1709
    }
9,858✔
1710
}
16,158✔
1711

1712

1713
void SessionWrapper::on_suspended(const SessionErrorInfo& error_info)
1714
{
668✔
1715
    REALM_ASSERT(!m_finalized);
668✔
1716
    m_suspended = true;
668✔
1717
    if (m_connection_state_change_listener) {
668✔
1718
        m_connection_state_change_listener(ConnectionState::disconnected, error_info); // Throws
668✔
1719
    }
668✔
1720
}
668✔
1721

1722

1723
void SessionWrapper::on_resumed()
1724
{
60✔
1725
    REALM_ASSERT(!m_finalized);
60✔
1726
    m_suspended = false;
60✔
1727
    if (m_connection_state_change_listener) {
60✔
1728
        ClientImpl::Connection& conn = m_sess->get_connection();
60✔
1729
        if (conn.get_state() != ConnectionState::disconnected) {
60✔
1730
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
54✔
1731
            if (conn.get_state() == ConnectionState::connected)
54✔
1732
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
48✔
1733
        }
54✔
1734
    }
60✔
1735
}
60✔
1736

1737

1738
void SessionWrapper::on_connection_state_changed(ConnectionState state,
1739
                                                 const std::optional<SessionErrorInfo>& error_info)
1740
{
11,942✔
1741
    if (m_connection_state_change_listener && !m_suspended) {
11,942✔
1742
        m_connection_state_change_listener(state, error_info); // Throws
11,908✔
1743
    }
11,908✔
1744
}
11,942✔
1745

1746
void SessionWrapper::init_progress_handler()
1747
{
10,346✔
1748
    uint64_t unused = 0;
10,346✔
1749
    ClientHistory::get_upload_download_bytes(m_db.get(), m_reported_progress.final_downloaded, unused,
10,346✔
1750
                                             m_reported_progress.final_uploaded, unused, unused);
10,346✔
1751
}
10,346✔
1752

1753
void SessionWrapper::report_progress(bool is_download, bool only_if_new_uploadable_data)
1754
{
184,014✔
1755
    REALM_ASSERT(!m_finalized);
184,014✔
1756
    REALM_ASSERT(m_sess);
184,014✔
1757
    REALM_ASSERT(!(only_if_new_uploadable_data && is_download));
184,014✔
1758

1759
    if (!m_progress_handler)
184,014✔
1760
        return;
129,096✔
1761

1762
    // Ignore progress messages from before we first receive a DOWNLOAD message
1763
    if (!m_reliable_download_progress)
54,918✔
1764
        return;
27,754✔
1765

1766
    ReportedProgress p = m_reported_progress;
27,164✔
1767
    ClientHistory::get_upload_download_bytes(m_db.get(), p.downloaded, p.downloadable, p.uploaded, p.uploadable,
27,164✔
1768
                                             p.snapshot);
27,164✔
1769

1770
    // If this progress notification was triggered by a commit being made we
1771
    // only want to send it if the uploadable bytes has actually increased,
1772
    // and not if it was an empty commit.
1773
    if (only_if_new_uploadable_data && m_reported_progress.uploadable == p.uploadable)
27,164✔
1774
        return;
18,474✔
1775

1776
    // uploadable_bytes is uploaded + remaining to upload, while downloadable_bytes
1777
    // is only the remaining to download. This is confusing, so make them use
1778
    // the same units.
1779
    p.downloadable += p.downloaded;
8,690✔
1780

1781
    bool is_completed = false;
8,690✔
1782
    if (is_download) {
8,690✔
1783
        if (m_download_estimate)
3,394✔
1784
            is_completed = *m_download_estimate >= 1.0;
1,324✔
1785
        else
2,070✔
1786
            is_completed = p.downloaded == p.downloadable;
2,070✔
1787
    }
3,394✔
1788
    else {
5,296✔
1789
        is_completed = p.uploaded == p.uploadable;
5,296✔
1790
    }
5,296✔
1791

1792
    auto calculate_progress = [](uint64_t transferred, uint64_t transferable, uint64_t final_transferred) {
9,540✔
1793
        REALM_ASSERT_DEBUG_EX(final_transferred <= transferred, final_transferred, transferred, transferable);
9,540✔
1794
        REALM_ASSERT_DEBUG_EX(transferred <= transferable, final_transferred, transferred, transferable);
9,540✔
1795

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

1804
        double progress_estimate = 1.0;
9,540✔
1805
        if (final_transferred < transferable && transferred < transferable)
9,540✔
1806
            progress_estimate = (transferred - final_transferred) / double(transferable - final_transferred);
3,996✔
1807
        return progress_estimate;
9,540✔
1808
    };
9,540✔
1809

1810
    double upload_estimate = 1.0, download_estimate = 1.0;
8,690✔
1811

1812
    // calculate estimate for both download/upload since the progress is reported all at once
1813
    if (!is_completed || is_download)
8,690✔
1814
        upload_estimate = calculate_progress(p.uploaded, p.uploadable, p.final_uploaded);
5,868✔
1815

1816
    // download estimate only known for flx
1817
    if (m_download_estimate) {
8,690✔
1818
        download_estimate = *m_download_estimate;
2,978✔
1819

1820
        // ... bootstrap store bytes should be null after initial sync when every changeset integrated immediately
1821
        if (m_bootstrap_store_bytes)
2,978✔
1822
            p.downloaded += *m_bootstrap_store_bytes;
196✔
1823

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

1838
    if (is_completed) {
8,690✔
1839
        if (is_download)
5,986✔
1840
            p.final_downloaded = p.downloaded;
3,166✔
1841
        else
2,820✔
1842
            p.final_uploaded = p.uploaded;
2,820✔
1843
    }
5,986✔
1844

1845
    m_reported_progress = p;
8,690✔
1846

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

1861
    m_progress_handler(p.downloaded, p.downloadable, p.uploaded, p.uploadable, p.snapshot, download_estimate,
8,690✔
1862
                       upload_estimate, m_flx_last_seen_version);
8,690✔
1863
}
8,690✔
1864

1865
util::Future<std::string> SessionWrapper::send_test_command(std::string body)
1866
{
60✔
1867
    if (!m_sess) {
60✔
1868
        return Status{ErrorCodes::RuntimeError, "session must be activated to send a test command"};
×
1869
    }
×
1870

1871
    return m_sess->send_test_command(std::move(body));
60✔
1872
}
60✔
1873

1874
void SessionWrapper::handle_pending_client_reset_acknowledgement()
1875
{
10,346✔
1876
    REALM_ASSERT(!m_finalized);
10,346✔
1877

1878
    auto has_pending_reset = PendingResetStore::has_pending_reset(m_db->start_frozen());
10,346✔
1879
    if (!has_pending_reset) {
10,346✔
1880
        return; // nothing to do
10,018✔
1881
    }
10,018✔
1882

1883
    m_sess->logger.info(util::LogCategory::reset, "Tracking %1", *has_pending_reset);
328✔
1884

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

1898
            logger.debug(util::LogCategory::reset, "Server has acknowledged %1", pending_reset);
176✔
1899

1900
            auto tr = self->m_db->start_write();
176✔
1901
            auto cur_pending_reset = PendingResetStore::has_pending_reset(tr);
176✔
1902
            if (!cur_pending_reset) {
176✔
1903
                logger.debug(util::LogCategory::reset, "Client reset cycle detection tracker already removed.");
4✔
1904
                return;
4✔
1905
            }
4✔
1906
            if (*cur_pending_reset == pending_reset) {
172✔
1907
                logger.debug(util::LogCategory::reset, "Removing client reset cycle detection tracker.");
168✔
1908
            }
168✔
1909
            else {
4✔
1910
                logger.info(util::LogCategory::reset, "Found new %1", cur_pending_reset);
4✔
1911
            }
4✔
1912
            PendingResetStore::clear_pending_reset(tr);
172✔
1913
            tr->commit();
172✔
1914
        });
172✔
1915
}
328✔
1916

1917
void SessionWrapper::update_subscription_version_info()
1918
{
10,346✔
1919
    if (!m_flx_subscription_store)
10,346✔
1920
        return;
8,722✔
1921
    auto versions_info = m_flx_subscription_store->get_version_info();
1,624✔
1922
    m_flx_active_version = versions_info.active;
1,624✔
1923
    m_flx_pending_mark_version = versions_info.pending_mark;
1,624✔
1924
}
1,624✔
1925

1926
std::string SessionWrapper::get_appservices_connection_id()
1927
{
72✔
1928
    auto pf = util::make_promise_future<std::string>();
72✔
1929

1930
    m_client.post([self = util::bind_ptr{this}, promise = std::move(pf.promise)](Status status) mutable {
72✔
1931
        if (!status.is_ok()) {
72✔
1932
            promise.set_error(status);
×
1933
            return;
×
1934
        }
×
1935

1936
        if (!self->m_sess) {
72✔
1937
            promise.set_error({ErrorCodes::RuntimeError, "session already finalized"});
×
1938
            return;
×
1939
        }
×
1940

1941
        promise.emplace_value(self->m_sess->get_connection().get_active_appservices_connection_id());
72✔
1942
    });
72✔
1943

1944
    return pf.future.get();
72✔
1945
}
72✔
1946

1947
// ################ ClientImpl::Connection ################
1948

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

1976
        REALM_ASSERT(m_activated);
2,782✔
1977
        if (m_state == ConnectionState::disconnected && m_num_active_sessions == 0) {
2,782✔
1978
            on_idle(); // Throws
2,774✔
1979
            // Connection object may be destroyed now.
1980
        }
2,774✔
1981
    });
2,782✔
1982
}
2,786✔
1983

1984
inline connection_ident_type ClientImpl::Connection::get_ident() const noexcept
1985
{
12✔
1986
    return m_ident;
12✔
1987
}
12✔
1988

1989

1990
inline const ServerEndpoint& ClientImpl::Connection::get_server_endpoint() const noexcept
1991
{
2,774✔
1992
    return m_server_endpoint;
2,774✔
1993
}
2,774✔
1994

1995
inline void ClientImpl::Connection::update_connect_info(const std::string& http_request_path_prefix,
1996
                                                        const std::string& signed_access_token)
1997
{
10,262✔
1998
    m_http_request_path_prefix = http_request_path_prefix; // Throws (copy)
10,262✔
1999
    m_signed_access_token = signed_access_token;           // Throws (copy)
10,262✔
2000
}
10,262✔
2001

2002

2003
void ClientImpl::Connection::resume_active_sessions()
2004
{
1,908✔
2005
    auto handler = [=](ClientImpl::Session& sess) {
3,812✔
2006
        sess.cancel_resumption_delay(); // Throws
3,812✔
2007
    };
3,812✔
2008
    for_each_active_session(std::move(handler)); // Throws
1,908✔
2009
}
1,908✔
2010

2011
void ClientImpl::Connection::on_idle()
2012
{
2,774✔
2013
    logger.debug(util::LogCategory::session, "Destroying connection object");
2,774✔
2014
    ClientImpl& client = get_client();
2,774✔
2015
    client.remove_connection(*this);
2,774✔
2016
    // NOTE: This connection object is now destroyed!
2017
}
2,774✔
2018

2019

2020
std::string ClientImpl::Connection::get_http_request_path() const
2021
{
3,754✔
2022
    using namespace std::string_view_literals;
3,754✔
2023
    const auto param = m_http_request_path_prefix.find('?') == std::string::npos ? "?baas_at="sv : "&baas_at="sv;
3,754✔
2024

2025
    std::string path;
3,754✔
2026
    path.reserve(m_http_request_path_prefix.size() + param.size() + m_signed_access_token.size());
3,754✔
2027
    path += m_http_request_path_prefix;
3,754✔
2028
    path += param;
3,754✔
2029
    path += m_signed_access_token;
3,754✔
2030

2031
    return path;
3,754✔
2032
}
3,754✔
2033

2034

2035
std::string ClientImpl::Connection::make_logger_prefix(connection_ident_type ident)
2036
{
2,786✔
2037
    return util::format("Connection[%1] ", ident);
2,786✔
2038
}
2,786✔
2039

2040

2041
void ClientImpl::Connection::report_connection_state_change(ConnectionState state,
2042
                                                            std::optional<SessionErrorInfo> error_info)
2043
{
11,052✔
2044
    if (m_force_closed) {
11,052✔
2045
        return;
2,410✔
2046
    }
2,410✔
2047
    auto handler = [=](ClientImpl::Session& sess) {
11,790✔
2048
        SessionImpl& sess_2 = static_cast<SessionImpl&>(sess);
11,790✔
2049
        sess_2.on_connection_state_changed(state, error_info); // Throws
11,790✔
2050
    };
11,790✔
2051
    for_each_active_session(std::move(handler)); // Throws
8,642✔
2052
}
8,642✔
2053

2054

2055
Client::Client(Config config)
2056
    : m_impl{new ClientImpl{std::move(config)}} // Throws
4,894✔
2057
{
9,926✔
2058
}
9,926✔
2059

2060

2061
Client::Client(Client&& client) noexcept
2062
    : m_impl{std::move(client.m_impl)}
2063
{
×
2064
}
×
2065

2066

2067
Client::~Client() noexcept {}
9,926✔
2068

2069

2070
void Client::shutdown() noexcept
2071
{
10,008✔
2072
    m_impl->shutdown();
10,008✔
2073
}
10,008✔
2074

2075
void Client::shutdown_and_wait()
2076
{
768✔
2077
    m_impl->shutdown_and_wait();
768✔
2078
}
768✔
2079

2080
void Client::cancel_reconnect_delay()
2081
{
1,912✔
2082
    m_impl->cancel_reconnect_delay();
1,912✔
2083
}
1,912✔
2084

2085
void Client::voluntary_disconnect_all_connections()
2086
{
12✔
2087
    m_impl->voluntary_disconnect_all_connections();
12✔
2088
}
12✔
2089

2090
bool Client::wait_for_session_terminations_or_client_stopped()
2091
{
9,528✔
2092
    return m_impl->wait_for_session_terminations_or_client_stopped();
9,528✔
2093
}
9,528✔
2094

2095
util::Future<void> Client::notify_session_terminated()
2096
{
56✔
2097
    return m_impl->notify_session_terminated();
56✔
2098
}
56✔
2099

2100
bool Client::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
2101
                                  port_type& port, std::string& path) const
2102
{
4,038✔
2103
    return m_impl->decompose_server_url(url, protocol, address, port, path); // Throws
4,038✔
2104
}
4,038✔
2105

2106

2107
Session::Session(Client& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
2108
                 std::shared_ptr<MigrationStore> migration_store, Config&& config)
2109
{
10,126✔
2110
    m_impl = new SessionWrapper{*client.m_impl, std::move(db), std::move(flx_sub_store), std::move(migration_store),
10,126✔
2111
                                std::move(config)}; // Throws
10,126✔
2112
}
10,126✔
2113

2114

2115
void Session::nonsync_transact_notify(version_type new_version)
2116
{
17,898✔
2117
    m_impl->on_commit(new_version); // Throws
17,898✔
2118
}
17,898✔
2119

2120

2121
void Session::cancel_reconnect_delay()
2122
{
28✔
2123
    m_impl->cancel_reconnect_delay(); // Throws
28✔
2124
}
28✔
2125

2126

2127
void Session::async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler handler)
2128
{
4,880✔
2129
    m_impl->async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws
4,880✔
2130
}
4,880✔
2131

2132

2133
bool Session::wait_for_upload_complete_or_client_stopped()
2134
{
12,900✔
2135
    return m_impl->wait_for_upload_complete_or_client_stopped(); // Throws
12,900✔
2136
}
12,900✔
2137

2138

2139
bool Session::wait_for_download_complete_or_client_stopped()
2140
{
9,988✔
2141
    return m_impl->wait_for_download_complete_or_client_stopped(); // Throws
9,988✔
2142
}
9,988✔
2143

2144

2145
void Session::refresh(std::string_view signed_access_token)
2146
{
216✔
2147
    m_impl->refresh(signed_access_token); // Throws
216✔
2148
}
216✔
2149

2150

2151
void Session::abandon() noexcept
2152
{
10,126✔
2153
    REALM_ASSERT(m_impl);
10,126✔
2154
    // Reabsorb the ownership assigned to the applications naked pointer by
2155
    // Session constructor
2156
    util::bind_ptr<SessionWrapper> wrapper{m_impl, util::bind_ptr_base::adopt_tag{}};
10,126✔
2157
    SessionWrapper::abandon(std::move(wrapper));
10,126✔
2158
}
10,126✔
2159

2160
util::Future<std::string> Session::send_test_command(std::string body)
2161
{
60✔
2162
    return m_impl->send_test_command(std::move(body));
60✔
2163
}
60✔
2164

2165
std::string Session::get_appservices_connection_id()
2166
{
72✔
2167
    return m_impl->get_appservices_connection_id();
72✔
2168
}
72✔
2169

2170
std::ostream& operator<<(std::ostream& os, ProxyConfig::Type proxyType)
2171
{
×
2172
    switch (proxyType) {
×
2173
        case ProxyConfig::Type::HTTP:
×
2174
            return os << "HTTP";
×
2175
        case ProxyConfig::Type::HTTPS:
×
2176
            return os << "HTTPS";
×
2177
    }
×
2178
    REALM_TERMINATE("Invalid Proxy Type object.");
2179
}
×
2180

2181
} // 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