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

realm / realm-core / 2430

18 Jun 2024 08:08PM UTC coverage: 90.976% (+0.007%) from 90.969%
2430

push

Evergreen

web-flow
Store FLX download progress in the Realm file (#7780)

102198 of 180368 branches covered (56.66%)

94 of 96 new or added lines in 8 files covered. (97.92%)

56 existing lines in 12 files now uncovered.

214776 of 236081 relevant lines covered (90.98%)

5829107.03 hits per line

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

91.98
/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;
148
        uint64_t uploaded;
149
        uint64_t uploadable;
150
        uint64_t downloaded;
151
        uint64_t downloadable;
152

153
        // Does not check snapshot
154
        bool operator==(const ReportedProgress& p) const noexcept
155
        {
23,438✔
156
            return uploaded == p.uploaded && uploadable == p.uploadable && downloaded == p.downloaded &&
23,438✔
157
                   downloadable == p.downloadable;
23,438✔
158
        }
23,438✔
159
    };
160
    std::optional<ReportedProgress> m_reported_progress;
161
    uint64_t m_final_uploaded = 0;
162
    uint64_t m_final_downloaded = 0;
163

164
    const util::UniqueFunction<ProgressHandler> m_progress_handler;
165
    util::UniqueFunction<ConnectionStateChangeListener> m_connection_state_change_listener;
166

167
    const util::UniqueFunction<SyncClientHookAction(SyncClientHookData const&)> m_debug_hook;
168
    bool m_in_debug_hook = false;
169

170
    const SessionReason m_session_reason;
171

172
    const uint64_t m_schema_version;
173

174
    std::shared_ptr<SubscriptionStore> m_flx_subscription_store;
175
    int64_t m_flx_active_version = 0;
176
    int64_t m_flx_last_seen_version = 0;
177
    int64_t m_flx_pending_mark_version = 0;
178
    std::unique_ptr<PendingBootstrapStore> m_flx_pending_bootstrap_store;
179

180
    std::shared_ptr<MigrationStore> m_migration_store;
181

182
    // Set to true when this session wrapper is actualized (i.e. the wrapped
183
    // session is created), or when the wrapper is finalized before actualization.
184
    // It is then never modified again.
185
    //
186
    // Actualization is scheduled during the construction of SessionWrapper, and
187
    // so a session specific post handler will always find that `m_actualized`
188
    // is true as the handler will always be run after the actualization job.
189
    // This holds even if the wrapper is finalized or closed before actualization.
190
    bool m_actualized = false;
191

192
    // Set to true when session deactivation is begun, either via force_close()
193
    // or finalize().
194
    bool m_closed = false;
195

196
    // Set to true in on_suspended() and then false in on_resumed(). Used to
197
    // suppress spurious connection state and error reporting while the session
198
    // is already in an error state.
199
    bool m_suspended = false;
200

201
    // Set when the session has been abandoned. After this point none of the
202
    // public API functions should be called again.
203
    bool m_abandoned = false;
204
    // Has the SessionWrapper been finalized?
205
    bool m_finalized = false;
206

207
    // Set to true when the first DOWNLOAD message is received to indicate that
208
    // the byte-level download progress parameters can be considered reasonable
209
    // reliable. Before that, a lot of time may have passed, so our record of
210
    // the download progress is likely completely out of date.
211
    bool m_reliable_download_progress = false;
212

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

226
    // These must only be accessed from the event loop thread.
227
    std::vector<WaitOperCompletionHandler> m_upload_completion_handlers;
228
    std::vector<WaitOperCompletionHandler> m_download_completion_handlers;
229
    std::vector<WaitOperCompletionHandler> m_sync_completion_handlers;
230

231
    // `m_target_*load_mark` and `m_reached_*load_mark` are protected by
232
    // `m_client.m_mutex`. `m_staged_*load_mark` must only be accessed by the
233
    // event loop thread.
234
    std::int_fast64_t m_target_upload_mark = 0, m_target_download_mark = 0;
235
    std::int_fast64_t m_staged_upload_mark = 0, m_staged_download_mark = 0;
236
    std::int_fast64_t m_reached_upload_mark = 0, m_reached_download_mark = 0;
237

238
    void on_upload_completion();
239
    void on_download_completion();
240
    void on_suspended(const SessionErrorInfo& error_info);
241
    void on_resumed();
242
    void on_connection_state_changed(ConnectionState, const std::optional<SessionErrorInfo>&);
243
    void on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state);
244
    void on_flx_sync_error(int64_t version, std::string_view err_msg);
245
    void on_flx_sync_version_complete(int64_t version);
246

247
    void init_progress_handler();
248
    void report_progress();
249

250
    friend class SessionWrapperStack;
251
    friend class ClientImpl::Session;
252
};
253

254

255
// ################ SessionWrapperStack ################
256

257
inline bool SessionWrapperStack::empty() const noexcept
258
{
19,836✔
259
    return !m_back;
19,836✔
260
}
19,836✔
261

262

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

270

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

281

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

290

291
inline bool SessionWrapperStack::erase(SessionWrapper* w) noexcept
292
{
10,124✔
293
    SessionWrapper** p = &m_back;
10,124✔
294
    while (*p && *p != w) {
10,298✔
295
        p = &(*p)->m_next;
174✔
296
    }
174✔
297
    if (!*p) {
10,124✔
298
        return false;
10,054✔
299
    }
10,054✔
300
    *p = w->m_next;
70✔
301
    util::bind_ptr<SessionWrapper>{w, util::bind_ptr_base::adopt_tag{}};
70✔
302
    return true;
70✔
303
}
10,124✔
304

305

306
SessionWrapperStack::~SessionWrapperStack()
307
{
19,836✔
308
    clear();
19,836✔
309
}
19,836✔
310

311

312
// ################ ClientImpl ################
313

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

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

327

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

357

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

388

389
bool ClientImpl::wait_for_session_terminations_or_client_stopped()
390
{
9,528✔
391
    // Thread safety required
392

393
    {
9,528✔
394
        util::CheckedLockGuard lock{m_mutex};
9,528✔
395
        m_sessions_terminated = false;
9,528✔
396
    }
9,528✔
397

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

423
    bool completion_condition_was_satisfied;
9,528✔
424
    {
9,528✔
425
        util::CheckedUniqueLock lock{m_mutex};
9,528✔
426
        m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_mutex) {
19,036✔
427
            return m_sessions_terminated || m_stopped;
19,036✔
428
        });
19,036✔
429
        completion_condition_was_satisfied = !m_stopped;
9,528✔
430
    }
9,528✔
431
    return completion_condition_was_satisfied;
9,528✔
432
}
9,528✔
433

434

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

446
        promise.emplace_value();
56✔
447
    });
56✔
448

449
    return std::move(pf.future);
56✔
450
}
56✔
451

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

460
void ClientImpl::shutdown_and_wait()
461
{
10,702✔
462
    shutdown();
10,702✔
463
    util::CheckedUniqueLock lock{m_drain_mutex};
10,702✔
464
    if (m_drained) {
10,702✔
465
        return;
772✔
466
    }
772✔
467

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

473
    m_drained = true;
9,930✔
474
}
9,930✔
475

476
void ClientImpl::shutdown() noexcept
477
{
20,714✔
478
    {
20,714✔
479
        util::CheckedLockGuard lock{m_mutex};
20,714✔
480
        if (m_stopped)
20,714✔
481
            return;
10,784✔
482
        m_stopped = true;
9,930✔
483
    }
9,930✔
484
    m_wait_or_client_stopped_cond.notify_all();
×
485

486
    drain_connections_on_loop();
9,930✔
487
}
9,930✔
488

489

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

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

508

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

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

533

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

572

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

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

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

615

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

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

648

649
// ################ SessionImpl ################
650

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

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

668

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

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

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

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

697
ClientHistory& SessionImpl::get_history() const noexcept
698
{
118,288✔
699
    return get_repl().get_history();
118,288✔
700
}
118,288✔
701

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

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

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

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

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

753

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

762

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

771

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

780

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

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

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

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

813
    if (is_steady_state_download_message(batch_state, query_version)) {
47,494✔
814
        return false;
45,350✔
815
    }
45,350✔
816

817
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
2,144✔
818
    std::optional<SyncProgress> maybe_progress;
2,144✔
819
    if (batch_state == DownloadBatchState::LastInBatch) {
2,144✔
820
        maybe_progress = progress;
1,960✔
821
    }
1,960✔
822

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

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

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

851
    if (batch_state == DownloadBatchState::MoreToCome) {
2,132✔
852
        notify_sync_progress();
180✔
853
        return true;
180✔
854
    }
180✔
855

856
    try {
1,952✔
857
        process_pending_flx_bootstrap();
1,952✔
858
    }
