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

realm / realm-core / thomas.goyne_484

05 Aug 2024 04:20PM UTC coverage: 91.097% (-0.01%) from 91.108%
thomas.goyne_484

Pull #7912

Evergreen

tgoyne
Extract some duplicated code for sync triggers and timers
Pull Request #7912: Extract some duplicated code for sync triggers and timers

102644 of 181486 branches covered (56.56%)

62 of 71 new or added lines in 6 files covered. (87.32%)

87 existing lines in 14 files now uncovered.

216695 of 237872 relevant lines covered (91.1%)

5798402.26 hits per line

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

91.33
/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
    // Can be called from any thread.
108
    std::string get_appservices_connection_id();
109

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

114
private:
115
    ClientImpl& m_client;
116
    DBRef m_db;
117
    Replication* m_replication;
118

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

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

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

144
    struct ReportedProgress {
145
        uint64_t snapshot;
146
        uint64_t uploaded;
147
        uint64_t uploadable;
148
        uint64_t downloaded;
149
        uint64_t downloadable;
150
        int64_t query_version = 0;
151
        double download_estimate;
152

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

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

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

171
    const SessionReason m_session_reason;
172

173
    // If false, QUERY and MARK messages are allowed but UPLOAD messages will not
174
    // be sent to the server.
175
    const bool m_allow_upload_messages;
176

177
    const uint64_t m_schema_version;
178

179
    std::shared_ptr<SubscriptionStore> m_flx_subscription_store;
180
    std::unique_ptr<PendingBootstrapStore> m_flx_pending_bootstrap_store;
181
    std::shared_ptr<MigrationStore> m_migration_store;
182

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

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

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

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

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

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

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

232
    version_type m_upload_completion_requested_version = -1;
233

234
    void on_download_completion();
235
    void on_suspended(const SessionErrorInfo& error_info);
236
    void on_resumed();
237
    void on_connection_state_changed(ConnectionState, const std::optional<SessionErrorInfo>&);
238
    void on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state);
239

240
    void init_progress_handler();
241
    void check_progress();
242
    void report_progress(ReportedProgress& p, DownloadableProgress downloadable);
243
    void report_upload_completion(version_type);
244

245
    friend class SessionWrapperStack;
246
    friend class ClientImpl::Session;
247
};
248

249

250
// ################ SessionWrapperStack ################
251

252
inline bool SessionWrapperStack::empty() const noexcept
253
{
19,932✔
254
    return !m_back;
19,932✔
255
}
19,932✔
256

257

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

265

266
inline util::bind_ptr<SessionWrapper> SessionWrapperStack::pop() noexcept
267
{
61,938✔
268
    util::bind_ptr<SessionWrapper> w{m_back, util::bind_ptr_base::adopt_tag{}};
61,938✔
269
    if (m_back) {
61,938✔
270
        m_back = m_back->m_next;
20,828✔
271
        w->m_next = nullptr;
20,828✔
272
    }
20,828✔
273
    return w;
61,938✔
274
}
61,938✔
275

276

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

285

286
inline bool SessionWrapperStack::erase(SessionWrapper* w) noexcept
287
{
10,478✔
288
    SessionWrapper** p = &m_back;
10,478✔
289
    while (*p && *p != w) {
10,660✔
290
        p = &(*p)->m_next;
182✔
291
    }
182✔
292
    if (!*p) {
10,478✔
293
        return false;
10,414✔
294
    }
10,414✔
295
    *p = w->m_next;
64✔
296
    util::bind_ptr<SessionWrapper>{w, util::bind_ptr_base::adopt_tag{}};
64✔
297
    return true;
64✔
298
}
10,478✔
299

300

301
SessionWrapperStack::~SessionWrapperStack()
302
{
19,932✔
303
    clear();
19,932✔
304
}
19,932✔
305

306

307
// ################ ClientImpl ################
308

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

314
    shutdown_and_wait();
9,966✔
315
    // Session wrappers are removed from m_unactualized_session_wrappers as they
316
    // are abandoned.
317
    REALM_ASSERT(m_stopped);
9,966✔
318
    REALM_ASSERT(m_unactualized_session_wrappers.empty());
9,966✔
319
    REALM_ASSERT(m_abandoned_session_wrappers.empty());
9,966✔
320
}
9,966✔
321

322

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

352

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

383

384
bool ClientImpl::wait_for_session_terminations_or_client_stopped()
385
{
9,640✔
386
    // Thread safety required
387

388
    {
9,640✔
389
        util::CheckedLockGuard lock{m_mutex};
9,640✔
390
        m_sessions_terminated = false;
9,640✔
391
    }
9,640✔
392

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

418
    bool completion_condition_was_satisfied;
9,640✔
419
    {
9,640✔
420
        util::CheckedUniqueLock lock{m_mutex};
9,640✔
421
        m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_mutex) {
19,276✔
422
            return m_sessions_terminated || m_stopped;
19,276✔
423
        });
19,276✔
424
        completion_condition_was_satisfied = !m_stopped;
9,640✔
425
    }
9,640✔
426
    return completion_condition_was_satisfied;
9,640✔
427
}
9,640✔
428

429

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

441
        promise.emplace_value();
56✔
442
    });
56✔
443

444
    return std::move(pf.future);
56✔
445
}
56✔
446

447
void ClientImpl::drain_connections_on_loop()
448
{
9,966✔
449
    post([this](Status status) {
9,966✔
450
        REALM_ASSERT(status.is_ok());
9,966✔
451
        drain_connections();
9,966✔
452
    });
9,966✔
453
}
9,966✔
454

455
void ClientImpl::shutdown_and_wait()
456
{
10,738✔
457
    shutdown();
10,738✔
458
    util::CheckedUniqueLock lock{m_drain_mutex};
10,738✔
459
    if (m_drained) {
10,738✔
460
        return;
772✔
461
    }
772✔
462

463
    logger.debug("Waiting for %1 connections to drain", m_num_connections);
9,966✔
464
    m_drain_cv.wait(lock.native_handle(), [&]() REQUIRES(m_drain_mutex) {
15,962✔
465
        return m_num_connections == 0 && m_outstanding_posts == 0;
15,962✔
466
    });
15,962✔
467

468
    m_drained = true;
9,966✔
469
}
9,966✔
470

471
void ClientImpl::shutdown() noexcept
472
{
20,786✔
473
    {
20,786✔
474
        util::CheckedLockGuard lock{m_mutex};
20,786✔
475
        if (m_stopped)
20,786✔
476
            return;
10,820✔
477
        m_stopped = true;
9,966✔
478
    }
9,966✔
479
    m_wait_or_client_stopped_cond.notify_all();
×
480

481
    drain_connections_on_loop();
9,966✔
482
}
9,966✔
483

484

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

497
        m_unactualized_session_wrappers.push(util::bind_ptr(wrapper));
10,482✔
498
    }
10,482✔
NEW
499
    m_actualize_and_finalize.trigger();
×
500
}
10,482✔
501

502

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

513
        // If the session wrapper has not yet been actualized (on the event loop
514
        // thread), it can be immediately finalized. This ensures that we will
515
        // generally not actualize a session wrapper that has already been
516
        // abandoned.
517
        if (m_unactualized_session_wrappers.erase(wrapper.get())) {
10,476✔
518
            wrapper->finalize_before_actualization();
64✔
519
            return;
64✔
520
        }
64✔
521
        m_abandoned_session_wrappers.push(std::move(wrapper));
10,412✔
522
    }
10,412✔
NEW
523
    m_actualize_and_finalize.trigger();
×
524
}
10,412✔
525

526

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

565

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

578
    // TODO: enable multiplexing with proxies
579
    if (server_slot.connection && !m_one_connection_per_session && !proxy_config) {
10,406✔
580
        // Use preexisting connection
581
        REALM_ASSERT(server_slot.alt_connections.empty());
7,572✔
582
        return *server_slot.connection;
7,572✔
583
    }
7,572✔
584

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

608

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

630
    bool notify;
2,836✔
631
    {
2,836✔
632
        util::CheckedLockGuard lk(m_drain_mutex);
2,836✔
633
        REALM_ASSERT(m_num_connections);
2,836✔
634
        notify = --m_num_connections <= 0;
2,836✔
635
    }
2,836✔
636
    if (notify) {
2,836✔
637
        m_drain_cv.notify_all();
2,212✔
638
    }
2,212✔
639
}
2,836✔
640

641

642
// ################ SessionImpl ################
643

644
void SessionImpl::force_close()
645
{
102✔
646
    // Allow force_close() if session is active or hasn't been activated yet.
647
    if (m_state == SessionImpl::Active || m_state == SessionImpl::Unactivated) {
102!
648
        m_wrapper.force_close();
102✔
649
    }
102✔
650
}
102✔
651