1,952✔
859
    catch (const IntegrationException& e) {
1,952✔
860
        on_integration_failure(e);
12✔
861
    }
12✔
862
    catch (...) {
1,952✔
863
        on_integration_failure(IntegrationException(exception_to_status()));
×
864
    }
×
865

866
    return true;
1,952✔
867
}
1,952✔
868

869

870
void SessionImpl::process_pending_flx_bootstrap()
871
{
12,002✔
872
    // Ignore the call if not a flx session or session is not active
873
    if (!m_is_flx_sync_session || m_state != State::Active) {
12,002✔
874
        return;
8,544✔
875
    }
8,544✔
876
    // Should never be called if session is not active
877
    REALM_ASSERT_EX(m_state == SessionImpl::Active, m_state);
3,458✔
878
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
3,458✔
879
    if (!bootstrap_store->has_pending()) {
3,458✔
880
        return;
1,486✔
881
    }
1,486✔
882

883
    auto pending_batch_stats = bootstrap_store->pending_stats();
1,972✔
884
    logger.info("Begin processing pending FLX bootstrap for query version %1. (changesets: %2, original total "
1,972✔
885
                "changeset size: %3)",
1,972✔
886
                pending_batch_stats.query_version, pending_batch_stats.pending_changesets,
1,972✔
887
                pending_batch_stats.pending_changeset_bytes);
1,972✔
888
    auto& history = get_repl().get_history();
1,972✔
889
    VersionInfo new_version;
1,972✔
890
    SyncProgress progress;
1,972✔
891
    int64_t query_version = -1;
1,972✔
892
    size_t changesets_processed = 0;
1,972✔
893

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

908
        auto batch_state =
2,116✔
909
            pending_batch.remaining_changesets > 0 ? DownloadBatchState::MoreToCome : DownloadBatchState::LastInBatch;
2,116✔
910
        uint64_t downloadable_bytes = 0;
2,116✔
911
        query_version = pending_batch.query_version;
2,116✔
912
        bool simulate_integration_error =
2,116✔
913
            (m_wrapper.m_simulate_integration_error && !pending_batch.changesets.empty());
2,116✔
914
        if (simulate_integration_error) {
2,116✔
915
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
4✔
916
        }
4✔
917

918
        call_debug_hook(SyncClientHookEvent::BootstrapBatchAboutToProcess, *pending_batch.progress, query_version,
2,112✔
919
                        batch_state, pending_batch.changesets.size());
2,112✔
920

921
        history.integrate_server_changesets(
2,112✔
922
            *pending_batch.progress, downloadable_bytes, pending_batch.changesets, new_version, batch_state, logger,
2,112✔
923
            transact, [&](const TransactionRef& tr, util::Span<Changeset> changesets_applied) {
2,112✔
924
                REALM_ASSERT_3(changesets_applied.size(), <=, pending_batch.changesets.size());
2,100✔
925
                bootstrap_store->pop_front_pending(tr, changesets_applied.size());
2,100✔
926
            });
2,100✔
927
        progress = *pending_batch.progress;
2,112✔
928
        changesets_processed += pending_batch.changesets.size();
2,112✔
929
        auto duration = std::chrono::steady_clock::now() - start_time;
2,112✔
930

931
        auto action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
2,112✔
932
                                      batch_state, pending_batch.changesets.size());
2,112✔
933
        REALM_ASSERT_EX(action == SyncClientHookAction::NoAction, action);
2,112✔
934

935
        logger.info("Integrated %1 changesets from pending bootstrap for query version %2, producing client version "
2,112✔
936
                    "%3 in %4 ms. %5 changesets remaining in bootstrap",
2,112✔
937
                    pending_batch.changesets.size(), pending_batch.query_version, new_version.realm_version,
2,112✔
938
                    std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(),
2,112✔
939
                    pending_batch.remaining_changesets);
2,112✔
940
    }
2,112✔
941

942
    REALM_ASSERT_3(query_version, !=, -1);
1,960✔
943
    on_flx_sync_progress(query_version, DownloadBatchState::LastInBatch);
1,960✔
944

945
    on_changesets_integrated(new_version.realm_version, progress, changesets_processed > 0);
1,960✔
946
    auto action = call_debug_hook(SyncClientHookEvent::BootstrapProcessed, progress, query_version,
1,960✔
947
                                  DownloadBatchState::LastInBatch, changesets_processed);
1,960✔
948
    // NoAction/EarlyReturn are both valid no-op actions to take here.
949
    REALM_ASSERT_EX(action == SyncClientHookAction::NoAction || action == SyncClientHookAction::EarlyReturn, action);
1,960✔
950
}
1,960✔
951

952
void SessionImpl::on_flx_sync_error(int64_t version, std::string_view err_msg)
953
{
20✔
954
    // Ignore the call if the session is not active
955
    if (m_state == State::Active) {
20✔
956
        m_wrapper.on_flx_sync_error(version, err_msg);
20✔
957
    }
20✔
958
}
20✔
959

960
void SessionImpl::on_flx_sync_progress(int64_t version, DownloadBatchState batch_state)
961
{
1,996✔
962
    // Ignore the call if the session is not active
963
    if (m_state == State::Active) {
1,996✔
964
        m_wrapper.on_flx_sync_progress(version, batch_state);
1,996✔
965
    }
1,996✔
966
}
1,996✔
967

968
SubscriptionStore* SessionImpl::get_flx_subscription_store()
969
{
18,298✔
970
    // Should never be called if session is not active
971
    REALM_ASSERT_EX(m_state == State::Active, m_state);
18,298✔
972
    return m_wrapper.get_flx_subscription_store();
18,298✔
973
}
18,298✔
974

975
MigrationStore* SessionImpl::get_migration_store()
976
{
67,596✔
977
    // Should never be called if session is not active
978
    REALM_ASSERT_EX(m_state == State::Active, m_state);
67,596✔
979
    return m_wrapper.get_migration_store();
67,596✔
980
}
67,596✔
981

982
void SessionImpl::on_flx_sync_version_complete(int64_t version)
983
{
300✔
984
    // Ignore the call if the session is not active
985
    if (m_state == State::Active) {
300✔
986
        m_wrapper.on_flx_sync_version_complete(version);
300✔
987
    }
300✔
988
}
300✔
989

990
SyncClientHookAction SessionImpl::call_debug_hook(const SyncClientHookData& data)
991
{
2,498✔
992
    // Should never be called if session is not active
993
    REALM_ASSERT_EX(m_state == State::Active, m_state);
2,498✔
994

995
    // Make sure we don't call the debug hook recursively.
996
    if (m_wrapper.m_in_debug_hook) {
2,498✔
997
        return SyncClientHookAction::NoAction;
24✔
998
    }
24✔
999
    m_wrapper.m_in_debug_hook = true;
2,474✔
1000
    auto in_hook_guard = util::make_scope_exit([&]() noexcept {
2,474✔
1001
        m_wrapper.m_in_debug_hook = false;
2,474✔
1002
    });
2,474✔
1003

1004
    auto action = m_wrapper.m_debug_hook(data);
2,474✔
1005
    switch (action) {
2,474✔
1006
        case realm::SyncClientHookAction::SuspendWithRetryableError: {
12✔
1007
            SessionErrorInfo err_info(Status{ErrorCodes::RuntimeError, "hook requested error"}, IsFatal{false});
12✔
1008
            err_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
12✔
1009

1010
            auto err_processing_err = receive_error_message(err_info);
12✔
1011
            REALM_ASSERT_EX(err_processing_err.is_ok(), err_processing_err);
12✔
1012
            return SyncClientHookAction::EarlyReturn;
12✔
1013
        }
×
1014
        case realm::SyncClientHookAction::TriggerReconnect: {
24✔
1015
            get_connection().voluntary_disconnect();
24✔
1016
            return SyncClientHookAction::EarlyReturn;
24✔
1017
        }
×
1018
        default:
2,430✔
1019
            return action;
2,430✔
1020
    }
2,474✔
1021
}
2,474✔
1022

1023
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const SyncProgress& progress,
1024
                                                  int64_t query_version, DownloadBatchState batch_state,
1025
                                                  size_t num_changesets)
1026
{
120,082✔
1027
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
120,082✔
1028
        return SyncClientHookAction::NoAction;
117,784✔
1029
    }
117,784✔
1030
    if (REALM_UNLIKELY(m_state != State::Active)) {
2,298✔
1031
        return SyncClientHookAction::NoAction;
×
1032
    }
×
1033

1034
    SyncClientHookData data;
2,298✔
1035
    data.event = event;
2,298✔
1036
    data.batch_state = batch_state;
2,298✔
1037
    data.progress = progress;
2,298✔
1038
    data.num_changesets = num_changesets;
2,298✔
1039
    data.query_version = query_version;
2,298✔
1040

1041
    return call_debug_hook(data);
2,298✔
1042
}
2,298✔
1043

1044
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const ProtocolErrorInfo& error_info)
1045
{
1,376✔
1046
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
1,376✔
1047
        return SyncClientHookAction::NoAction;
1,176✔
1048
    }
1,176✔
1049
    if (REALM_UNLIKELY(m_state != State::Active)) {
200✔
1050
        return SyncClientHookAction::NoAction;
×
1051
    }
×
1052

1053
    SyncClientHookData data;
200✔
1054
    data.event = event;
200✔
1055
    data.batch_state = DownloadBatchState::SteadyState;
200✔
1056
    data.progress = m_progress;
200✔
1057
    data.num_changesets = 0;
200✔
1058
    data.query_version = 0;
200✔
1059
    data.error_info = &error_info;
200✔
1060

1061
    return call_debug_hook(data);
200✔
1062
}
200✔
1063

1064
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event)
1065
{
18,914✔
1066
    return call_debug_hook(event, m_progress, m_last_sent_flx_query_version, DownloadBatchState::SteadyState, 0);
18,914✔
1067
}
18,914✔
1068

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

1077
    if (!m_is_flx_sync_session) {
49,656✔
1078
        return true;
44,032✔
1079
    }
44,032✔
1080

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

1086
    return false;
4,296✔
1087
}
5,624✔
1088

1089
void SessionImpl::init_progress_handler()
1090
{
10,346✔
1091
    REALM_ASSERT_EX(m_state == State::Unactivated || m_state == State::Active, m_state);
10,346✔
1092
    m_wrapper.init_progress_handler();
10,346✔
1093
}
10,346✔
1094

1095
void SessionImpl::enable_progress_notifications()
1096
{
45,886✔
1097
    m_wrapper.m_reliable_download_progress = true;
45,886✔
1098
}
45,886✔
1099

1100
void SessionImpl::notify_sync_progress()
1101
{
47,458✔
1102
    if (m_state != State::Active)
47,458✔
1103
        return;
×
1104

1105
    m_wrapper.report_progress();
47,458✔
1106
}
47,458✔
1107

1108
util::Future<std::string> SessionImpl::send_test_command(std::string body)
1109
{
60✔
1110
    if (m_state != State::Active) {
60✔
1111
        return Status{ErrorCodes::RuntimeError, "Cannot send a test command for a session that is not active"};
×
1112
    }
×
1113

1114
    try {
60✔
1115
        auto json_body = nlohmann::json::parse(body.begin(), body.end());
60✔
1116
        if (auto it = json_body.find("command"); it == json_body.end() || !it->is_string()) {
60✔
1117
            return Status{ErrorCodes::LogicError,
4✔
1118
                          "Must supply command name in \"command\" field of test command json object"};
4✔
1119
        }
4✔
1120
        if (json_body.size() > 1 && json_body.find("args") == json_body.end()) {
56✔
1121
            return Status{ErrorCodes::LogicError, "Only valid fields in a test command are \"command\" and \"args\""};
×
1122
        }
×
1123
    }
56✔
1124
    catch (const nlohmann::json::parse_error& e) {
60✔
1125
        return Status{ErrorCodes::LogicError, util::format("Invalid json input to send_test_command: %1", e.what())};
4✔
1126
    }
4✔
1127

1128
    auto pf = util::make_promise_future<std::string>();
52✔
1129
    get_client().post([this, promise = std::move(pf.promise), body = std::move(body)](Status status) mutable {
52✔
1130
        // Includes operation_aborted
1131
        if (!status.is_ok()) {
52✔
1132
            promise.set_error(status);
×
1133
            return;
×
1134
        }
×
1135

1136
        auto id = ++m_last_pending_test_command_ident;
52✔
1137
        m_pending_test_commands.push_back(PendingTestCommand{id, std::move(body), std::move(promise)});
52✔
1138
        ensure_enlisted_to_send();
52✔
1139
    });
52✔
1140

1141
    return std::move(pf.future);
52✔
1142
}
60✔
1143

1144
// ################ SessionWrapper ################
1145

1146
// The SessionWrapper class is held by a sync::Session (which is owned by the SyncSession instance) and
1147
// provides a link to the ClientImpl::Session that creates and receives messages with the server with
1148
// the ClientImpl::Connection that owns the ClientImpl::Session.
1149
SessionWrapper::SessionWrapper(ClientImpl& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1150
                               std::shared_ptr<MigrationStore> migration_store, Session::Config&& config)
1151
    : m_client{client}
4,890✔
1152
    , m_db(std::move(db))
4,890✔
1153
    , m_replication(m_db->get_replication())
4,890✔
1154
    , m_protocol_envelope{config.protocol_envelope}
4,890✔
1155
    , m_server_address{std::move(config.server_address)}
4,890✔
1156
    , m_server_port{config.server_port}
4,890✔
1157
    , m_server_verified{config.server_verified}
4,890✔
1158
    , m_user_id(std::move(config.user_id))
4,890✔
1159
    , m_sync_mode(flx_sub_store ? SyncServerMode::FLX : SyncServerMode::PBS)
4,890✔
1160
    , m_authorization_header_name{config.authorization_header_name}
4,890✔
1161
    , m_custom_http_headers{std::move(config.custom_http_headers)}
4,890✔
1162
    , m_verify_servers_ssl_certificate{config.verify_servers_ssl_certificate}
4,890✔
1163
    , m_simulate_integration_error{config.simulate_integration_error}
4,890✔
1164
    , m_ssl_trust_certificate_path{std::move(config.ssl_trust_certificate_path)}
4,890✔
1165
    , m_ssl_verify_callback{std::move(config.ssl_verify_callback)}
4,890✔
1166
    , m_flx_bootstrap_batch_size_bytes(config.flx_bootstrap_batch_size_bytes)
4,890✔
1167
    , m_http_request_path_prefix{std::move(config.service_identifier)}
4,890✔
1168
    , m_virt_path{std::move(config.realm_identifier)}
4,890✔
1169
    , m_proxy_config{std::move(config.proxy_config)}
4,890✔
1170
    , m_signed_access_token{std::move(config.signed_user_token)}
4,890✔
1171
    , m_client_reset_config{std::move(config.client_reset_config)}
4,890✔
1172
    , m_progress_handler(std::move(config.progress_handler))
4,890✔
1173
    , m_connection_state_change_listener(std::move(config.connection_state_change_listener))
4,890✔
1174
    , m_debug_hook(std::move(config.on_sync_client_event_hook))
4,890✔
1175
    , m_session_reason(m_client_reset_config ? SessionReason::ClientReset : config.session_reason)
4,890✔
1176
    , m_schema_version(config.schema_version)
4,890✔
1177
    , m_flx_subscription_store(std::move(flx_sub_store))
4,890✔
1178
    , m_migration_store(std::move(migration_store))
4,890✔
1179
{
10,126✔
1180
    REALM_ASSERT(m_db);
10,126✔
1181
    REALM_ASSERT(m_db->get_replication());
10,126✔
1182
    REALM_ASSERT(dynamic_cast<ClientReplication*>(m_db->get_replication()));
10,126✔
1183

1184
    // SessionWrapper begins at +1 retain count because Client retains and
1185
    // releases it while performing async operations, and these need to not
1186
    // take it to 0 or it could be deleted before the caller can retain it.
1187
    bind_ptr();
10,126✔
1188
    m_client.register_unactualized_session_wrapper(this);
10,126✔
1189
}
10,126✔
1190

1191
SessionWrapper::~SessionWrapper() noexcept
1192
{
10,116✔
1193
    // We begin actualization in the constructor and do not delete the wrapper
1194
    // until both the Client is done with it and the Session has abandoned it,
1195
    // so at this point we must have actualized, finalized, and been abandoned.
1196
    REALM_ASSERT(m_actualized);
10,116✔
1197
    REALM_ASSERT(m_abandoned);
10,116✔
1198
    REALM_ASSERT(m_finalized);
10,116✔
1199
    REALM_ASSERT(m_closed);
10,116✔
1200
    REALM_ASSERT(!m_db);
10,116✔
1201
}
10,116✔
1202

1203

1204
inline ClientReplication& SessionWrapper::get_replication() noexcept
1205
{
120,260✔
1206
    REALM_ASSERT(m_db);
120,260✔
1207
    return static_cast<ClientReplication&>(*m_replication);
120,260✔
1208
}
120,260✔
1209

1210

1211
inline ClientImpl& SessionWrapper::get_client() noexcept
1212
{
×
1213
    return m_client;
×
1214
}
×
1215

1216
bool SessionWrapper::has_flx_subscription_store() const
1217
{
1,996✔
1218
    return static_cast<bool>(m_flx_subscription_store);
1,996✔
1219
}
1,996✔
1220