652
void SessionImpl::on_connection_state_changed(ConnectionState state,
653
                                              const std::optional<SessionErrorInfo>& error_info)
654
{
12,230✔
655
    // Only used to report errors back to the SyncSession while the Session is active
656
    if (m_state == SessionImpl::Active) {
12,230✔
657
        m_wrapper.on_connection_state_changed(state, error_info); // Throws
12,230✔
658
    }
12,230✔
659
}
12,230✔
660

661

662
const std::string& SessionImpl::get_virt_path() const noexcept
663
{
7,438✔
664
    // Can only be called if the session is active or being activated
665
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
7,438✔
666
    return m_wrapper.m_virt_path;
7,438✔
667
}
7,438✔
668

669
const std::string& SessionImpl::get_realm_path() const noexcept
670
{
10,752✔
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);
10,752✔
673
    return m_wrapper.m_db->get_path();
10,752✔
674
}
10,752✔
675

676
DBRef SessionImpl::get_db() const noexcept
677
{
26,508✔
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);
26,508!
680
    return m_wrapper.m_db;
26,508✔
681
}
26,508✔
682

683
ClientReplication& SessionImpl::get_repl() const noexcept
684
{
123,510✔
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);
123,510✔
687
    return m_wrapper.get_replication();
123,510✔
688
}
123,510✔
689

690
ClientHistory& SessionImpl::get_history() const noexcept
691
{
121,082✔
692
    return get_repl().get_history();
121,082✔
693
}
121,082✔
694

695
std::optional<ClientReset>& SessionImpl::get_client_reset_config() noexcept
696
{
104,472✔
697
    // Can only be called if the session is active or being activated
698
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
104,472✔
699
    return m_wrapper.m_client_reset_config;
104,472✔
700
}
104,472✔
701

702
SessionReason SessionImpl::get_session_reason() noexcept
703
{
1,894✔
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);
1,894!
706
    return m_wrapper.m_session_reason;
1,894✔
707
}
1,894✔
708

709
uint64_t SessionImpl::get_schema_version() noexcept
710
{
1,894✔
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,894!
713
    return m_wrapper.m_schema_version;
1,894✔
714
}
1,894✔
715

716
bool SessionImpl::upload_messages_allowed() noexcept
717
{
66,394✔
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);
66,394✔
720
    return m_wrapper.m_allow_upload_messages;
66,394✔
721
}
66,394✔
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,446✔
726
    // Ignore the call if the session is not active
727
    if (m_state != State::Active) {
45,446✔
728
        return;
×
729
    }
×
730

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

753

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

762

763
void SessionImpl::on_suspended(const SessionErrorInfo& error_info)
764
{
834✔
765
    // Ignore the call if the session is not active
766
    if (m_state == State::Active) {
834✔
767
        m_wrapper.on_suspended(error_info); // Throws
834✔
768
    }
834✔
769
}
834✔
770

771

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

780
void SessionImpl::handle_pending_client_reset_acknowledgement()
781
{
10,752✔
782
    // Ignore the call if the session is not active
783
    if (m_state == State::Active) {
10,752✔
784
        m_wrapper.handle_pending_client_reset_acknowledgement();
10,752✔
785
    }
10,752✔
786
}
10,752✔
787

788
bool SessionImpl::process_flx_bootstrap_message(const DownloadMessage& message)
789
{
49,400✔
790
    // Ignore the message if the session is not active or a steady state message
791
    if (m_state != State::Active || message.batch_state == DownloadBatchState::SteadyState) {
49,400✔
792
        return false;
45,444✔
793
    }
45,444✔
794

795
    REALM_ASSERT(m_is_flx_sync_session);
3,956✔
796

797
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
3,956✔
798
    std::optional<SyncProgress> maybe_progress;
3,956✔
799
    if (message.batch_state == DownloadBatchState::LastInBatch) {
3,956✔
800
        maybe_progress = message.progress;
2,404✔
801
    }
2,404✔
802

803
    try {
3,956✔
804
        bootstrap_store->add_batch(*message.query_version, maybe_progress, message.downloadable, message.changesets);
3,956✔
805
    }
3,956✔
806
    catch (const LogicError& ex) {
3,956✔
807
        if (ex.code() == ErrorCodes::LimitExceeded) {
×
808
            IntegrationException ex(ErrorCodes::LimitExceeded,
×
809
                                    "bootstrap changeset too large to store in pending bootstrap store",
×
810
                                    ProtocolError::bad_changeset_size);
×
811
            on_integration_failure(ex);
×
812
            return true;
×
813
        }
×
814
        throw;
×
815
    }
×
816

817
    auto hook_action = call_debug_hook(SyncClientHookEvent::BootstrapMessageProcessed, message.progress,
3,956✔
818
                                       *message.query_version, message.batch_state, message.changesets.size());
3,956✔
819
    if (hook_action == SyncClientHookAction::EarlyReturn) {
3,956✔
820
        return true;
12✔
821
    }
12✔
822
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
3,944✔
823

824
    if (message.batch_state == DownloadBatchState::MoreToCome) {
3,944✔
825
        return true;
1,548✔
826
    }
1,548✔
827

828
    try {
2,396✔
829
        process_pending_flx_bootstrap(); // throws
2,396✔
830
    }
2,396✔
831
    catch (const IntegrationException& e) {
2,396✔
832
        on_integration_failure(e);
12✔
833
    }
12✔
834
    catch (...) {
2,396✔
835
        on_integration_failure(IntegrationException(exception_to_status()));
×
836
    }
×
837

838
    return true;
2,396✔
839
}
2,396✔
840

841

842
void SessionImpl::process_pending_flx_bootstrap()
843
{
12,976✔
844
    // Ignore the call if not a flx session or session is not active
845
    if (!m_is_flx_sync_session || m_state != State::Active) {
12,976✔
846
        return;
8,618✔
847
    }
8,618✔
848
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
4,358✔
849
    if (!bootstrap_store->has_pending()) {
4,358✔
850
        return;
1,932✔
851
    }
1,932✔
852

853
    auto pending_batch_stats = bootstrap_store->pending_stats();
2,426✔
854
    logger.info("Begin processing pending FLX bootstrap for query version %1. (changesets: %2, original total "
2,426✔
855
                "changeset size: %3)",
2,426✔
856
                pending_batch_stats.query_version, pending_batch_stats.pending_changesets,
2,426✔
857
                pending_batch_stats.pending_changeset_bytes);
2,426✔
858
    auto& history = get_repl().get_history();
2,426✔
859
    VersionInfo new_version;
2,426✔
860
    SyncProgress progress;
2,426✔
861
    int64_t query_version = -1;
2,426✔
862
    size_t changesets_processed = 0;
2,426✔
863

864
    // Used to commit each batch after it was transformed.
865
    TransactionRef transact = get_db()->start_write();
2,426✔
866
    while (bootstrap_store->has_pending()) {
5,138✔
867
        auto start_time = std::chrono::steady_clock::now();
2,736✔
868
        auto pending_batch = bootstrap_store->peek_pending(*transact, m_wrapper.m_flx_bootstrap_batch_size_bytes);
2,736✔
869
        if (!pending_batch.progress) {
2,736✔
870
            logger.info("Incomplete pending bootstrap found for query version %1", pending_batch.query_version);
20✔
871
            bootstrap_store->clear(*transact, pending_batch.query_version);
20✔
872
            transact->commit();
20✔
873
            return;
20✔
874
        }
20✔
875

876
        auto batch_state =
2,716✔
877
            pending_batch.remaining_changesets > 0 ? DownloadBatchState::MoreToCome : DownloadBatchState::LastInBatch;
2,716✔
878
        query_version = pending_batch.query_version;
2,716✔
879
        bool simulate_integration_error =
2,716✔
880
            (m_wrapper.m_simulate_integration_error && !pending_batch.changesets.empty());
2,716✔
881
        if (simulate_integration_error) {
2,716✔
882
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
4✔
883
        }
4✔
884

885
        call_debug_hook(SyncClientHookEvent::BootstrapBatchAboutToProcess, *pending_batch.progress, query_version,
2,712✔
886
                        batch_state, pending_batch.changesets.size());
2,712✔
887

888
        history.integrate_server_changesets(
2,712✔
889
            *pending_batch.progress, 1.0, pending_batch.changesets, new_version, batch_state, logger, transact,
2,712✔
890
            [&](const Transaction& tr, util::Span<Changeset> changesets_applied) {
2,712✔
891
                REALM_ASSERT_3(changesets_applied.size(), <=, pending_batch.changesets.size());
2,700✔
892
                bootstrap_store->pop_front_pending(tr, changesets_applied.size());
2,700✔
893
            });
2,700✔
894
        progress = *pending_batch.progress;
2,712✔
895
        changesets_processed += pending_batch.changesets.size();
2,712✔
896
        auto duration = std::chrono::steady_clock::now() - start_time;
2,712✔
897

898
        auto action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
2,712✔
899
                                      batch_state, pending_batch.changesets.size());
2,712✔
900
        REALM_ASSERT_EX(action == SyncClientHookAction::NoAction, action);
2,712✔
901

902
        logger.info("Integrated %1 changesets from pending bootstrap for query version %2, producing client version "
2,712✔
903
                    "%3 in %4 ms. %5 changesets remaining in bootstrap",
2,712✔
904
                    pending_batch.changesets.size(), pending_batch.query_version, new_version.realm_version,
2,712✔
905
                    std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(),
2,712✔
906
                    pending_batch.remaining_changesets);
2,712✔
907
    }
2,712✔
908

909
    REALM_ASSERT_3(query_version, !=, -1);
2,402✔
910

911
    on_changesets_integrated(new_version.realm_version, progress);
2,402✔
912
    auto action = call_debug_hook(SyncClientHookEvent::BootstrapProcessed, progress, query_version,
2,402✔
913
                                  DownloadBatchState::LastInBatch, changesets_processed);
2,402✔
914
    // NoAction/EarlyReturn are both valid no-op actions to take here.
915
    REALM_ASSERT_EX(action == SyncClientHookAction::NoAction || action == SyncClientHookAction::EarlyReturn, action);
2,402✔
916
}
2,402✔
917

918
void SessionImpl::on_flx_sync_error(int64_t version, std::string_view err_msg)
919
{
20✔
920
    // Ignore the call if the session is not active
921
    if (m_state == State::Active) {
20✔
922
        get_flx_subscription_store()->set_error(version, err_msg);
20✔
923
    }
20✔
924
}
20✔
925

926
SubscriptionStore* SessionImpl::get_flx_subscription_store()
927
{
25,378✔
928
    // Should never be called if session is not active
929
    REALM_ASSERT_EX(m_state == State::Active, m_state);
25,378✔
930
    return m_wrapper.get_flx_subscription_store();
25,378✔
931
}
25,378✔
932

933
MigrationStore* SessionImpl::get_migration_store()
934
{
74,892✔
935
    // Should never be called if session is not active
936
    REALM_ASSERT_EX(m_state == State::Active, m_state);
74,892✔
937
    return m_wrapper.get_migration_store();
74,892✔
938
}
74,892✔
939

940
SyncClientHookAction SessionImpl::call_debug_hook(const SyncClientHookData& data)
941
{
15,662✔
942
    // Should never be called if session is not active
943
    REALM_ASSERT_EX(m_state == State::Active, m_state);
15,662✔
944

945
    // Make sure we don't call the debug hook recursively.
946
    if (m_wrapper.m_in_debug_hook) {
15,662✔
947
        return SyncClientHookAction::NoAction;
24✔
948
    }
24✔
949
    m_wrapper.m_in_debug_hook = true;
15,638✔
950
    auto in_hook_guard = util::make_scope_exit([&]() noexcept {
15,638✔
951
        m_wrapper.m_in_debug_hook = false;
15,638✔
952
    });
15,638✔
953

954
    auto action = m_wrapper.m_debug_hook(data);
15,638✔
955
    switch (action) {
15,638✔
956
        case realm::SyncClientHookAction::SuspendWithRetryableError: {
12✔
957
            SessionErrorInfo err_info(Status{ErrorCodes::RuntimeError, "hook requested error"}, IsFatal{false});
12✔
958
            err_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
12✔
959

960
            auto err_processing_err = receive_error_message(err_info);
12✔
961
            REALM_ASSERT_EX(err_processing_err.is_ok(), err_processing_err);
12✔
962
            return SyncClientHookAction::EarlyReturn;
12✔
963
        }
×
964
        case realm::SyncClientHookAction::TriggerReconnect: {
24✔
965
            get_connection().voluntary_disconnect();
24✔
966
            return SyncClientHookAction::EarlyReturn;
24✔
967
        }
×
968
        default:
15,594✔
969
            return action;
15,594✔
970
    }
15,638✔
971
}
15,638✔
972

973
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const SyncProgress& progress,
974
                                                  int64_t query_version, DownloadBatchState batch_state,
975
                                                  size_t num_changesets)
976
{
106,628✔
977
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
106,628✔
978
        return SyncClientHookAction::NoAction;
97,702✔
979
    }
97,702✔
980
    if (REALM_UNLIKELY(m_state != State::Active)) {
8,926✔
981
        return SyncClientHookAction::NoAction;
×
982
    }
×
983

984
    SyncClientHookData data;
8,926✔
985
    data.event = event;
8,926✔
986
    data.batch_state = batch_state;
8,926✔
987
    data.progress = progress;
8,926✔
988
    data.num_changesets = num_changesets;
8,926✔
989
    data.query_version = query_version;
8,926✔
990

991
    return call_debug_hook(data);
8,926✔
992
}
8,926✔
993

994
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const ProtocolErrorInfo* error_info)
995
{
97,270✔
996
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
97,270✔
997
        return SyncClientHookAction::NoAction;
90,532✔
998
    }
90,532✔
999
    if (REALM_UNLIKELY(m_state != State::Active)) {
6,738✔
1000
        return SyncClientHookAction::NoAction;
×
1001
    }
×
1002

1003
    SyncClientHookData data;
6,738✔
1004
    data.event = event;
6,738✔
1005
    data.batch_state = DownloadBatchState::SteadyState;
6,738✔
1006
    data.progress = m_progress;
6,738✔
1007
    data.num_changesets = 0;
6,738✔
1008
    data.query_version = m_last_sent_flx_query_version;
6,738✔
1009
    data.error_info = error_info;
6,738✔
1010

1011
    return call_debug_hook(data);
6,738✔
1012
}
6,738✔
1013

1014
void SessionImpl::init_progress_handler()
1015
{
10,754✔
1016
    REALM_ASSERT_EX(m_state == State::Unactivated || m_state == State::Active, m_state);
10,754✔
1017
    m_wrapper.init_progress_handler();
10,754✔
1018
}
10,754✔
1019

1020
void SessionImpl::enable_progress_notifications()
1021
{
47,472✔
1022
    m_wrapper.m_reliable_download_progress = true;
47,472✔
1023
}
47,472✔
1024

1025
util::Future<std::string> SessionImpl::send_test_command(std::string body)
1026
{
72✔
1027
    if (m_state != State::Active) {
72✔
1028
        return Status{ErrorCodes::RuntimeError, "Cannot send a test command for a session that is not active"};
×
1029
    }
×
1030

1031
    try {
72✔
1032
        auto json_body = nlohmann::json::parse(body.begin(), body.end());
72✔
1033
        if (auto it = json_body.find("command"); it == json_body.end() || !it->is_string()) {
72✔
1034
            return Status{ErrorCodes::LogicError,
4✔
1035
                          "Must supply command name in \"command\" field of test command json object"};
4✔
1036
        }
4✔
1037
        if (json_body.size() > 1 && json_body.find("args") == json_body.end()) {
68✔
1038
            return Status{ErrorCodes::LogicError, "Only valid fields in a test command are \"command\" and \"args\""};
×
1039
        }
×
1040
    }
68✔
1041
    catch (const nlohmann::json::parse_error& e) {
72✔
1042
        return Status{ErrorCodes::LogicError, util::format("Invalid json input to send_test_command: %1", e.what())};
4✔
1043
    }
4✔
1044

1045
    auto pf = util::make_promise_future<std::string>();
64✔
1046
    get_client().post([this, promise = std::move(pf.promise), body = std::move(body)](Status status) mutable {
64✔
1047
        // Includes operation_aborted
1048
        if (!status.is_ok()) {
64✔
1049
            promise.set_error(status);
×
1050
            return;
×
1051
        }
×
1052

1053
        auto id = ++m_last_pending_test_command_ident;
64✔
1054
        m_pending_test_commands.push_back(PendingTestCommand{id, std::move(body), std::move(promise)});
64✔
1055
        ensure_enlisted_to_send();
64✔
1056
    });
64✔
1057

1058
    return std::move(pf.future);
64✔
1059
}
72✔
1060

1061
// ################ SessionWrapper ################
1062

1063
// The SessionWrapper class is held by a sync::Session (which is owned by the SyncSession instance) and
1064
// provides a link to the ClientImpl::Session that creates and receives messages with the server with
1065
// the ClientImpl::Connection that owns the ClientImpl::Session.
1066
SessionWrapper::SessionWrapper(ClientImpl& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1067
                               std::shared_ptr<MigrationStore> migration_store, Session::Config&& config)
1068
    : m_client{client}