1221
void SessionWrapper::on_flx_sync_error(int64_t version, std::string_view err_msg)
1222
{
20✔
1223
    REALM_ASSERT(!m_finalized);
20✔
1224
    get_flx_subscription_store()->update_state(version, SubscriptionSet::State::Error, err_msg);
20✔
1225
}
20✔
1226

1227
void SessionWrapper::on_flx_sync_version_complete(int64_t version)
1228
{
2,248✔
1229
    REALM_ASSERT(!m_finalized);
2,248✔
1230
    m_flx_last_seen_version = version;
2,248✔
1231
    m_flx_active_version = version;
2,248✔
1232
}
2,248✔
1233

1234
void SessionWrapper::on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state)
1235
{
1,996✔
1236
    if (!has_flx_subscription_store()) {
1,996✔
1237
        return;
×
1238
    }
×
1239
    REALM_ASSERT(!m_finalized);
1,996✔
1240
    REALM_ASSERT(new_version >= m_flx_last_seen_version);
1,996✔
1241
    REALM_ASSERT(new_version >= m_flx_active_version);
1,996✔
1242
    REALM_ASSERT(batch_state != DownloadBatchState::SteadyState);
1,996✔
1243

1244
    SubscriptionSet::State new_state = SubscriptionSet::State::Uncommitted; // Initialize to make compiler happy
1,996✔
1245

1246
    switch (batch_state) {
1,996✔
1247
        case DownloadBatchState::SteadyState:
✔
1248
            // Cannot be called with this value.
1249
            REALM_UNREACHABLE();
1250
        case DownloadBatchState::LastInBatch:
1,948✔
1251
            if (m_flx_active_version == new_version) {
1,948✔
1252
                return;
×
1253
            }
×
1254
            on_flx_sync_version_complete(new_version);
1,948✔
1255
            if (new_version == 0) {
1,948✔
1256
                new_state = SubscriptionSet::State::Complete;
924✔
1257
            }
924✔
1258
            else {
1,024✔
1259
                new_state = SubscriptionSet::State::AwaitingMark;
1,024✔
1260
                m_flx_pending_mark_version = new_version;
1,024✔
1261
            }
1,024✔
1262
            break;
1,948✔
1263
        case DownloadBatchState::MoreToCome:
48✔
1264
            if (m_flx_last_seen_version == new_version) {
48✔
1265
                return;
×
1266
            }
×
1267

1268
            m_flx_last_seen_version = new_version;
48✔
1269
            new_state = SubscriptionSet::State::Bootstrapping;
48✔
1270
            break;
48✔
1271
    }
1,996✔
1272

1273
    get_flx_subscription_store()->update_state(new_version, new_state);
1,996✔
1274
}
1,996✔
1275

1276
SubscriptionStore* SessionWrapper::get_flx_subscription_store()
1277
{
20,314✔
1278
    REALM_ASSERT(!m_finalized);
20,314✔
1279
    return m_flx_subscription_store.get();
20,314✔
1280
}
20,314✔
1281

1282
PendingBootstrapStore* SessionWrapper::get_flx_pending_bootstrap_store()
1283
{
5,602✔
1284
    REALM_ASSERT(!m_finalized);
5,602✔
1285
    return m_flx_pending_bootstrap_store.get();
5,602✔
1286
}
5,602✔
1287

1288
MigrationStore* SessionWrapper::get_migration_store()
1289
{
67,596✔
1290
    REALM_ASSERT(!m_finalized);
67,596✔
1291
    return m_migration_store.get();
67,596✔
1292
}
67,596✔
1293

1294
inline bool SessionWrapper::mark_abandoned()
1295
{
10,128✔
1296
    REALM_ASSERT(!m_abandoned);
10,128✔
1297
    m_abandoned = true;
10,128✔
1298
    return m_finalized;
10,128✔
1299
}
10,128✔
1300

1301

1302
void SessionWrapper::on_commit(version_type new_version)
1303
{
113,974✔
1304
    // Thread safety required
1305
    m_client.post([self = util::bind_ptr{this}, new_version] {
113,974✔
1306
        REALM_ASSERT(self->m_actualized);
113,974✔
1307
        if (REALM_UNLIKELY(!self->m_sess))
113,974✔
1308
            return; // Already finalized
846✔
1309
        SessionImpl& sess = *self->m_sess;
113,128✔
1310
        sess.recognize_sync_version(new_version); // Throws
113,128✔
1311
        self->report_progress();                  // Throws
113,128✔
1312
    });
113,128✔
1313
}
113,974✔
1314

1315

1316
void SessionWrapper::cancel_reconnect_delay()
1317
{
28✔
1318
    // Thread safety required
1319

1320
    m_client.post([self = util::bind_ptr{this}] {
28✔
1321
        REALM_ASSERT(self->m_actualized);
28✔
1322
        if (REALM_UNLIKELY(self->m_closed)) {
28✔
1323
            return;
×
1324
        }
×
1325

1326
        if (REALM_UNLIKELY(!self->m_sess))
28✔
1327
            return; // Already finalized
×
1328
        SessionImpl& sess = *self->m_sess;
28✔
1329
        sess.cancel_resumption_delay(); // Throws
28✔
1330
        ClientImpl::Connection& conn = sess.get_connection();
28✔
1331
        conn.cancel_reconnect_delay(); // Throws
28✔
1332
    });                                // Throws
28✔
1333
}
28✔
1334

1335
void SessionWrapper::async_wait_for(bool upload_completion, bool download_completion,
1336
                                    WaitOperCompletionHandler handler)
1337
{
5,202✔
1338
    REALM_ASSERT(upload_completion || download_completion);
5,202✔
1339

1340
    m_client.post([self = util::bind_ptr{this}, handler = std::move(handler), upload_completion,
5,202✔
1341
                   download_completion]() mutable {
5,202✔
1342
        REALM_ASSERT(self->m_actualized);
5,202✔
1343
        if (REALM_UNLIKELY(!self->m_sess)) {
5,202✔
1344
            // Already finalized
1345
            handler({ErrorCodes::OperationAborted, "Session finalized before callback could run"}); // Throws
104✔
1346
            return;
104✔
1347
        }
104✔
1348
        if (upload_completion) {
5,098✔
1349
            if (download_completion) {
2,604✔
1350
                // Wait for upload and download completion
1351
                self->m_sync_completion_handlers.push_back(std::move(handler)); // Throws
314✔
1352
            }
314✔
1353
            else {
2,290✔
1354
                // Wait for upload completion only
1355
                self->m_upload_completion_handlers.push_back(std::move(handler)); // Throws
2,290✔
1356
            }
2,290✔
1357
        }
2,604✔
1358
        else {
2,494✔
1359
            // Wait for download completion only
1360
            self->m_download_completion_handlers.push_back(std::move(handler)); // Throws
2,494✔
1361
        }
2,494✔
1362
        SessionImpl& sess = *self->m_sess;
5,098✔
1363
        if (upload_completion)
5,098✔
1364
            sess.request_upload_completion_notification(); // Throws
2,604✔
1365
        if (download_completion)
5,098✔
1366
            sess.request_download_completion_notification(); // Throws
2,808✔
1367
    });                                                      // Throws
5,098✔
1368
}
5,202✔
1369

1370

1371
bool SessionWrapper::wait_for_upload_complete_or_client_stopped()
1372
{
12,908✔
1373
    // Thread safety required
1374
    REALM_ASSERT(!m_abandoned);
12,908✔
1375

1376
    std::int_fast64_t target_mark;
12,908✔
1377
    {
12,908✔
1378
        util::CheckedLockGuard lock{m_client.m_mutex};
12,908✔
1379
        target_mark = ++m_target_upload_mark;
12,908✔
1380
    }
12,908✔
1381

1382
    m_client.post([self = util::bind_ptr{this}, target_mark] {
12,908✔
1383
        REALM_ASSERT(self->m_actualized);
12,908✔
1384
        // The session wrapper may already have been finalized. This can only
1385
        // happen if it was abandoned, but in that case, the call of
1386
        // wait_for_upload_complete_or_client_stopped() must have returned
1387
        // already.
1388
        if (REALM_UNLIKELY(!self->m_sess))
12,908✔
1389
            return;
24✔
1390
        if (target_mark > self->m_staged_upload_mark) {
12,884✔
1391
            self->m_staged_upload_mark = target_mark;
12,884✔
1392
            SessionImpl& sess = *self->m_sess;
12,884✔
1393
            sess.request_upload_completion_notification(); // Throws
12,884✔
1394
        }
12,884✔
1395
    }); // Throws
12,884✔
1396

1397
    bool completion_condition_was_satisfied;
12,908✔
1398
    {
12,908✔
1399
        util::CheckedUniqueLock lock{m_client.m_mutex};
12,908✔
1400
        m_client.m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_client.m_mutex) {
32,574✔
1401
            return m_reached_upload_mark >= target_mark || m_client.m_stopped;
32,574✔
1402
        });