5,068✔
1069
    , m_db(std::move(db))
5,068✔
1070
    , m_replication(m_db->get_replication())
5,068✔
1071
    , m_protocol_envelope{config.protocol_envelope}
5,068✔
1072
    , m_server_address{std::move(config.server_address)}
5,068✔
1073
    , m_server_port{config.server_port}
5,068✔
1074
    , m_server_verified{config.server_verified}
5,068✔
1075
    , m_user_id(std::move(config.user_id))
5,068✔
1076
    , m_sync_mode(flx_sub_store ? SyncServerMode::FLX : SyncServerMode::PBS)
5,068✔
1077
    , m_authorization_header_name{config.authorization_header_name}
5,068✔
1078
    , m_custom_http_headers{std::move(config.custom_http_headers)}
5,068✔
1079
    , m_verify_servers_ssl_certificate{config.verify_servers_ssl_certificate}
5,068✔
1080
    , m_simulate_integration_error{config.simulate_integration_error}
5,068✔
1081
    , m_ssl_trust_certificate_path{std::move(config.ssl_trust_certificate_path)}
5,068✔
1082
    , m_ssl_verify_callback{std::move(config.ssl_verify_callback)}
5,068✔
1083
    , m_flx_bootstrap_batch_size_bytes(config.flx_bootstrap_batch_size_bytes)
5,068✔
1084
    , m_http_request_path_prefix{std::move(config.service_identifier)}
5,068✔
1085
    , m_virt_path{std::move(config.realm_identifier)}
5,068✔
1086
    , m_proxy_config{std::move(config.proxy_config)}
5,068✔
1087
    , m_signed_access_token{std::move(config.signed_user_token)}
5,068✔
1088
    , m_client_reset_config{std::move(config.client_reset_config)}
5,068✔
1089
    , m_progress_handler(std::move(config.progress_handler))
5,068✔
1090
    , m_connection_state_change_listener(std::move(config.connection_state_change_listener))
5,068✔
1091
    , m_debug_hook(std::move(config.on_sync_client_event_hook))
5,068✔
1092
    , m_session_reason(m_client_reset_config || config.fresh_realm_download ? SessionReason::ClientReset
5,068✔
1093
                                                                            : SessionReason::Sync)
5,068✔
1094
    , m_allow_upload_messages(!config.fresh_realm_download)
5,068✔
1095
    , m_schema_version(config.schema_version)
5,068✔
1096
    , m_flx_subscription_store(std::move(flx_sub_store))
5,068✔
1097
    , m_migration_store(std::move(migration_store))
5,068✔
1098
{
10,478✔
1099
    REALM_ASSERT(m_db);
10,478✔
1100
    REALM_ASSERT(m_db->get_replication());
10,478✔
1101
    REALM_ASSERT(dynamic_cast<ClientReplication*>(m_db->get_replication()));
10,478✔
1102

1103
    // SessionWrapper begins at +1 retain count because Client retains and
1104
    // releases it while performing async operations, and these need to not
1105
    // take it to 0 or it could be deleted before the caller can retain it.
1106
    bind_ptr();
10,478✔
1107
    m_client.register_unactualized_session_wrapper(this);
10,478✔
1108
}
10,478✔
1109

1110
SessionWrapper::~SessionWrapper() noexcept
1111
{
10,482✔
1112
    // We begin actualization in the constructor and do not delete the wrapper
1113
    // until both the Client is done with it and the Session has abandoned it,
1114
    // so at this point we must have actualized, finalized, and been abandoned.
1115
    REALM_ASSERT(m_actualized);
10,482✔
1116
    REALM_ASSERT(m_abandoned);
10,482✔
1117
    REALM_ASSERT(m_finalized);
10,482✔
1118
    REALM_ASSERT(m_closed);
10,482✔
1119
    REALM_ASSERT(!m_db);
10,482✔
1120
}
10,482✔
1121

1122

1123
inline ClientReplication& SessionWrapper::get_replication() noexcept
1124
{
123,512✔
1125
    REALM_ASSERT(m_db);
123,512✔
1126
    return static_cast<ClientReplication&>(*m_replication);
123,512✔
1127
}
123,512✔
1128

1129

1130
inline ClientImpl& SessionWrapper::get_client() noexcept
1131
{
×
1132
    return m_client;
×
1133
}
×
1134

1135
bool SessionWrapper::has_flx_subscription_store() const
1136
{
×
1137
    return static_cast<bool>(m_flx_subscription_store);
×
1138
}
×
1139

1140
SubscriptionStore* SessionWrapper::get_flx_subscription_store()
1141
{
25,378✔
1142
    REALM_ASSERT(!m_finalized);
25,378✔
1143
    return m_flx_subscription_store.get();
25,378✔
1144
}
25,378✔
1145

1146
PendingBootstrapStore* SessionWrapper::get_flx_pending_bootstrap_store()
1147
{
8,316✔
1148
    REALM_ASSERT(!m_finalized);
8,316✔
1149
    return m_flx_pending_bootstrap_store.get();
8,316✔
1150
}
8,316✔
1151

1152
MigrationStore* SessionWrapper::get_migration_store()
1153
{
74,892✔
1154
    REALM_ASSERT(!m_finalized);
74,892✔
1155
    return m_migration_store.get();
74,892✔
1156
}
74,892✔
1157

1158
inline bool SessionWrapper::mark_abandoned()
1159
{
10,482✔
1160
    REALM_ASSERT(!m_abandoned);
10,482✔
1161
    m_abandoned = true;
10,482✔
1162
    return m_finalized;
10,482✔
1163
}
10,482✔
1164

1165

1166
void SessionWrapper::on_commit(version_type new_version)
1167
{
119,022✔
1168
    // Thread safety required
1169
    m_client.post([self = util::bind_ptr{this}, new_version] {
119,022✔
1170
        REALM_ASSERT(self->m_actualized);
119,022✔
1171
        if (REALM_UNLIKELY(!self->m_sess))
119,022✔
1172
            return; // Already finalized
474✔
1173
        SessionImpl& sess = *self->m_sess;
118,548✔
1174
        sess.recognize_sync_version(new_version); // Throws
118,548✔
1175
        self->check_progress();                   // Throws
118,548✔
1176
    });
118,548✔
1177
}
119,022✔
1178

1179

1180
void SessionWrapper::cancel_reconnect_delay()
1181
{
32✔
1182
    // Thread safety required
1183

1184
    m_client.post([self = util::bind_ptr{this}] {
32✔
1185
        REALM_ASSERT(self->m_actualized);
32✔
1186
        if (REALM_UNLIKELY(self->m_closed)) {
32✔
1187
            return;
×
1188
        }
×
1189

1190
        if (REALM_UNLIKELY(!self->m_sess))
32✔
1191
            return; // Already finalized
×
1192
        SessionImpl& sess = *self->m_sess;
32✔
1193
        sess.cancel_resumption_delay(); // Throws
32✔
1194
        ClientImpl::Connection& conn = sess.get_connection();
32✔
1195
        conn.cancel_reconnect_delay(); // Throws
32✔
1196
    });                                // Throws
32✔
1197
}
32✔
1198

1199
void SessionWrapper::async_wait_for(bool upload_completion, bool download_completion,
1200
                                    WaitOperCompletionHandler handler)
1201
{
28,724✔
1202
    REALM_ASSERT(upload_completion || download_completion);
28,724✔
1203

1204
    m_client.post([self = util::bind_ptr{this}, handler = std::move(handler), upload_completion,
28,724✔
1205
                   download_completion](Status status) mutable {
28,724✔
1206
        REALM_ASSERT(self->m_actualized);
28,724✔
1207
        if (!status.is_ok()) {
28,724✔
1208
            handler(status); // Throws
×
1209
            return;
×
1210
        }
×
1211
        if (REALM_UNLIKELY(!self->m_sess)) {
28,724✔
1212
            // Already finalized
1213
            handler({ErrorCodes::OperationAborted, "Session finalized before callback could run"}); // Throws
186✔
1214
            return;
186✔
1215
        }
186✔
1216
        if (upload_completion) {
28,538✔
1217
            self->m_upload_completion_requested_version = self->m_db->get_version_of_latest_snapshot();
15,656✔
1218
            if (download_completion) {
15,656✔
1219
                // Wait for upload and download completion
1220
                self->m_sync_completion_handlers.push_back(std::move(handler)); // Throws
364✔
1221
            }
364✔
1222
            else {
15,292✔
1223
                // Wait for upload completion only
1224
                self->m_upload_completion_handlers.push_back(std::move(handler)); // Throws
15,292✔
1225
            }
15,292✔
1226
        }
15,656✔
1227
        else {
12,882✔
1228
            // Wait for download completion only
1229
            self->m_download_completion_handlers.push_back(std::move(handler)); // Throws
12,882✔
1230
        }
12,882✔
1231
        SessionImpl& sess = *self->m_sess;
28,538✔
1232
        if (upload_completion)
28,538✔
1233
            self->check_progress();
15,656✔
1234
        if (download_completion)
28,538✔
1235
            sess.request_download_completion_notification(); // Throws
13,246✔
1236
    });                                                      // Throws
28,538✔
1237
}
28,724✔
1238

1239

1240
bool SessionWrapper::wait_for_upload_complete_or_client_stopped()
1241
{
12,912✔
1242
    // Thread safety required
1243
    REALM_ASSERT(!m_abandoned);
12,912✔
1244

1245
    auto pf = util::make_promise_future<bool>();
12,912✔
1246
    async_wait_for(true, false, [promise = std::move(pf.promise)](Status status) mutable {
12,912✔
1247
        promise.emplace_value(status.is_ok());
12,912✔
1248
    });
12,912✔
1249
    return pf.future.get();
12,912✔
1250
}
12,912✔
1251

1252

1253
bool SessionWrapper::wait_for_download_complete_or_client_stopped()
1254
{
10,004✔
1255
    // Thread safety required
1256
    REALM_ASSERT(!m_abandoned);
10,004✔
1257

1258
    auto pf = util::make_promise_future<bool>();
10,004✔
1259
    async_wait_for(false, true, [promise = std::move(pf.promise)](Status status) mutable {
10,004✔
1260
        promise.emplace_value(status.is_ok());
10,004✔
1261
    });
10,004✔
1262
    return pf.future.get();
10,004✔
1263
}
10,004✔
1264

1265

1266
void SessionWrapper::refresh(std::string_view signed_access_token)
1267
{
218✔
1268
    // Thread safety required
1269
    REALM_ASSERT(!m_abandoned);
218✔
1270

1271
    m_client.post([self = util::bind_ptr{this}, token = std::string(signed_access_token)] {
218✔
1272
        REALM_ASSERT(self->m_actualized);
218✔
1273
        if (REALM_UNLIKELY(!self->m_sess))
218✔
1274
            return; // Already finalized
×
1275
        self->m_signed_access_token = std::move(token);
218✔
1276
        SessionImpl& sess = *self->m_sess;
218✔
1277
        ClientImpl::Connection& conn = sess.get_connection();
218✔
1278
        // FIXME: This only makes sense when each session uses a separate connection.
1279
        conn.update_connect_info(self->m_http_request_path_prefix, self->m_signed_access_token); // Throws
218✔
1280
        sess.cancel_resumption_delay();                                                          // Throws
218✔
1281
        conn.cancel_reconnect_delay();                                                           // Throws
218✔
1282
    });
218✔
1283
}
218✔
1284

1285

1286
void SessionWrapper::abandon(util::bind_ptr<SessionWrapper> wrapper) noexcept
1287
{
10,482✔
1288
    ClientImpl& client = wrapper->m_client;
10,482✔
1289
    client.register_abandoned_session_wrapper(std::move(wrapper));
10,482✔
1290
}
10,482✔
1291

1292

1293
// Must be called from event loop thread
1294
void SessionWrapper::actualize()
1295
{
10,412✔
1296
    // actualize() can only ever be called once
1297
    REALM_ASSERT(!m_actualized);
10,412✔
1298
    REALM_ASSERT(!m_sess);
10,412✔
1299
    // The client should have removed this wrapper from those pending
1300
    // actualization if it called force_close() or finalize_before_actualize()
1301
    REALM_ASSERT(!m_finalized);
10,412✔
1302
    REALM_ASSERT(!m_closed);
10,412✔
1303

1304
    m_actualized = true;
10,412✔
1305

1306
    ScopeExitFail close_on_error([&]() noexcept {
10,412✔
1307
        m_closed = true;
4✔
1308
    });
4✔
1309

1310
    m_db->claim_sync_agent();
10,412✔
1311
    m_db->add_commit_listener(this);
10,412✔
1312
    ScopeExitFail remove_commit_listener([&]() noexcept {
10,412✔
1313
        m_db->remove_commit_listener(this);
×
1314
    });
×
1315

1316
    ServerEndpoint endpoint{m_protocol_envelope, m_server_address, m_server_port,
10,412✔
1317
                            m_user_id,           m_sync_mode,      m_server_verified};
10,412✔
1318
    bool was_created = false;
10,412✔
1319
    ClientImpl::Connection& conn = m_client.get_connection(
10,412✔
1320
        std::move(endpoint), m_authorization_header_name, m_custom_http_headers, m_verify_servers_ssl_certificate,
10,412✔
1321
        m_ssl_trust_certificate_path, m_ssl_verify_callback, m_proxy_config,
10,412✔
1322
        was_created); // Throws
10,412✔
1323
    ScopeExitFail remove_connection([&]() noexcept {
10,412✔
1324
        if (was_created)
×
1325
            m_client.remove_connection(conn);
×
1326
    });
×
1327

1328
    // FIXME: This only makes sense when each session uses a separate connection.
1329
    conn.update_connect_info(m_http_request_path_prefix, m_signed_access_token);    // Throws
10,412✔
1330
    std::unique_ptr<SessionImpl> sess = std::make_unique<SessionImpl>(*this, conn); // Throws
10,412✔
1331
    if (m_sync_mode == SyncServerMode::FLX) {
10,412✔
1332
        m_flx_pending_bootstrap_store =
1,806✔
1333
            std::make_unique<PendingBootstrapStore>(m_db, sess->logger, m_flx_subscription_store);
1,806✔
1334
    }
1,806✔
1335

1336
    sess->logger.info("Binding '%1' to '%2'", m_db->get_path(), m_virt_path); // Throws
10,412✔
1337
    m_sess = sess.get();
10,412✔
1338
    ScopeExitFail clear_sess([&]() noexcept {
10,412✔
1339
        m_sess = nullptr;
×
1340
    });
×
1341
    conn.activate_session(std::move(sess)); // Throws
10,412✔
1342

1343
    if (was_created)
10,412✔
1344
        conn.activate(); // Throws
2,838✔
1345

1346
    if (m_connection_state_change_listener) {
10,412✔
1347
        ConnectionState state = conn.get_state();
10,400✔
1348
        if (state != ConnectionState::disconnected) {
10,400✔
1349
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,410✔
1350
            if (state == ConnectionState::connected)
7,410✔
1351
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
7,288✔
1352
        }
7,410✔
1353
    }
10,400✔
1354

1355
    if (!m_client_reset_config)
10,412✔
1356
        check_progress(); // Throws
9,982✔
1357
}
10,412✔
1358

1359
void SessionWrapper::force_close()
1360
{
10,516✔
1361
    if (m_closed) {
10,516✔
1362
        return;
106✔
1363
    }
106✔
1364
    REALM_ASSERT(m_actualized);
10,410✔
1365
    REALM_ASSERT(m_sess);
10,410✔
1366
    m_closed = true;
10,410✔
1367

1368
    ClientImpl::Connection& conn = m_sess->get_connection();
10,410✔
1369
    conn.initiate_session_deactivation(m_sess); // Throws
10,410✔
1370

1371
    // We need to keep the DB open until finalization, but we no longer want to
1372
    // know when commits are made
1373
    m_db->remove_commit_listener(this);
10,410✔
1374

1375
    // Delete the pending bootstrap store since it uses a reference to the logger in m_sess
1376
    m_flx_pending_bootstrap_store.reset();
10,410✔
1377
    // Clear the subscription and migration store refs since they are owned by SyncSession
1378
    m_flx_subscription_store.reset();
10,410✔
1379
    m_migration_store.reset();
10,410✔
1380
    m_sess = nullptr;
10,410✔
1381
    // Everything is being torn down, no need to report connection state anymore
1382
    m_connection_state_change_listener = {};
10,410✔
1383

1384
    // All outstanding wait operations must be canceled
1385
    while (!m_upload_completion_handlers.empty()) {
10,774✔
1386
        auto handler = std::move(m_upload_completion_handlers.back());
364✔
1387
        m_upload_completion_handlers.pop_back();
364✔
1388
        handler({ErrorCodes::OperationAborted, "Sync session is being closed before upload was complete"}); // Throws
364✔
1389
    }
364✔
1390
    while (!m_download_completion_handlers.empty()) {
10,810✔
1391
        auto handler = std::move(m_download_completion_handlers.back());
400✔
1392
        m_download_completion_handlers.pop_back();
400✔
1393
        handler(
400✔
1394
            {ErrorCodes::OperationAborted, "Sync session is being closed before download was complete"}); // Throws
400✔
1395
    }
400✔
1396
    while (!m_sync_completion_handlers.empty()) {
10,422✔
1397
        auto handler = std::move(m_sync_completion_handlers.back());
12✔
1398
        m_sync_completion_handlers.pop_back();
12✔
1399
        handler({ErrorCodes::OperationAborted, "Sync session is being closed before sync was complete"}); // Throws
12✔
1400
    }
12✔
1401
}
10,410✔
1402