32,574✔
1403
        completion_condition_was_satisfied = !m_client.m_stopped;
12,908✔
1404
    }
12,908✔
1405
    return completion_condition_was_satisfied;
12,908✔
1406
}
12,908✔
1407

1408

1409
bool SessionWrapper::wait_for_download_complete_or_client_stopped()
1410
{
9,996✔
1411
    // Thread safety required
1412
    REALM_ASSERT(!m_abandoned);
9,996✔
1413

1414
    std::int_fast64_t target_mark;
9,996✔
1415
    {
9,996✔
1416
        util::CheckedLockGuard lock{m_client.m_mutex};
9,996✔
1417
        target_mark = ++m_target_download_mark;
9,996✔
1418
    }
9,996✔
1419

1420
    m_client.post([self = util::bind_ptr{this}, target_mark] {
9,996✔
1421
        REALM_ASSERT(self->m_actualized);
9,996✔
1422
        // The session wrapper may already have been finalized. This can only
1423
        // happen if it was abandoned, but in that case, the call of
1424
        // wait_for_download_complete_or_client_stopped() must have returned
1425
        // already.
1426
        if (REALM_UNLIKELY(!self->m_sess))
9,996✔
1427
            return;
60✔
1428
        if (target_mark > self->m_staged_download_mark) {
9,936✔
1429
            self->m_staged_download_mark = target_mark;
9,932✔
1430
            SessionImpl& sess = *self->m_sess;
9,932✔
1431
            sess.request_download_completion_notification(); // Throws
9,932✔
1432
        }
9,932✔
1433
    }); // Throws
9,936✔
1434

1435
    bool completion_condition_was_satisfied;
9,996✔
1436
    {
9,996✔
1437
        util::CheckedUniqueLock lock{m_client.m_mutex};
9,996✔
1438
        m_client.m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_client.m_mutex) {
20,348✔
1439
            return m_reached_download_mark >= target_mark || m_client.m_stopped;
20,348✔
1440
        });
20,348✔
1441
        completion_condition_was_satisfied = !m_client.m_stopped;
9,996✔
1442
    }
9,996✔
1443
    return completion_condition_was_satisfied;
9,996✔
1444
}
9,996✔
1445

1446

1447
void SessionWrapper::refresh(std::string_view signed_access_token)
1448
{
216✔
1449
    // Thread safety required
1450
    REALM_ASSERT(!m_abandoned);
216✔
1451

1452
    m_client.post([self = util::bind_ptr{this}, token = std::string(signed_access_token)] {
216✔
1453
        REALM_ASSERT(self->m_actualized);
216✔
1454
        if (REALM_UNLIKELY(!self->m_sess))
216✔
1455
            return; // Already finalized
4✔
1456
        self->m_signed_access_token = std::move(token);
212✔
1457
        SessionImpl& sess = *self->m_sess;
212✔
1458
        ClientImpl::Connection& conn = sess.get_connection();
212✔
1459
        // FIXME: This only makes sense when each session uses a separate connection.
1460
        conn.update_connect_info(self->m_http_request_path_prefix, self->m_signed_access_token); // Throws
212✔
1461
        sess.cancel_resumption_delay();                                                          // Throws
212✔
1462
        conn.cancel_reconnect_delay();                                                           // Throws
212✔
1463
    });
212✔
1464
}
216✔
1465

1466

1467
void SessionWrapper::abandon(util::bind_ptr<SessionWrapper> wrapper) noexcept
1468
{
10,128✔
1469
    ClientImpl& client = wrapper->m_client;
10,128✔
1470
    client.register_abandoned_session_wrapper(std::move(wrapper));
10,128✔
1471
}
10,128✔
1472

1473

1474
// Must be called from event loop thread
1475
void SessionWrapper::actualize()
1476
{
10,050✔
1477
    // actualize() can only ever be called once
1478
    REALM_ASSERT(!m_actualized);
10,050✔
1479
    REALM_ASSERT(!m_sess);
10,050✔
1480
    // The client should have removed this wrapper from those pending
1481
    // actualization if it called force_close() or finalize_before_actualize()
1482
    REALM_ASSERT(!m_finalized);
10,050✔
1483
    REALM_ASSERT(!m_closed);
10,050✔
1484

1485
    m_actualized = true;
10,050✔
1486

1487
    ScopeExitFail close_on_error([&]() noexcept {
10,050✔
1488
        m_closed = true;
4✔
1489
    });
4✔
1490

1491
    m_db->claim_sync_agent();
10,050✔
1492
    m_db->add_commit_listener(this);
10,050✔
1493
    ScopeExitFail remove_commit_listener([&]() noexcept {
10,050✔
1494
        m_db->remove_commit_listener(this);
×
1495
    });
×
1496

1497
    ServerEndpoint endpoint{m_protocol_envelope, m_server_address, m_server_port,
10,050✔
1498
                            m_user_id,           m_sync_mode,      m_server_verified};
10,050✔
1499
    bool was_created = false;
10,050✔
1500
    ClientImpl::Connection& conn = m_client.get_connection(
10,050✔
1501
        std::move(endpoint), m_authorization_header_name, m_custom_http_headers, m_verify_servers_ssl_certificate,
10,050✔
1502
        m_ssl_trust_certificate_path, m_ssl_verify_callback, m_proxy_config,
10,050✔
1503
        was_created); // Throws
10,050✔
1504
    ScopeExitFail remove_connection([&]() noexcept {
10,050✔
1505
        if (was_created)
×
1506
            m_client.remove_connection(conn);
×
1507
    });
×
1508

1509
    // FIXME: This only makes sense when each session uses a separate connection.
1510
    conn.update_connect_info(m_http_request_path_prefix, m_signed_access_token);    // Throws
10,050✔
1511
    std::unique_ptr<SessionImpl> sess = std::make_unique<SessionImpl>(*this, conn); // Throws
10,050✔
1512
    if (m_sync_mode == SyncServerMode::FLX) {
10,050✔
1513
        m_flx_pending_bootstrap_store = std::make_unique<PendingBootstrapStore>(m_db, sess->logger);
1,506✔
1514
    }
1,506✔
1515

1516
    sess->logger.info("Binding '%1' to '%2'", m_db->get_path(), m_virt_path); // Throws
10,050✔
1517
    m_sess = sess.get();
10,050✔
1518
    ScopeExitFail clear_sess([&]() noexcept {
10,050✔
1519
        m_sess = nullptr;
×
1520
    });
×
1521
    conn.activate_session(std::move(sess)); // Throws
10,050✔
1522

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

1527
    if (was_created)
10,050✔
1528
        conn.activate(); // Throws
2,786✔
1529

1530
    if (m_connection_state_change_listener) {
10,050✔
1531
        ConnectionState state = conn.get_state();
10,040✔
1532
        if (state != ConnectionState::disconnected) {
10,040✔
1533
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,082✔
1534
            if (state == ConnectionState::connected)
7,082✔
1535
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
6,756✔
1536
        }
7,082✔
1537
    }
10,040✔
1538

1539
    if (!m_client_reset_config)
10,050✔
1540
        report_progress(); // Throws
9,670✔
1541
}
10,050✔
1542

1543
void SessionWrapper::force_close()
1544
{
10,138✔
1545
    if (m_closed) {
10,138✔
1546
        return;
106✔
1547
    }
106✔
1548
    REALM_ASSERT(m_actualized);
10,032✔
1549
    REALM_ASSERT(m_sess);
10,032✔
1550
    m_closed = true;
10,032✔
1551

1552
    ClientImpl::Connection& conn = m_sess->get_connection();
10,032✔
1553
    conn.initiate_session_deactivation(m_sess); // Throws
10,032✔
1554

1555
    // We need to keep the DB open until finalization, but we no longer want to
1556
    // know when commits are made
1557
    m_db->remove_commit_listener(this);
10,032✔
1558

1559
    // Delete the pending bootstrap store since it uses a reference to the logger in m_sess
1560
    m_flx_pending_bootstrap_store.reset();
10,032✔
1561
    // Clear the subscription and migration store refs since they are owned by SyncSession
1562
    m_flx_subscription_store.reset();
10,032✔
1563
    m_migration_store.reset();
10,032✔
1564
    m_sess = nullptr;
10,032✔
1565
    // Everything is being torn down, no need to report connection state anymore
1566
    m_connection_state_change_listener = {};
10,032✔
1567
}
10,032✔
1568