1403
// Must be called from event loop thread
1404
//
1405
// `m_client.m_mutex` is not held while this is called, but it is guaranteed to
1406
// have been acquired at some point in between the final read or write ever made
1407
// from a different thread and when this is called.
1408
void SessionWrapper::finalize()
1409
{
10,414✔
1410
    REALM_ASSERT(m_actualized);
10,414✔
1411
    REALM_ASSERT(m_abandoned);
10,414✔
1412
    REALM_ASSERT(!m_finalized);
10,414✔
1413

1414
    force_close();
10,414✔
1415

1416
    m_finalized = true;
10,414✔
1417

1418
    // The Realm file can be closed now, as no access to the Realm file is
1419
    // supposed to happen on behalf of a session after initiation of
1420
    // deactivation.
1421
    m_db->release_sync_agent();
10,414✔
1422
    m_db = nullptr;
10,414✔
1423
}
10,414✔
1424

1425

1426
// Must be called only when an unactualized session wrapper becomes abandoned.
1427
//
1428
// Called with a lock on `m_client.m_mutex`.
1429
inline void SessionWrapper::finalize_before_actualization() noexcept
1430
{
68✔
1431
    REALM_ASSERT(!m_finalized);
68✔
1432
    REALM_ASSERT(!m_sess);
68✔
1433
    m_actualized = true;
68✔
1434
    m_finalized = true;
68✔
1435
    m_closed = true;
68✔
1436
    m_db->remove_commit_listener(this);
68✔
1437
    m_db->release_sync_agent();
68✔
1438
    m_db = nullptr;
68✔
1439
}
68✔
1440

1441
void SessionWrapper::on_download_completion()
1442
{
16,840✔
1443
    // Ensure that progress handlers get called before completion handlers. The
1444
    // download completing performed a commit and will trigger progress
1445
    // notifications asynchronously, but they would arrive after the download
1446
    // completion without this.
1447
    check_progress();
16,840✔
1448

1449
    if (m_flx_subscription_store) {
16,840✔
1450
        m_flx_subscription_store->download_complete();
2,988✔
1451
    }
2,988✔
1452

1453
    while (!m_download_completion_handlers.empty()) {
29,578✔
1454
        auto handler = std::move(m_download_completion_handlers.back());
12,738✔
1455
        m_download_completion_handlers.pop_back();
12,738✔
1456
        handler(Status::OK()); // Throws
12,738✔
1457
    }
12,738✔
1458
    while (!m_sync_completion_handlers.empty()) {
16,936✔
1459
        auto handler = std::move(m_sync_completion_handlers.back());
96✔
1460
        m_upload_completion_handlers.push_back(std::move(handler)); // Throws
96✔
1461
        m_sync_completion_handlers.pop_back();
96✔
1462
    }
96✔
1463
}
16,840✔
1464

1465

1466
void SessionWrapper::on_suspended(const SessionErrorInfo& error_info)
1467
{
834✔
1468
    REALM_ASSERT(!m_finalized);
834✔
1469
    m_suspended = true;
834✔
1470
    if (m_connection_state_change_listener) {
834✔
1471
        m_connection_state_change_listener(ConnectionState::disconnected, error_info); // Throws
834✔
1472
    }
834✔
1473
}
834✔
1474

1475

1476
void SessionWrapper::on_resumed()
1477
{
174✔
1478
    REALM_ASSERT(!m_finalized);
174✔
1479
    m_suspended = false;
174✔
1480
    if (m_connection_state_change_listener) {
174✔
1481
        ClientImpl::Connection& conn = m_sess->get_connection();
174✔
1482
        if (conn.get_state() != ConnectionState::disconnected) {
174✔
1483
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
162✔
1484
            if (conn.get_state() == ConnectionState::connected)
162✔
1485
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
152✔
1486
        }
162✔
1487
    }
174✔
1488
}
174✔
1489

1490

1491
void SessionWrapper::on_connection_state_changed(ConnectionState state,
1492
                                                 const std::optional<SessionErrorInfo>& error_info)
1493
{
12,230✔
1494
    if (m_connection_state_change_listener && !m_suspended) {
12,230✔
1495
        m_connection_state_change_listener(state, error_info); // Throws
12,170✔
1496
    }
12,170✔
1497
}
12,230✔
1498

1499
void SessionWrapper::init_progress_handler()
1500
{
10,754✔
1501
    ClientHistory::get_upload_download_state(m_db.get(), m_final_downloaded, m_final_uploaded);
10,754✔
1502
}
10,754✔
1503

1504
void SessionWrapper::check_progress()
1505
{
161,020✔
1506
    REALM_ASSERT(!m_finalized);
161,020✔
1507
    REALM_ASSERT(m_sess);
161,020✔
1508

1509
    // Check if there's anything which even wants progress or completion information
1510
    bool has_progress_handler = m_progress_handler && m_reliable_download_progress;
161,020✔
1511
    bool has_completion_handler = !m_upload_completion_handlers.empty() || !m_sync_completion_handlers.empty();
161,020✔
1512
    if (!m_flx_subscription_store && !has_progress_handler && !has_completion_handler)
161,020✔
1513
        return;
82,060✔
1514

1515
    // The order in which we report each type of completion or progress is important,
1516
    // and changing it needs to be avoided as it'd be a breaking change to the APIs
1517

1518
    TransactionRef tr;
78,960✔
1519
    ReportedProgress p;
78,960✔
1520
    if (m_flx_subscription_store) {
78,960✔
1521
        m_flx_subscription_store->report_progress(tr);
36,828✔
1522
    }
36,828✔
1523

1524
    if (!has_progress_handler && !has_completion_handler)
78,960✔
1525
        return;
20,504✔
1526
    // The subscription store may have started a read transaction that we'll
1527
    // reuse, but it may not have needed to or may not exist
1528
    if (!tr)
58,456✔
1529
        tr = m_db->start_read();
52,062✔
1530

1531
    version_type uploaded_version;
58,456✔
1532
    DownloadableProgress downloadable;
58,456✔
1533
    ClientHistory::get_upload_download_state(*tr, m_db->get_alloc(), p.downloaded, downloadable, p.uploaded,
58,456✔
1534
                                             p.uploadable, p.snapshot, uploaded_version);
58,456✔
1535
    if (m_flx_subscription_store && has_progress_handler)
58,456✔
1536
        p.query_version = m_flx_subscription_store->get_downloading_query_version(*tr);
14,796✔
1537

1538
    report_progress(p, downloadable);
58,456✔
1539
    report_upload_completion(uploaded_version);
58,456✔
1540
}
58,456✔
1541

1542
void SessionWrapper::report_upload_completion(version_type uploaded_version)
1543
{
58,460✔
1544
    if (uploaded_version < m_upload_completion_requested_version)
58,460✔
1545
        return;
38,878✔
1546

1547
    std::move(m_sync_completion_handlers.begin(), m_sync_completion_handlers.end(),
19,582✔
1548
              std::back_inserter(m_download_completion_handlers));
19,582✔
1549
    m_sync_completion_handlers.clear();
19,582✔
1550

1551
    while (!m_upload_completion_handlers.empty()) {
34,606✔
1552
        auto handler = std::move(m_upload_completion_handlers.back());
15,024✔
1553
        m_upload_completion_handlers.pop_back();
15,024✔
1554
        handler(Status::OK()); // Throws
15,024✔
1555
    }
15,024✔
1556
}
19,582✔
1557

1558
void SessionWrapper::report_progress(ReportedProgress& p, DownloadableProgress downloadable)
1559
{
58,458✔
1560
    if (!m_progress_handler)
58,458✔
1561
        return;
27,814✔
1562

1563
    // Ignore progress messages from before we first receive a DOWNLOAD message
1564
    if (!m_reliable_download_progress)
30,644✔
1565
        return;
3,304✔
1566

1567
    auto calculate_progress = [](uint64_t transferred, uint64_t transferable, uint64_t final_transferred) {
27,340✔
1568
        REALM_ASSERT_DEBUG_EX(final_transferred <= transferred, final_transferred, transferred, transferable);
18,722✔
1569
        REALM_ASSERT_DEBUG_EX(transferred <= transferable, final_transferred, transferred, transferable);
18,722✔
1570

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

1579
        double progress_estimate = 1.0;
18,722✔
1580
        if (final_transferred < transferable && transferred < transferable)
18,722✔
1581
            progress_estimate = (transferred - final_transferred) / double(transferable - final_transferred);
9,538✔
1582
        return progress_estimate;
18,722✔
1583
    };
18,722✔
1584

1585
    bool upload_completed = p.uploaded == p.uploadable;
27,340✔
1586
    double upload_estimate = 1.0;
27,340✔
1587
    if (!upload_completed)
27,340✔
1588
        upload_estimate = calculate_progress(p.uploaded, p.uploadable, m_final_uploaded);
9,490✔
1589

1590
    bool download_completed = p.downloaded == 0;
27,340✔
1591
    p.download_estimate = 1.00;
27,340✔
1592
    if (m_flx_pending_bootstrap_store) {
27,340✔
1593
        p.download_estimate = downloadable.as_estimate();
14,796✔
1594
        if (m_flx_pending_bootstrap_store->has_pending()) {
14,796✔
1595
            p.downloaded += m_flx_pending_bootstrap_store->pending_stats().pending_changeset_bytes;
2,742✔
1596
        }
2,742✔
1597
        download_completed = p.download_estimate >= 1.0;
14,796✔
1598

1599
        // for flx with download estimate these bytes are not known
1600
        // provide some sensible value for non-streaming version of object-store callbacks
1601
        // until these field are completely removed from the api after pbs deprecation
1602
        p.downloadable = p.downloaded;
14,796✔
1603
        if (p.download_estimate > 0 && p.download_estimate < 1.0 && p.downloaded > m_final_downloaded)
14,796✔
1604
            p.downloadable = m_final_downloaded + uint64_t((p.downloaded - m_final_downloaded) / p.download_estimate);
2,778✔
1605
    }
14,796✔
1606
    else {
12,544✔
1607
        // uploadable_bytes is uploaded + remaining to upload, while downloadable_bytes
1608
        // is only the remaining to download. This is confusing, so make them use
1609
        // the same units.
1610
        p.downloadable = downloadable.as_bytes() + p.downloaded;
12,544✔
1611
        if (!download_completed)
12,544✔
1612
            p.download_estimate = calculate_progress(p.downloaded, p.downloadable, m_final_downloaded);
9,232✔
1613
    }
12,544✔
1614

1615
    if (download_completed)
27,340✔
1616
        m_final_downloaded = p.downloaded;
15,322✔
1617
    if (upload_completed)
27,340✔
1618
        m_final_uploaded = p.uploaded;
17,850✔
1619

1620
    if (p == m_reported_progress)
27,340✔
1621
        return;
18,242✔
1622

1623
    m_reported_progress = p;
9,098✔
1624

1625
    if (m_sess->logger.would_log(Logger::Level::debug)) {
9,098✔
1626
        auto to_str = [](double d) {
17,724✔
1627
            std::ostringstream ss;
17,724✔
1628
            // progress estimate string in the DOWNLOAD message isn't expected to have more than 4 digits of precision
1629
            ss << std::fixed << std::setprecision(4) << d;
17,724✔
1630
            return ss.str();
17,724✔
1631
        };
17,724✔
1632
        m_sess->logger.debug(
8,862✔
1633
            "Progress handler called, downloaded = %1, downloadable = %2, estimate = %3, "
8,862✔
1634
            "uploaded = %4, uploadable = %5, estimate = %6, snapshot version = %7, query_version = %8",
8,862✔
1635
            p.downloaded, p.downloadable, to_str(p.download_estimate), p.uploaded, p.uploadable,
8,862✔
1636
            to_str(upload_estimate), p.snapshot, p.query_version);
8,862✔
1637
    }
8,862✔
1638

1639
    m_progress_handler(p.downloaded, p.downloadable, p.uploaded, p.uploadable, p.snapshot, p.download_estimate,
9,098✔
1640
                       upload_estimate, p.query_version);
9,098✔
1641
}
9,098✔
1642

1643
util::Future<std::string> SessionWrapper::send_test_command(std::string body)
1644
{
72✔
1645
    if (!m_sess) {
72✔
1646
        return Status{ErrorCodes::RuntimeError, "session must be activated to send a test command"};
×
1647
    }
×
1648

1649
    return m_sess->send_test_command(std::move(body));
72✔
1650
}
72✔
1651

1652
void SessionWrapper::handle_pending_client_reset_acknowledgement()
1653
{
10,752✔
1654
    REALM_ASSERT(!m_finalized);
10,752✔
1655

1656
    auto has_pending_reset = PendingResetStore::has_pending_reset(*m_db->start_frozen());
10,752✔
1657
    if (!has_pending_reset) {
10,752✔
1658
        return; // nothing to do
10,384✔
1659
    }
10,384✔
1660

1661
    m_sess->logger.info(util::LogCategory::reset, "Tracking %1", *has_pending_reset);
368✔
1662

1663
    // Now that the client reset merge is complete, wait for the changes to synchronize with the server
1664
    async_wait_for(
368✔
1665
        true, true, [self = util::bind_ptr(this), pending_reset = std::move(*has_pending_reset)](Status status) {
370✔
1666
            if (status == ErrorCodes::OperationAborted) {
370✔
1667
                return;
166✔
1668
            }
166✔
1669
            auto& logger = self->m_sess->logger;
204✔
1670
            if (!status.is_ok()) {
204✔
1671
                logger.error(util::LogCategory::reset, "Error while tracking client reset acknowledgement: %1",
×
1672
                             status);
×
1673
                return;
×
1674
            }
×
1675

1676
            logger.debug(util::LogCategory::reset, "Server has acknowledged %1", pending_reset);
204✔
1677

1678
            auto tr = self->m_db->start_write();
204✔
1679
            auto cur_pending_reset = PendingResetStore::has_pending_reset(*tr);
204✔
1680
            if (!cur_pending_reset) {
204✔
1681
                logger.debug(util::LogCategory::reset, "Client reset cycle detection tracker already removed.");
4✔
1682
                return;
4✔
1683
            }
4✔
1684
            if (*cur_pending_reset == pending_reset) {
200✔
1685
                logger.debug(util::LogCategory::reset, "Removing client reset cycle detection tracker.");
200✔
1686
            }
200✔
1687
            else {
×
1688
                logger.info(util::LogCategory::reset, "Found new %1", cur_pending_reset);
×
1689
            }
×
1690
            PendingResetStore::clear_pending_reset(*tr);
200✔
1691
            tr->commit();
200✔
1692
        });
200✔
1693
}
368✔
1694

1695
std::string SessionWrapper::get_appservices_connection_id()
1696
{
76✔
1697
    auto pf = util::make_promise_future<std::string>();
76✔
1698

1699
    m_client.post([self = util::bind_ptr{this}, promise = std::move(pf.promise)](Status status) mutable {
76✔
1700
        if (!status.is_ok()) {
76✔
1701
            promise.set_error(status);
×
1702
            return;
×
1703
        }
×
1704

1705
        if (!self->m_sess) {
76✔
1706
            promise.set_error({ErrorCodes::RuntimeError, "session already finalized"});
×
1707
            return;
×
1708
        }
×
1709

1710
        promise.emplace_value(self->m_sess->get_connection().get_active_appservices_connection_id());
76✔
1711
    });
76✔
1712

1713
    return pf.future.get();
76✔
1714
}
76✔
1715

1716
// ################ ClientImpl::Connection ################
1717

1718
ClientImpl::Connection::Connection(ClientImpl& client, connection_ident_type ident, ServerEndpoint endpoint,
1719
                                   const std::string& authorization_header_name,
1720
                                   const std::map<std::string, std::string>& custom_http_headers,
1721
                                   bool verify_servers_ssl_certificate,
1722
                                   Optional<std::string> ssl_trust_certificate_path,
1723
                                   std::function<SSLVerifyCallback> ssl_verify_callback,
1724
                                   Optional<ProxyConfig> proxy_config, ReconnectInfo reconnect_info)
1725
    : logger{make_logger(ident, std::nullopt, client.logger.base_logger)} // Throws
1,354✔
1726
    , m_client{client}
1,354✔
1727
    , m_verify_servers_ssl_certificate{verify_servers_ssl_certificate}    // DEPRECATED
1,354✔
1728
    , m_ssl_trust_certificate_path{std::move(ssl_trust_certificate_path)} // DEPRECATED
1,354✔
1729
    , m_ssl_verify_callback{std::move(ssl_verify_callback)}               // DEPRECATED
1,354✔
1730
    , m_proxy_config{std::move(proxy_config)}                             // DEPRECATED
1,354✔
1731
    , m_reconnect_info{reconnect_info}
1,354✔
1732
    , m_on_idle{m_client, &Connection::on_idle, this}
1,354✔
1733
    , m_ident{ident}
1,354✔
1734
    , m_server_endpoint{std::move(endpoint)}