1569
// Must be called from event loop thread
1570
//
1571
// `m_client.m_mutex` is not held while this is called, but it is guaranteed to
1572
// have been acquired at some point in between the final read or write ever made
1573
// from a different thread and when this is called.
1574
void SessionWrapper::finalize()
1575
{
10,036✔
1576
    REALM_ASSERT(m_actualized);
10,036✔
1577
    REALM_ASSERT(m_abandoned);
10,036✔
1578
    REALM_ASSERT(!m_finalized);
10,036✔
1579

1580
    force_close();
10,036✔
1581

1582
    m_finalized = true;
10,036✔
1583

1584
    // The Realm file can be closed now, as no access to the Realm file is
1585
    // supposed to happen on behalf of a session after initiation of
1586
    // deactivation.
1587
    m_db->release_sync_agent();
10,036✔
1588
    m_db = nullptr;
10,036✔
1589

1590
    // All outstanding wait operations must be canceled
1591
    while (!m_upload_completion_handlers.empty()) {
10,466✔
1592
        auto handler = std::move(m_upload_completion_handlers.back());
430✔
1593
        m_upload_completion_handlers.pop_back();
430✔
1594
        handler(
430✔
1595
            {ErrorCodes::OperationAborted, "Sync session is being finalized before upload was complete"}); // Throws
430✔
1596
    }
430✔
1597
    while (!m_download_completion_handlers.empty()) {
10,266✔
1598
        auto handler = std::move(m_download_completion_handlers.back());
230✔
1599
        m_download_completion_handlers.pop_back();
230✔
1600
        handler(
230✔
1601
            {ErrorCodes::OperationAborted, "Sync session is being finalized before download was complete"}); // Throws
230✔
1602
    }
230✔
1603
    while (!m_sync_completion_handlers.empty()) {
10,054✔
1604
        auto handler = std::move(m_sync_completion_handlers.back());
18✔
1605
        m_sync_completion_handlers.pop_back();
18✔
1606
        handler({ErrorCodes::OperationAborted, "Sync session is being finalized before sync was complete"}); // Throws
18✔
1607
    }
18✔
1608
}
10,036✔
1609

1610

1611
// Must be called only when an unactualized session wrapper becomes abandoned.
1612
//
1613
// Called with a lock on `m_client.m_mutex`.
1614
inline void SessionWrapper::finalize_before_actualization() noexcept
1615
{
74✔
1616
    REALM_ASSERT(!m_finalized);
74✔
1617
    REALM_ASSERT(!m_sess);
74✔
1618
    m_actualized = true;
74✔
1619
    m_finalized = true;
74✔
1620
    m_closed = true;
74✔
1621
    m_db->remove_commit_listener(this);
74✔
1622
    m_db->release_sync_agent();
74✔
1623
    m_db = nullptr;
74✔
1624
}
74✔
1625

1626
void SessionWrapper::on_upload_completion()
1627
{
14,806✔
1628
    REALM_ASSERT(!m_finalized);
14,806✔
1629
    while (!m_upload_completion_handlers.empty()) {
16,762✔
1630
        auto handler = std::move(m_upload_completion_handlers.back());
1,956✔
1631
        m_upload_completion_handlers.pop_back();
1,956✔
1632
        handler(Status::OK()); // Throws
1,956✔
1633
    }
1,956✔
1634
    while (!m_sync_completion_handlers.empty()) {
15,006✔
1635
        auto handler = std::move(m_sync_completion_handlers.back());
200✔
1636
        m_download_completion_handlers.push_back(std::move(handler)); // Throws
200✔
1637
        m_sync_completion_handlers.pop_back();
200✔
1638
    }
200✔
1639
    util::CheckedLockGuard lock{m_client.m_mutex};
14,806✔
1640
    if (m_staged_upload_mark > m_reached_upload_mark) {
14,806✔
1641
        m_reached_upload_mark = m_staged_upload_mark;
12,866✔
1642
        m_client.m_wait_or_client_stopped_cond.notify_all();
12,866✔
1643
    }
12,866✔
1644
}
14,806✔
1645

1646

1647
void SessionWrapper::on_download_completion()
1648
{
16,170✔
1649
    while (!m_download_completion_handlers.empty()) {
18,622✔
1650
        auto handler = std::move(m_download_completion_handlers.back());
2,452✔
1651
        m_download_completion_handlers.pop_back();
2,452✔
1652
        handler(Status::OK()); // Throws
2,452✔
1653
    }
2,452✔
1654
    while (!m_sync_completion_handlers.empty()) {
16,266✔
1655
        auto handler = std::move(m_sync_completion_handlers.back());
96✔
1656
        m_upload_completion_handlers.push_back(std::move(handler)); // Throws
96✔
1657
        m_sync_completion_handlers.pop_back();
96✔
1658
    }
96✔
1659

1660
    if (m_flx_subscription_store && m_flx_pending_mark_version != SubscriptionSet::EmptyVersion) {
16,170✔
1661
        m_sess->logger.debug("Marking query version %1 as complete after receiving MARK message",
900✔
1662
                             m_flx_pending_mark_version);
900✔
1663
        m_flx_subscription_store->update_state(m_flx_pending_mark_version, SubscriptionSet::State::Complete);
900✔
1664
        m_flx_pending_mark_version = SubscriptionSet::EmptyVersion;
900✔
1665
    }
900✔
1666

1667
    util::CheckedLockGuard lock{m_client.m_mutex};
16,170✔
1668
    if (m_staged_download_mark > m_reached_download_mark) {
16,170✔
1669
        m_reached_download_mark = m_staged_download_mark;
9,866✔
1670
        m_client.m_wait_or_client_stopped_cond.notify_all();
9,866✔
1671
    }
9,866✔
1672
}
16,170✔
1673

1674

1675
void SessionWrapper::on_suspended(const SessionErrorInfo& error_info)
1676
{
668✔
1677
    REALM_ASSERT(!m_finalized);
668✔
1678
    m_suspended = true;
668✔
1679
    if (m_connection_state_change_listener) {
668✔
1680
        m_connection_state_change_listener(ConnectionState::disconnected, error_info); // Throws
668✔
1681
    }
668✔
1682
}
668✔
1683

1684

1685
void SessionWrapper::on_resumed()
1686
{
60✔
1687
    REALM_ASSERT(!m_finalized);
60✔
1688
    m_suspended = false;
60✔
1689
    if (m_connection_state_change_listener) {
60✔
1690
        ClientImpl::Connection& conn = m_sess->get_connection();
60✔
1691
        if (conn.get_state() != ConnectionState::disconnected) {
60✔
1692
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
54✔
1693
            if (conn.get_state() == ConnectionState::connected)
54✔
1694
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
48✔
1695
        }
54✔
1696
    }
60✔
1697
}
60✔
1698

1699

1700
void SessionWrapper::on_connection_state_changed(ConnectionState state,
1701
                                                 const std::optional<SessionErrorInfo>& error_info)
1702
{
11,588✔
1703
    if (m_connection_state_change_listener && !m_suspended) {
11,588✔
1704
        m_connection_state_change_listener(state, error_info); // Throws
11,554✔
1705
    }
11,554✔
1706
}
11,588✔
1707

1708
void SessionWrapper::init_progress_handler()
1709
{
10,346✔
1710
    ClientHistory::get_upload_download_bytes(m_db.get(), m_final_downloaded, m_final_uploaded);
10,346✔
1711
}
10,346✔
1712