1,354✔
1735
    , m_authorization_header_name{authorization_header_name} // DEPRECATED
1,354✔
1736
    , m_custom_http_headers{custom_http_headers}             // DEPRECATED
1,354✔
1737
{
2,834✔
1738
}
2,834✔
1739

1740
inline connection_ident_type ClientImpl::Connection::get_ident() const noexcept
1741
{
12✔
1742
    return m_ident;
12✔
1743
}
12✔
1744

1745

1746
inline const ServerEndpoint& ClientImpl::Connection::get_server_endpoint() const noexcept
1747
{
2,836✔
1748
    return m_server_endpoint;
2,836✔
1749
}
2,836✔
1750

1751
inline void ClientImpl::Connection::update_connect_info(const std::string& http_request_path_prefix,
1752
                                                        const std::string& signed_access_token)
1753
{
10,628✔
1754
    m_http_request_path_prefix = http_request_path_prefix; // Throws (copy)
10,628✔
1755
    m_signed_access_token = signed_access_token;           // Throws (copy)
10,628✔
1756
}
10,628✔
1757

1758

1759
void ClientImpl::Connection::resume_active_sessions()
1760
{
1,948✔
1761
    auto handler = [=](ClientImpl::Session& sess) {
3,892✔
1762
        sess.cancel_resumption_delay(); // Throws
3,892✔
1763
    };
3,892✔
1764
    for_each_active_session(std::move(handler)); // Throws
1,948✔
1765
}
1,948✔
1766

1767
void ClientImpl::Connection::on_idle()
1768
{
2,846✔
1769
    REALM_ASSERT(m_activated);
2,846✔
1770
    if (m_state != ConnectionState::disconnected || m_num_active_sessions != 0)
2,846✔
1771
        return;
10✔
1772

1773
    logger.debug(util::LogCategory::session, "Destroying connection object");
2,836✔
1774
    ClientImpl& client = get_client();
2,836✔
1775
    client.remove_connection(*this);
2,836✔
1776
    // NOTE: This connection object is now destroyed!
1777
}
2,836✔
1778

1779

1780
std::string ClientImpl::Connection::get_http_request_path() const
1781
{
3,852✔
1782
    using namespace std::string_view_literals;
3,852✔
1783
    const auto param = m_http_request_path_prefix.find('?') == std::string::npos ? "?baas_at="sv : "&baas_at="sv;
3,852✔
1784

1785
    std::string path;
3,852✔
1786
    path.reserve(m_http_request_path_prefix.size() + param.size() + m_signed_access_token.size());
3,852✔
1787
    path += m_http_request_path_prefix;
3,852✔
1788
    path += param;
3,852✔
1789
    path += m_signed_access_token;
3,852✔
1790

1791
    return path;
3,852✔
1792
}
3,852✔
1793

1794

1795
std::shared_ptr<util::Logger> ClientImpl::Connection::make_logger(connection_ident_type ident,
1796
                                                                  std::optional<std::string_view> coid,
1797
                                                                  std::shared_ptr<util::Logger> base_logger)
1798
{
10,060✔
1799
    std::string prefix =
10,060✔
1800
        coid ? util::format("Connection[%1:%2] ", ident, *coid) : util::format("Connection[%1] ", ident);
10,060✔
1801
    return std::make_shared<util::PrefixLogger>(util::LogCategory::session, std::move(prefix), base_logger);
10,060✔
1802
}
10,060✔
1803

1804

1805
void ClientImpl::Connection::report_connection_state_change(ConnectionState state,
1806
                                                            std::optional<SessionErrorInfo> error_info)
1807
{
11,352✔
1808
    if (m_force_closed) {
11,352✔
1809
        return;
2,470✔
1810
    }
2,470✔
1811
    auto handler = [=](ClientImpl::Session& sess) {
12,066✔
1812
        SessionImpl& sess_2 = static_cast<SessionImpl&>(sess);
12,066✔
1813
        sess_2.on_connection_state_changed(state, error_info); // Throws
12,066✔
1814
    };
12,066✔
1815
    for_each_active_session(std::move(handler)); // Throws
8,882✔
1816
}
8,882✔
1817

1818

1819
Client::Client(Config config)
1820
    : m_impl{new ClientImpl{std::move(config)}} // Throws
4,914✔
1821
{
9,966✔
1822
}
9,966✔
1823

1824

1825
Client::Client(Client&& client) noexcept
1826
    : m_impl{std::move(client.m_impl)}
1827
{
×
1828
}
×
1829

1830

1831
Client::~Client() noexcept {}
9,966✔
1832

1833

1834
void Client::shutdown() noexcept
1835
{
10,048✔
1836
    m_impl->shutdown();
10,048✔
1837
}
10,048✔
1838

1839
void Client::shutdown_and_wait()
1840
{
772✔
1841
    m_impl->shutdown_and_wait();
772✔
1842
}
772✔
1843

1844
void Client::cancel_reconnect_delay()
1845
{
1,952✔
1846
    m_impl->cancel_reconnect_delay();
1,952✔
1847
}
1,952✔
1848

1849
void Client::voluntary_disconnect_all_connections()
1850
{
12✔
1851
    m_impl->voluntary_disconnect_all_connections();
12✔
1852
}
12✔
1853

1854
bool Client::wait_for_session_terminations_or_client_stopped()
1855
{
9,640✔
1856
    return m_impl->wait_for_session_terminations_or_client_stopped();
9,640✔
1857
}
9,640✔
1858

1859
util::Future<void> Client::notify_session_terminated()
1860
{
56✔
1861
    return m_impl->notify_session_terminated();
56✔
1862
}
56✔
1863

1864
bool Client::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
1865
                                  port_type& port, std::string& path) const
1866
{
4,382✔
1867
    return m_impl->decompose_server_url(url, protocol, address, port, path); // Throws
4,382✔
1868
}
4,382✔
1869

1870

1871
Session::Session(Client& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1872
                 std::shared_ptr<MigrationStore> migration_store, Config&& config)
1873
{
10,480✔
1874
    m_impl = new SessionWrapper{*client.m_impl, std::move(db), std::move(flx_sub_store), std::move(migration_store),
10,480✔
1875
                                std::move(config)}; // Throws
10,480✔
1876
}
10,480✔
1877

1878

1879
void Session::nonsync_transact_notify(version_type new_version)
1880
{
20,180✔
1881
    m_impl->on_commit(new_version); // Throws
20,180✔
1882
}
20,180✔
1883

1884

1885
void Session::cancel_reconnect_delay()
1886
{
32✔
1887
    m_impl->cancel_reconnect_delay(); // Throws
32✔
1888
}
32✔
1889

1890

1891
void Session::async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler handler)
1892
{
5,438✔
1893
    m_impl->async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws
5,438✔
1894
}
5,438✔
1895

1896

1897
bool Session::wait_for_upload_complete_or_client_stopped()
1898
{
12,912✔
1899
    return m_impl->wait_for_upload_complete_or_client_stopped(); // Throws
12,912✔
1900
}
12,912✔
1901

1902

1903
bool Session::wait_for_download_complete_or_client_stopped()
1904
{
10,004✔
1905
    return m_impl->wait_for_download_complete_or_client_stopped(); // Throws
10,004✔
1906
}
10,004✔
1907

1908

1909
void Session::refresh(std::string_view signed_access_token)
1910
{
218✔
1911
    m_impl->refresh(signed_access_token); // Throws
218✔
1912
}
218✔
1913

1914

1915
void Session::abandon() noexcept
1916
{
10,482✔
1917
    REALM_ASSERT(m_impl);
10,482✔
1918
    // Reabsorb the ownership assigned to the applications naked pointer by
1919
    // Session constructor
1920
    util::bind_ptr<SessionWrapper> wrapper{m_impl, util::bind_ptr_base::adopt_tag{}};
10,482✔
1921
    SessionWrapper::abandon(std::move(wrapper));
10,482✔
1922
}
10,482✔
1923

1924
util::Future<std::string> Session::send_test_command(std::string body)
1925
{
72✔
1926
    return m_impl->send_test_command(std::move(body));
72✔
1927
}
72✔
1928

1929
std::string Session::get_appservices_connection_id()
1930
{
76✔
1931
    return m_impl->get_appservices_connection_id();
76✔
1932
}
76✔
1933

1934
std::ostream& operator<<(std::ostream& os, ProxyConfig::Type proxyType)
1935
{
×
1936
    switch (proxyType) {
×
1937
        case ProxyConfig::Type::HTTP:
×
1938
            return os << "HTTP";
×
1939
        case ProxyConfig::Type::HTTPS:
×
1940
            return os << "HTTPS";
×
1941
    }
×
1942
    REALM_TERMINATE("Invalid Proxy Type object.");
1943
}
×
1944

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