1713
void SessionWrapper::report_progress()
1714
{
170,254✔
1715
    REALM_ASSERT(!m_finalized);
170,254✔
1716
    REALM_ASSERT(m_sess);
170,254✔
1717

1718
    if (!m_progress_handler)
170,254✔
1719
        return;
116,604✔
1720

1721
    // Ignore progress messages from before we first receive a DOWNLOAD message
1722
    if (!m_reliable_download_progress)
53,650✔
1723
        return;
27,668✔
1724

1725
    ReportedProgress p;
25,982✔
1726
    DownloadableProgress downloadable;
25,982✔
1727
    ClientHistory::get_upload_download_bytes(m_db.get(), p.downloaded, downloadable, p.uploaded, p.uploadable,
25,982✔
1728
                                             p.snapshot);
25,982✔
1729

1730
    auto calculate_progress = [](uint64_t transferred, uint64_t transferable, uint64_t final_transferred) {
25,982✔
1731
        REALM_ASSERT_DEBUG_EX(final_transferred <= transferred, final_transferred, transferred, transferable);
20,418✔
1732
        REALM_ASSERT_DEBUG_EX(transferred <= transferable, final_transferred, transferred, transferable);
20,418✔
1733

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

1742
        double progress_estimate = 1.0;
20,418✔
1743
        if (final_transferred < transferable && transferred < transferable)
20,418✔
1744
            progress_estimate = (transferred - final_transferred) / double(transferable - final_transferred);
10,550✔
1745
        return progress_estimate;
20,418✔
1746
    };
20,418✔
1747

1748
    bool upload_completed = p.uploaded == p.uploadable;
25,982✔
1749
    double upload_estimate = 1.0;
25,982✔
1750
    if (!upload_completed)
25,982✔
1751
        upload_estimate = calculate_progress(p.uploaded, p.uploadable, m_final_uploaded);
10,470✔
1752

1753
    bool download_completed = p.downloaded == 0;
25,982✔
1754
    double download_estimate = 1.00;
25,982✔
1755
    if (m_flx_pending_bootstrap_store) {
25,982✔
1756
        if (m_flx_pending_bootstrap_store->has_pending()) {
12,256✔
1757
            download_estimate = downloadable.as_estimate();
708✔
1758
            p.downloaded += m_flx_pending_bootstrap_store->pending_stats().pending_changeset_bytes;
708✔
1759
        }
708✔
1760
        download_completed = download_estimate >= 1.0;
12,256✔
1761

1762
        // for flx with download estimate these bytes are not known
1763
        // provide some sensible value for non-streaming version of object-store callbacks
1764
        // until these field are completely removed from the api after pbs deprecation
1765
        p.downloadable = p.downloaded;
12,256✔
1766
        if (download_estimate > 0 && download_estimate < 1.0 && p.downloaded > m_final_downloaded)
12,256!
NEW
1767
            p.downloadable = m_final_downloaded + uint64_t((p.downloaded - m_final_downloaded) / download_estimate);
×
1768
    }
12,256✔
1769
    else {
13,726✔
1770
        // uploadable_bytes is uploaded + remaining to upload, while downloadable_bytes
1771
        // is only the remaining to download. This is confusing, so make them use
1772
        // the same units.
1773
        p.downloadable = downloadable.as_bytes() + p.downloaded;
13,726✔
1774
        if (!download_completed)
13,726✔
1775
            download_estimate = calculate_progress(p.downloaded, p.downloadable, m_final_downloaded);
9,948✔
1776
    }
13,726✔
1777

1778
    if (download_completed)
25,982✔
1779
        m_final_downloaded = p.downloaded;
16,038✔
1780
    if (upload_completed)
25,982✔
1781
        m_final_uploaded = p.uploaded;
15,516✔
1782

1783
    if (p == m_reported_progress)
25,982✔
1784
        return;
18,634✔
1785

1786
    m_reported_progress = p;
7,348✔
1787

1788
    if (m_sess->logger.would_log(Logger::Level::debug)) {
7,348✔
1789
        auto to_str = [](double d) {
14,228✔
1790
            std::ostringstream ss;
14,228✔
1791
            // progress estimate string in the DOWNLOAD message isn't expected to have more than 4 digits of precision
1792
            ss << std::fixed << std::setprecision(4) << d;
14,228✔
1793
            return ss.str();
14,228✔
1794
        };
14,228✔
1795
        m_sess->logger.debug(
7,114✔
1796
            "Progress handler called, downloaded = %1, downloadable = %2, estimate = %3, "
7,114✔
1797
            "uploaded = %4, uploadable = %5, estimate = %6, snapshot version = %7, query_version = %8",
7,114✔
1798
            p.downloaded, p.downloadable, to_str(download_estimate), p.uploaded, p.uploadable,
7,114✔
1799
            to_str(upload_estimate), p.snapshot, m_flx_active_version);
7,114✔
1800
    }
7,114✔
1801

1802
    m_progress_handler(p.downloaded, p.downloadable, p.uploaded, p.uploadable, p.snapshot, download_estimate,
7,348✔
1803
                       upload_estimate, m_flx_last_seen_version);
7,348✔
1804
}
7,348✔
1805

1806
util::Future<std::string> SessionWrapper::send_test_command(std::string body)
1807
{
60✔
1808
    if (!m_sess) {
60✔
1809
        return Status{ErrorCodes::RuntimeError, "session must be activated to send a test command"};
×
1810
    }
×
1811

1812
    return m_sess->send_test_command(std::move(body));
60✔
1813
}
60✔
1814

1815
void SessionWrapper::handle_pending_client_reset_acknowledgement()
1816
{
10,346✔
1817
    REALM_ASSERT(!m_finalized);
10,346✔
1818

1819
    auto has_pending_reset = PendingResetStore::has_pending_reset(m_db->start_frozen());
10,346✔
1820
    if (!has_pending_reset) {
10,346✔
1821
        return; // nothing to do
10,024✔
1822
    }
10,024✔
1823

1824
    m_sess->logger.info(util::LogCategory::reset, "Tracking %1", *has_pending_reset);
322✔
1825

1826
    // Now that the client reset merge is complete, wait for the changes to synchronize with the server
1827
    async_wait_for(
322✔
1828
        true, true, [self = util::bind_ptr(this), pending_reset = std::move(*has_pending_reset)](Status status) {
322✔
1829
            if (status == ErrorCodes::OperationAborted) {
322✔
1830
                return;
146✔
1831
            }
146✔
1832
            auto& logger = self->m_sess->logger;
176✔
1833
            if (!status.is_ok()) {
176✔
1834
                logger.error(util::LogCategory::reset, "Error while tracking client reset acknowledgement: %1",
×
1835
                             status);
×
1836
                return;
×
1837
            }
×
1838

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

1841
            auto tr = self->m_db->start_write();
176✔
1842
            auto cur_pending_reset = PendingResetStore::has_pending_reset(tr);
176✔
1843
            if (!cur_pending_reset) {
176✔
1844
                logger.debug(util::LogCategory::reset, "Client reset cycle detection tracker already removed.");
4✔
1845
                return;
4✔
1846
            }
4✔
1847
            if (*cur_pending_reset == pending_reset) {
172✔
1848
                logger.debug(util::LogCategory::reset, "Removing client reset cycle detection tracker.");
168✔
1849
            }
168✔
1850
            else {
4✔
1851
                logger.info(util::LogCategory::reset, "Found new %1", cur_pending_reset);
4✔
1852
            }
4✔
1853
            PendingResetStore::clear_pending_reset(tr);
172✔
1854
            tr->commit();
172✔
1855
        });
172✔
1856
}
322✔
1857

1858
void SessionWrapper::update_subscription_version_info()
1859
{
10,346✔
1860
    if (!m_flx_subscription_store)
10,346✔
1861
        return;
8,726✔
1862
    auto versions_info = m_flx_subscription_store->get_version_info();
1,620✔
1863
    m_flx_active_version = versions_info.active;
1,620✔
1864
    m_flx_pending_mark_version = versions_info.pending_mark;
1,620✔
1865
}
1,620✔
1866

1867
std::string SessionWrapper::get_appservices_connection_id()
1868
{
72✔
1869
    auto pf = util::make_promise_future<std::string>();
72✔
1870

1871
    m_client.post([self = util::bind_ptr{this}, promise = std::move(pf.promise)](Status status) mutable {
72✔
1872
        if (!status.is_ok()) {
72✔
1873
            promise.set_error(status);
×
1874
            return;
×
1875
        }
×
1876

1877
        if (!self->m_sess) {
72✔
1878
            promise.set_error({ErrorCodes::RuntimeError, "session already finalized"});
×
1879
            return;
×
1880
        }
×
1881

1882
        promise.emplace_value(self->m_sess->get_connection().get_active_appservices_connection_id());
72✔
1883
    });
72✔
1884

1885
    return pf.future.get();
72✔
1886
}
72✔
1887

1888
// ################ ClientImpl::Connection ################
1889

1890
ClientImpl::Connection::Connection(ClientImpl& client, connection_ident_type ident, ServerEndpoint endpoint,
1891
                                   const std::string& authorization_header_name,
1892
                                   const std::map<std::string, std::string>& custom_http_headers,
1893
                                   bool verify_servers_ssl_certificate,
1894
                                   Optional<std::string> ssl_trust_certificate_path,
1895
                                   std::function<SSLVerifyCallback> ssl_verify_callback,
1896
                                   Optional<ProxyConfig> proxy_config, ReconnectInfo reconnect_info)
1897
    : logger_ptr{std::make_shared<util::PrefixLogger>(util::LogCategory::session, make_logger_prefix(ident),
1,328✔
1898
                                                      client.logger_ptr)} // Throws
1,328✔
1899
    , logger{*logger_ptr}
1,328✔
1900
    , m_client{client}
1,328✔
1901
    , m_verify_servers_ssl_certificate{verify_servers_ssl_certificate}    // DEPRECATED
1,328✔
1902
    , m_ssl_trust_certificate_path{std::move(ssl_trust_certificate_path)} // DEPRECATED
1,328✔
1903
    , m_ssl_verify_callback{std::move(ssl_verify_callback)}               // DEPRECATED
1,328✔
1904
    , m_proxy_config{std::move(proxy_config)}                             // DEPRECATED
1,328✔
1905
    , m_reconnect_info{reconnect_info}
1,328✔
1906
    , m_ident{ident}
1,328✔
1907
    , m_server_endpoint{std::move(endpoint)}
1,328✔
1908
    , m_authorization_header_name{authorization_header_name} // DEPRECATED
1,328✔
1909
    , m_custom_http_headers{custom_http_headers}             // DEPRECATED
1,328✔
1910
{
2,780✔
1911
    m_on_idle = m_client.create_trigger([this](Status status) {
2,784✔
1912
        if (status == ErrorCodes::OperationAborted)
2,782✔
1913
            return;
×
1914
        else if (!status.is_ok())
2,782✔
1915
            throw Exception(status);
×
1916

1917
        REALM_ASSERT(m_activated);
2,782✔
1918
        if (m_state == ConnectionState::disconnected && m_num_active_sessions == 0) {
2,784✔
1919
            on_idle(); // Throws
2,774✔
1920
            // Connection object may be destroyed now.
1921
        }
2,774✔
1922
    });
2,782✔
1923
}
2,780✔
1924

1925
inline connection_ident_type ClientImpl::Connection::get_ident() const noexcept
1926
{
12✔
1927
    return m_ident;
12✔
1928
}
12✔
1929

1930

1931
inline const ServerEndpoint& ClientImpl::Connection::get_server_endpoint() const noexcept
1932
{
2,772✔
1933
    return m_server_endpoint;
2,772✔
1934
}
2,772✔
1935

1936
inline void ClientImpl::Connection::update_connect_info(const std::string& http_request_path_prefix,
1937
                                                        const std::string& signed_access_token)
1938
{
10,260✔
1939
    m_http_request_path_prefix = http_request_path_prefix; // Throws (copy)
10,260✔
1940
    m_signed_access_token = signed_access_token;           // Throws (copy)
10,260✔
1941
}
10,260✔
1942

1943

1944
void ClientImpl::Connection::resume_active_sessions()
1945
{
1,792✔
1946
    auto handler = [=](ClientImpl::Session& sess) {
3,580✔
1947
        sess.cancel_resumption_delay(); // Throws
3,580✔
1948
    };
3,580✔
1949
    for_each_active_session(std::move(handler)); // Throws
1,792✔
1950
}
1,792✔
1951

1952
void ClientImpl::Connection::on_idle()
1953
{
2,774✔
1954
    logger.debug(util::LogCategory::session, "Destroying connection object");
2,774✔
1955
    ClientImpl& client = get_client();
2,774✔
1956
    client.remove_connection(*this);
2,774✔
1957
    // NOTE: This connection object is now destroyed!
1958
}
2,774✔
1959

1960

1961
std::string ClientImpl::Connection::get_http_request_path() const
1962
{
3,696✔
1963
    using namespace std::string_view_literals;
3,696✔
1964
    const auto param = m_http_request_path_prefix.find('?') == std::string::npos ? "?baas_at="sv : "&baas_at="sv;
2,147,485,349✔
1965

1966
    std::string path;
3,696✔
1967
    path.reserve(m_http_request_path_prefix.size() + param.size() + m_signed_access_token.size());
3,696✔
1968
    path += m_http_request_path_prefix;
3,696✔
1969
    path += param;
3,696✔
1970
    path += m_signed_access_token;
3,696✔
1971

1972
    return path;
3,696✔
1973
}
3,696✔
1974

1975

1976
std::string ClientImpl::Connection::make_logger_prefix(connection_ident_type ident)
1977
{
2,780✔
1978
    return util::format("Connection[%1] ", ident);
2,780✔
1979
}
2,780✔
1980

1981

1982
void ClientImpl::Connection::report_connection_state_change(ConnectionState state,
1983
                                                            std::optional<SessionErrorInfo> error_info)
1984
{
10,882✔
1985
    if (m_force_closed) {
10,882✔
1986
        return;
2,408✔
1987
    }
2,408✔
1988
    auto handler = [=](ClientImpl::Session& sess) {
11,436✔
1989
        SessionImpl& sess_2 = static_cast<SessionImpl&>(sess);
11,436✔
1990
        sess_2.on_connection_state_changed(state, error_info); // Throws
11,436✔
1991
    };
11,436✔
1992
    for_each_active_session(std::move(handler)); // Throws
8,474✔
1993
}
8,474✔
1994

1995

1996
Client::Client(Config config)
1997
    : m_impl{new ClientImpl{std::move(config)}} // Throws
4,896✔
1998
{
9,930✔
1999
}
9,930✔
2000

2001

2002
Client::Client(Client&& client) noexcept
2003
    : m_impl{std::move(client.m_impl)}
2004
{
×
2005
}
×
2006

2007

2008
Client::~Client() noexcept {}
9,930✔
2009

2010

2011
void Client::shutdown() noexcept
2012
{
10,012✔
2013
    m_impl->shutdown();
10,012✔
2014
}
10,012✔
2015

2016
void Client::shutdown_and_wait()
2017
{
772✔
2018
    m_impl->shutdown_and_wait();
772✔
2019
}
772✔
2020

2021
void Client::cancel_reconnect_delay()
2022
{
1,796✔
2023
    m_impl->cancel_reconnect_delay();
1,796✔
2024
}
1,796✔
2025

2026
void Client::voluntary_disconnect_all_connections()
2027
{
12✔
2028
    m_impl->voluntary_disconnect_all_connections();
12✔
2029
}
12✔
2030

2031
bool Client::wait_for_session_terminations_or_client_stopped()
2032
{
9,528✔
2033
    return m_impl->wait_for_session_terminations_or_client_stopped();
9,528✔
2034
}
9,528✔
2035

2036
util::Future<void> Client::notify_session_terminated()
2037
{
56✔
2038
    return m_impl->notify_session_terminated();
56✔
2039
}
56✔
2040

2041
bool Client::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
2042
                                  port_type& port, std::string& path) const
2043
{
4,032✔
2044
    return m_impl->decompose_server_url(url, protocol, address, port, path); // Throws
4,032✔
2045
}
4,032✔
2046

2047

2048
Session::Session(Client& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
2049
                 std::shared_ptr<MigrationStore> migration_store, Config&& config)
2050
{
10,128✔
2051
    m_impl = new SessionWrapper{*client.m_impl, std::move(db), std::move(flx_sub_store), std::move(migration_store),
10,128✔
2052
                                std::move(config)}; // Throws
10,128✔
2053
}
10,128✔
2054

2055

2056
void Session::nonsync_transact_notify(version_type new_version)
2057
{
17,846✔
2058
    m_impl->on_commit(new_version); // Throws
17,846✔
2059
}
17,846✔
2060

2061

2062
void Session::cancel_reconnect_delay()
2063
{
28✔
2064
    m_impl->cancel_reconnect_delay(); // Throws
28✔
2065
}
28✔
2066

2067

2068
void Session::async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler handler)
2069
{
4,880✔
2070
    m_impl->async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws
4,880✔
2071
}
4,880✔
2072

2073

2074
bool Session::wait_for_upload_complete_or_client_stopped()
2075
{
12,908✔
2076
    return m_impl->wait_for_upload_complete_or_client_stopped(); // Throws
12,908✔
2077
}
12,908✔
2078

2079

2080
bool Session::wait_for_download_complete_or_client_stopped()
2081
{
9,996✔
2082
    return m_impl->wait_for_download_complete_or_client_stopped(); // Throws
9,996✔
2083
}
9,996✔
2084

2085

2086
void Session::refresh(std::string_view signed_access_token)
2087
{
216✔
2088
    m_impl->refresh(signed_access_token); // Throws
216✔
2089
}
216✔
2090

2091

2092
void Session::abandon() noexcept
2093
{
10,128✔
2094
    REALM_ASSERT(m_impl);
10,128✔
2095
    // Reabsorb the ownership assigned to the applications naked pointer by
2096
    // Session constructor
2097
    util::bind_ptr<SessionWrapper> wrapper{m_impl, util::bind_ptr_base::adopt_tag{}};
10,128✔
2098
    SessionWrapper::abandon(std::move(wrapper));
10,128✔
2099
}
10,128✔
2100

2101
util::Future<std::string> Session::send_test_command(std::string body)
2102
{
60✔
2103
    return m_impl->send_test_command(std::move(body));
60✔
2104
}
60✔
2105

2106
std::string Session::get_appservices_connection_id()
2107
{
72✔
2108
    return m_impl->get_appservices_connection_id();
72✔
2109
}
72✔
2110

2111
std::ostream& operator<<(std::ostream& os, ProxyConfig::Type proxyType)
2112
{
×
2113
    switch (proxyType) {
×
2114
        case ProxyConfig::Type::HTTP:
×
2115
            return os << "HTTP";
×
2116
        case ProxyConfig::Type::HTTPS:
×
2117
            return os << "HTTPS";
×
2118
    }
×
2119
    REALM_TERMINATE("Invalid Proxy Type object.");
2120
}
×
2121

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