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

realm / realm-core / 2503

19 Jul 2024 12:39AM UTC coverage: 90.996%. Remained the same
2503

push

Evergreen

web-flow
Merge pull request #7897 from realm/feature/role-change

* RCORE-1872 Sync client should allow server bootstrapping at any time (#7440)
* First round of changes for server-initiated bootstraps
* Added test for role change bootstraps
* Updated test for handle role bootstraps
* Updated baas/baasaas to use branch with fixes
* Updated test to verify bootstrap actually occurred
* Fixed tsan warning
* Updates from review; added comments to clarify bootstrap detection logic
* Reverted baas branch to master and protocol version to 12
* Added comments to changes needed when merging to master; update baas version to not use master
* Pulled over changes from other branch and tweaking download params
* Refactored tests to validate different bootstrap types
* Updated tests to get passing using the server params
* Updated to support new batch_state protocol changes; updated tests
* Updated role change tests and merged test from separate PR
* Fixed issue with flx query verion 0 not being treated as a bootstrap
* Cleaned up the tests a bit and reworked query version 0 handling
* Updates from review; updated batch_state for schema bootstraps
* Removed extra mutex in favor of state machine's mutex
* Increased timeout when waiting for app initial sync to complete
* Updated role change test to use test commands
* Update resume and ident message handling
* Updated future waits for the pause/resume test command
* Added session connected event for when session multiplexing is disabled
* Added wait_until() to state machine to wait for callback; updated role change test

* RCORE-1973 Add role/permissions tests for new bootstrap feature (#7675)
* Moved role change tests to separate test file
* Fixed building of new flx_role_change.cpp file
* Added local changes w/role bootstrap test - fixed exception in subscription store during server initiated boostrap
* Updated local change test to include valid offline writes during role change
* Added role c... (continued)

102634 of 181458 branches covered (56.56%)

920 of 998 new or added lines in 12 files covered. (92.18%)

54 existing lines in 11 files now uncovered.

216311 of 237715 relevant lines covered (91.0%)

5880250.34 hits per line

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

90.54
/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
        int64_t query_version;
153
        double download_estimate;
154

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

167
    const util::UniqueFunction<ProgressHandler> m_progress_handler;
168
    util::UniqueFunction<ConnectionStateChangeListener> m_connection_state_change_listener;
169

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

173
    const SessionReason m_session_reason;
174

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

179
    const uint64_t m_schema_version;
180

181
    std::shared_ptr<SubscriptionStore> m_flx_subscription_store;
182
    int64_t m_flx_active_version = 0;
183
    int64_t m_flx_last_seen_version = 0;
184
    int64_t m_flx_pending_mark_version = 0;
185
    std::unique_ptr<PendingBootstrapStore> m_flx_pending_bootstrap_store;
186

187
    std::shared_ptr<MigrationStore> m_migration_store;
188

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

199
    // Set to true when session deactivation is begun, either via force_close()
200
    // or finalize().
201
    bool m_closed = false;
202

203
    // Set to true in on_suspended() and then false in on_resumed(). Used to
204
    // suppress spurious connection state and error reporting while the session
205
    // is already in an error state.
206
    bool m_suspended = false;
207

208
    // Set when the session has been abandoned. After this point none of the
209
    // public API functions should be called again.
210
    bool m_abandoned = false;
211
    // Has the SessionWrapper been finalized?
212
    bool m_finalized = false;
213

214
    // Set to true when the first DOWNLOAD message is received to indicate that
215
    // the byte-level download progress parameters can be considered reasonable
216
    // reliable. Before that, a lot of time may have passed, so our record of
217
    // the download progress is likely completely out of date.
218
    bool m_reliable_download_progress = false;
219

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

233
    // These must only be accessed from the event loop thread.
234
    std::vector<WaitOperCompletionHandler> m_upload_completion_handlers;
235
    std::vector<WaitOperCompletionHandler> m_download_completion_handlers;
236
    std::vector<WaitOperCompletionHandler> m_sync_completion_handlers;
237

238
    version_type m_upload_completion_requested_version = -1;
239

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

248
    void init_progress_handler();
249
    void check_progress();
250
    void report_progress(ReportedProgress& p, DownloadableProgress downloadable);
251
    void report_upload_completion(version_type);
252

253
    friend class SessionWrapperStack;
254
    friend class ClientImpl::Session;
255
};
256

257

258
// ################ SessionWrapperStack ################
259

260
inline bool SessionWrapperStack::empty() const noexcept
261
{
19,908✔
262
    return !m_back;
19,908✔
263
}
19,908✔
264

265

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

273

274
inline util::bind_ptr<SessionWrapper> SessionWrapperStack::pop() noexcept
275
{
61,710✔
276
    util::bind_ptr<SessionWrapper> w{m_back, util::bind_ptr_base::adopt_tag{}};
61,710✔
277
    if (m_back) {
61,710✔
278
        m_back = m_back->m_next;
20,790✔
279
        w->m_next = nullptr;
20,790✔
280
    }
20,790✔
281
    return w;
61,710✔
282
}
61,710✔
283

284

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

293

294
inline bool SessionWrapperStack::erase(SessionWrapper* w) noexcept
295
{
10,462✔
296
    SessionWrapper** p = &m_back;
10,462✔
297
    while (*p && *p != w) {
10,622✔
298
        p = &(*p)->m_next;
160✔
299
    }
160✔
300
    if (!*p) {
10,462✔
301
        return false;
10,394✔
302
    }
10,394✔
303
    *p = w->m_next;
68✔
304
    util::bind_ptr<SessionWrapper>{w, util::bind_ptr_base::adopt_tag{}};
68✔
305
    return true;
68✔
306
}
10,462✔
307

308

309
SessionWrapperStack::~SessionWrapperStack()
310
{
19,908✔
311
    clear();
19,908✔
312
}
19,908✔
313

314

315
// ################ ClientImpl ################
316

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

322
    shutdown_and_wait();
9,954✔
323
    // Session wrappers are removed from m_unactualized_session_wrappers as they
324
    // are abandoned.
325
    REALM_ASSERT(m_stopped);
9,954✔
326
    REALM_ASSERT(m_unactualized_session_wrappers.empty());
9,954✔
327
    REALM_ASSERT(m_abandoned_session_wrappers.empty());
9,954✔
328
}
9,954✔
329

330

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

360

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

391

392
bool ClientImpl::wait_for_session_terminations_or_client_stopped()
393
{
9,628✔
394
    // Thread safety required
395

396
    {
9,628✔
397
        util::CheckedLockGuard lock{m_mutex};
9,628✔
398
        m_sessions_terminated = false;
9,628✔
399
    }
9,628✔
400

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

426
    bool completion_condition_was_satisfied;
9,628✔
427
    {
9,628✔
428
        util::CheckedUniqueLock lock{m_mutex};
9,628✔
429
        m_wait_or_client_stopped_cond.wait(lock.native_handle(), [&]() REQUIRES(m_mutex) {
19,254✔
430
            return m_sessions_terminated || m_stopped;
19,254✔
431
        });
19,254✔
432
        completion_condition_was_satisfied = !m_stopped;
9,628✔
433
    }
9,628✔
434
    return completion_condition_was_satisfied;
9,628✔
435
}
9,628✔
436

437

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

449
        promise.emplace_value();
56✔
450
    });
56✔
451

452
    return std::move(pf.future);
56✔
453
}
56✔
454

455
void ClientImpl::drain_connections_on_loop()
456
{
9,954✔
457
    post([this](Status status) {
9,954✔
458
        REALM_ASSERT(status.is_ok());
9,954✔
459
        drain_connections();
9,954✔
460
    });
9,954✔
461
}
9,954✔
462

463
void ClientImpl::shutdown_and_wait()
464
{
10,726✔
465
    shutdown();
10,726✔
466
    util::CheckedUniqueLock lock{m_drain_mutex};
10,726✔
467
    if (m_drained) {
10,726✔
468
        return;
772✔
469
    }
772✔
470

471
    logger.debug("Waiting for %1 connections to drain", m_num_connections);
9,954✔
472
    m_drain_cv.wait(lock.native_handle(), [&]() REQUIRES(m_drain_mutex) {
15,872✔
473
        return m_num_connections == 0 && m_outstanding_posts == 0;
15,872✔
474
    });
15,872✔
475

476
    m_drained = true;
9,954✔
477
}
9,954✔
478

479
void ClientImpl::shutdown() noexcept
480
{
20,762✔
481
    {
20,762✔
482
        util::CheckedLockGuard lock{m_mutex};
20,762✔
483
        if (m_stopped)
20,762✔
484
            return;
10,808✔
485
        m_stopped = true;
9,954✔
486
    }
9,954✔
487
    m_wait_or_client_stopped_cond.notify_all();
×
488

489
    drain_connections_on_loop();
9,954✔
490
}
9,954✔
491

492

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

505
        REALM_ASSERT(m_actualize_and_finalize);
10,466✔
506
        m_unactualized_session_wrappers.push(util::bind_ptr(wrapper));
10,466✔
507
    }
10,466✔
508
    m_actualize_and_finalize->trigger();
×
509
}
10,466✔
510

511

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

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

536

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

575

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

588
    // TODO: enable multiplexing with proxies
589
    if (server_slot.connection && !m_one_connection_per_session && !proxy_config) {
10,388✔
590
        // Use preexisting connection
591
        REALM_ASSERT(server_slot.alt_connections.empty());
7,564✔
592
        return *server_slot.connection;
7,564✔
593
    }
7,564✔
594

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

618

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

640
    bool notify;
2,826✔
641
    {
2,826✔
642
        util::CheckedLockGuard lk(m_drain_mutex);
2,826✔
643
        REALM_ASSERT(m_num_connections);
2,826✔
644
        notify = --m_num_connections <= 0;
2,826✔
645
    }
2,826✔
646
    if (notify) {
2,826✔
647
        m_drain_cv.notify_all();
2,204✔
648
    }
2,204✔
649
}
2,826✔
650

651

652
// ################ SessionImpl ################
653

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

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

671

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

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

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

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

700
ClientHistory& SessionImpl::get_history() const noexcept
701
{
122,074✔
702
    return get_repl().get_history();
122,074✔
703
}
122,074✔
704

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

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

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

726
bool SessionImpl::upload_messages_allowed() noexcept
727
{
71,894✔
728
    // Can only be called if the session is active or being activated
729
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
71,894✔
730
    return m_wrapper.m_allow_upload_messages;
71,894✔
731
}
71,894✔
732

733
void SessionImpl::initiate_integrate_changesets(std::uint_fast64_t downloadable_bytes, DownloadBatchState batch_state,
734
                                                const SyncProgress& progress, const ReceivedChangesets& changesets)
735
{
45,952✔
736
    // Ignore the call if the session is not active
737
    if (m_state != State::Active) {
45,952✔
738
        return;
×
739
    }
×
740

741
    try {
45,952✔
742
        bool simulate_integration_error = (m_wrapper.m_simulate_integration_error && !changesets.empty());
45,952!
743
        if (simulate_integration_error) {
45,952✔
744
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
×
745
        }
×
746
        version_type client_version;
45,952✔
747
        if (REALM_LIKELY(!get_client().is_dry_run())) {
45,952✔
748
            VersionInfo version_info;
45,952✔
749
            integrate_changesets(progress, downloadable_bytes, changesets, version_info, batch_state); // Throws
45,952✔
750
            client_version = version_info.realm_version;
45,952✔
751
        }
45,952✔
UNCOV
752
        else {
×
753
            // Fake it for "dry run" mode
UNCOV
754
            client_version = m_last_version_available + 1;
×
UNCOV
755
        }
×
756
        on_changesets_integrated(client_version, progress); // Throws
45,952✔
757
    }
45,952✔
758
    catch (const IntegrationException& e) {
45,952✔
759
        on_integration_failure(e);
24✔
760
    }
24✔
761
}
45,952✔
762

763

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

772

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

781

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

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

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

806
bool SessionImpl::process_flx_bootstrap_message(const DownloadMessage& message)
807
{
49,862✔
808
    // Ignore the message if the session is not active or a steady state message
809
    if (m_state != State::Active || message.batch_state == DownloadBatchState::SteadyState) {
49,862✔
810
        return false;
45,952✔
811
    }
45,952✔
812

813
    REALM_ASSERT(m_is_flx_sync_session);
3,910✔
814

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

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

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

843
    auto hook_action = call_debug_hook(SyncClientHookEvent::BootstrapMessageProcessed, message.progress,
3,910✔
844
                                       *message.query_version, message.batch_state, message.changesets.size());
3,910✔
845
    if (hook_action == SyncClientHookAction::EarlyReturn) {
3,910✔
846
        return true;
12✔
847
    }
12✔
848
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
3,898✔
849

850
    if (message.batch_state == DownloadBatchState::MoreToCome) {
3,898✔
851
        return true;
1,526✔
852
    }
1,526✔
853

854
    try {
2,372✔
855
        process_pending_flx_bootstrap(); // throws
2,372✔
856
    }
2,372✔
857
    catch (const IntegrationException& e) {
2,372✔
858
        on_integration_failure(e);
12✔
859
    }
12✔
860
    catch (...) {
2,372✔
861
        on_integration_failure(IntegrationException(exception_to_status()));
×
862
    }
×
863

864
    return true;
2,372✔
865
}
2,372✔
866

867

868
void SessionImpl::process_pending_flx_bootstrap()
869
{
12,930✔
870
    // Ignore the call if not a flx session or session is not active
871
    if (!m_is_flx_sync_session || m_state != State::Active) {
12,930✔
872
        return;
8,614✔
873
    }
8,614✔
874
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
4,316✔
875
    if (!bootstrap_store->has_pending()) {
4,316✔
876
        return;
1,912✔
877
    }
1,912✔
878

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

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

904
        auto batch_state =
2,672✔
905
            pending_batch.remaining_changesets > 0 ? DownloadBatchState::MoreToCome : DownloadBatchState::LastInBatch;
2,672✔
906
        query_version = pending_batch.query_version;
2,672✔
907
        bool simulate_integration_error =
2,672✔
908
            (m_wrapper.m_simulate_integration_error && !pending_batch.changesets.empty());
2,672✔
909
        if (simulate_integration_error) {
2,672✔
910
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
4✔
911
        }
4✔
912

913
        call_debug_hook(SyncClientHookEvent::BootstrapBatchAboutToProcess, *pending_batch.progress, query_version,
2,668✔
914
                        batch_state, pending_batch.changesets.size());
2,668✔
915

916
        history.integrate_server_changesets(
2,668✔
917
            *pending_batch.progress, 1.0, pending_batch.changesets, new_version, batch_state, logger, transact,
2,668✔
918
            [&](const TransactionRef& tr, util::Span<Changeset> changesets_applied) {
2,668✔
919
                REALM_ASSERT_3(changesets_applied.size(), <=, pending_batch.changesets.size());
2,656✔
920
                bootstrap_store->pop_front_pending(tr, changesets_applied.size());
2,656✔
921
            });
2,656✔
922
        progress = *pending_batch.progress;
2,668✔
923
        changesets_processed += pending_batch.changesets.size();
2,668✔
924
        auto duration = std::chrono::steady_clock::now() - start_time;
2,668✔
925

926
        auto action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
2,668✔
927
                                      batch_state, pending_batch.changesets.size());
2,668✔
928
        REALM_ASSERT_EX(action == SyncClientHookAction::NoAction, action);
2,668✔
929

930
        logger.info("Integrated %1 changesets from pending bootstrap for query version %2, producing client version "
2,668✔
931
                    "%3 in %4 ms. %5 changesets remaining in bootstrap",
2,668✔
932
                    pending_batch.changesets.size(), pending_batch.query_version, new_version.realm_version,
2,668✔
933
                    std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(),
2,668✔
934
                    pending_batch.remaining_changesets);
2,668✔
935
    }
2,668✔
936

937
    REALM_ASSERT_3(query_version, !=, -1);
2,380✔
938
    on_flx_sync_progress(query_version, DownloadBatchState::LastInBatch);
2,380✔
939

940
    on_changesets_integrated(new_version.realm_version, progress);
2,380✔
941
    auto action = call_debug_hook(SyncClientHookEvent::BootstrapProcessed, progress, query_version,
2,380✔
942
                                  DownloadBatchState::LastInBatch, changesets_processed);
2,380✔
943
    // NoAction/EarlyReturn are both valid no-op actions to take here.
944
    REALM_ASSERT_EX(action == SyncClientHookAction::NoAction || action == SyncClientHookAction::EarlyReturn, action);
2,380✔
945
}
2,380✔
946

947
void SessionImpl::on_flx_sync_error(int64_t version, std::string_view err_msg)
948
{
20✔
949
    // Ignore the call if the session is not active
950
    if (m_state == State::Active) {
20✔
951
        m_wrapper.on_flx_sync_error(version, err_msg);
20✔
952
    }
20✔
953
}
20✔
954

955
void SessionImpl::on_flx_sync_progress(int64_t version, DownloadBatchState batch_state)
956
{
2,624✔
957
    // Ignore the call if the session is not active
958
    if (m_state == State::Active) {
2,624✔
959
        m_wrapper.on_flx_sync_progress(version, batch_state);
2,624✔
960
    }
2,624✔
961
}
2,624✔
962

963
SubscriptionStore* SessionImpl::get_flx_subscription_store()
964
{
24,352✔
965
    // Should never be called if session is not active
966
    REALM_ASSERT_EX(m_state == State::Active, m_state);
24,352✔
967
    return m_wrapper.get_flx_subscription_store();
24,352✔
968
}
24,352✔
969

970
MigrationStore* SessionImpl::get_migration_store()
971
{
75,024✔
972
    // Should never be called if session is not active
973
    REALM_ASSERT_EX(m_state == State::Active, m_state);
75,024✔
974
    return m_wrapper.get_migration_store();
75,024✔
975
}
75,024✔
976

977
void SessionImpl::on_flx_sync_version_complete(int64_t version)
978
{
348✔
979
    // Ignore the call if the session is not active
980
    if (m_state == State::Active) {
348✔
981
        m_wrapper.on_flx_sync_version_complete(version);
348✔
982
    }
348✔
983
}
348✔
984

985
SyncClientHookAction SessionImpl::call_debug_hook(const SyncClientHookData& data)
986
{
17,018✔
987
    // Should never be called if session is not active
988
    REALM_ASSERT_EX(m_state == State::Active, m_state);
17,018✔
989

990
    // Make sure we don't call the debug hook recursively.
991
    if (m_wrapper.m_in_debug_hook) {
17,018✔
992
        return SyncClientHookAction::NoAction;
24✔
993
    }
24✔
994
    m_wrapper.m_in_debug_hook = true;
16,994✔
995
    auto in_hook_guard = util::make_scope_exit([&]() noexcept {
16,994✔
996
        m_wrapper.m_in_debug_hook = false;
16,994✔
997
    });
16,994✔
998

999
    auto action = m_wrapper.m_debug_hook(data);
16,994✔
1000
    switch (action) {
16,994✔
1001
        case realm::SyncClientHookAction::SuspendWithRetryableError: {
12✔
1002
            SessionErrorInfo err_info(Status{ErrorCodes::RuntimeError, "hook requested error"}, IsFatal{false});
12✔
1003
            err_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
12✔
1004

1005
            auto err_processing_err = receive_error_message(err_info);
12✔
1006
            REALM_ASSERT_EX(err_processing_err.is_ok(), err_processing_err);
12✔
1007
            return SyncClientHookAction::EarlyReturn;
12✔
1008
        }
×
1009
        case realm::SyncClientHookAction::TriggerReconnect: {
24✔
1010
            get_connection().voluntary_disconnect();
24✔
1011
            return SyncClientHookAction::EarlyReturn;
24✔
1012
        }
×
1013
        default:
16,950✔
1014
            return action;
16,950✔
1015
    }
16,994✔
1016
}
16,994✔
1017

1018
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const SyncProgress& progress,
1019
                                                  int64_t query_version, DownloadBatchState batch_state,
1020
                                                  size_t num_changesets)
1021
{
107,430✔
1022
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
107,430✔
1023
        return SyncClientHookAction::NoAction;
98,744✔
1024
    }
98,744✔
1025
    if (REALM_UNLIKELY(m_state != State::Active)) {
8,686✔
1026
        return SyncClientHookAction::NoAction;
×
1027
    }
×
1028

1029
    SyncClientHookData data;
8,686✔
1030
    data.event = event;
8,686✔
1031
    data.batch_state = batch_state;
8,686✔
1032
    data.progress = progress;
8,686✔
1033
    data.num_changesets = num_changesets;
8,686✔
1034
    data.query_version = query_version;
8,686✔
1035

1036
    return call_debug_hook(data);
8,686✔
1037
}
8,686✔
1038

1039
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const ProtocolErrorInfo* error_info)
1040
{
101,518✔
1041
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
101,518✔
1042
        return SyncClientHookAction::NoAction;
93,184✔
1043
    }
93,184✔
1044
    if (REALM_UNLIKELY(m_state != State::Active)) {
8,334✔
1045
        return SyncClientHookAction::NoAction;
×
1046
    }
×
1047

1048
    SyncClientHookData data;
8,334✔
1049
    data.event = event;
8,334✔
1050
    data.batch_state = DownloadBatchState::SteadyState;
8,334✔
1051
    data.progress = m_progress;
8,334✔
1052
    data.num_changesets = 0;
8,334✔
1053
    data.query_version = m_last_sent_flx_query_version;
8,334✔
1054
    data.error_info = error_info;
8,334✔
1055

1056
    return call_debug_hook(data);
8,334✔
1057
}
8,334✔
1058

1059
void SessionImpl::init_progress_handler()
1060
{
10,734✔
1061
    REALM_ASSERT_EX(m_state == State::Unactivated || m_state == State::Active, m_state);
10,734✔
1062
    m_wrapper.init_progress_handler();
10,734✔
1063
}
10,734✔
1064

1065
void SessionImpl::enable_progress_notifications()
1066
{
47,980✔
1067
    m_wrapper.m_reliable_download_progress = true;
47,980✔
1068
}
47,980✔
1069

1070
util::Future<std::string> SessionImpl::send_test_command(std::string body)
1071
{
68✔
1072
    if (m_state != State::Active) {
68✔
1073
        return Status{ErrorCodes::RuntimeError, "Cannot send a test command for a session that is not active"};
×
1074
    }
×
1075

1076
    try {
68✔
1077
        auto json_body = nlohmann::json::parse(body.begin(), body.end());
68✔
1078
        if (auto it = json_body.find("command"); it == json_body.end() || !it->is_string()) {
68✔
1079
            return Status{ErrorCodes::LogicError,
4✔
1080
                          "Must supply command name in \"command\" field of test command json object"};
4✔
1081
        }
4✔
1082
        if (json_body.size() > 1 && json_body.find("args") == json_body.end()) {
64✔
1083
            return Status{ErrorCodes::LogicError, "Only valid fields in a test command are \"command\" and \"args\""};
×
1084
        }
×
1085
    }
64✔
1086
    catch (const nlohmann::json::parse_error& e) {
68✔
1087
        return Status{ErrorCodes::LogicError, util::format("Invalid json input to send_test_command: %1", e.what())};
4✔
1088
    }
4✔
1089

1090
    auto pf = util::make_promise_future<std::string>();
60✔
1091
    get_client().post([this, promise = std::move(pf.promise), body = std::move(body)](Status status) mutable {
60✔
1092
        // Includes operation_aborted
1093
        if (!status.is_ok()) {
60✔
1094
            promise.set_error(status);
×
1095
            return;
×
1096
        }
×
1097

1098
        auto id = ++m_last_pending_test_command_ident;
60✔
1099
        m_pending_test_commands.push_back(PendingTestCommand{id, std::move(body), std::move(promise)});
60✔
1100
        ensure_enlisted_to_send();
60✔
1101
    });
60✔
1102

1103
    return std::move(pf.future);
60✔
1104
}
68✔
1105

1106
// ################ SessionWrapper ################
1107

1108
// The SessionWrapper class is held by a sync::Session (which is owned by the SyncSession instance) and
1109
// provides a link to the ClientImpl::Session that creates and receives messages with the server with
1110
// the ClientImpl::Connection that owns the ClientImpl::Session.
1111
SessionWrapper::SessionWrapper(ClientImpl& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1112
                               std::shared_ptr<MigrationStore> migration_store, Session::Config&& config)
1113
    : m_client{client}
5,062✔
1114
    , m_db(std::move(db))
5,062✔
1115
    , m_replication(m_db->get_replication())
5,062✔
1116
    , m_protocol_envelope{config.protocol_envelope}
5,062✔
1117
    , m_server_address{std::move(config.server_address)}
5,062✔
1118
    , m_server_port{config.server_port}
5,062✔
1119
    , m_server_verified{config.server_verified}
5,062✔
1120
    , m_user_id(std::move(config.user_id))
5,062✔
1121
    , m_sync_mode(flx_sub_store ? SyncServerMode::FLX : SyncServerMode::PBS)
5,062✔
1122
    , m_authorization_header_name{config.authorization_header_name}
5,062✔
1123
    , m_custom_http_headers{std::move(config.custom_http_headers)}
5,062✔
1124
    , m_verify_servers_ssl_certificate{config.verify_servers_ssl_certificate}
5,062✔
1125
    , m_simulate_integration_error{config.simulate_integration_error}
5,062✔
1126
    , m_ssl_trust_certificate_path{std::move(config.ssl_trust_certificate_path)}
5,062✔
1127
    , m_ssl_verify_callback{std::move(config.ssl_verify_callback)}
5,062✔
1128
    , m_flx_bootstrap_batch_size_bytes(config.flx_bootstrap_batch_size_bytes)
5,062✔
1129
    , m_http_request_path_prefix{std::move(config.service_identifier)}
5,062✔
1130
    , m_virt_path{std::move(config.realm_identifier)}
5,062✔
1131
    , m_proxy_config{std::move(config.proxy_config)}
5,062✔
1132
    , m_signed_access_token{std::move(config.signed_user_token)}
5,062✔
1133
    , m_client_reset_config{std::move(config.client_reset_config)}
5,062✔
1134
    , m_progress_handler(std::move(config.progress_handler))
5,062✔
1135
    , m_connection_state_change_listener(std::move(config.connection_state_change_listener))
5,062✔
1136
    , m_debug_hook(std::move(config.on_sync_client_event_hook))
5,062✔
1137
    , m_session_reason(m_client_reset_config || config.fresh_realm_download ? SessionReason::ClientReset
5,062✔
1138
                                                                            : SessionReason::Sync)
5,062✔
1139
    , m_allow_upload_messages(!config.fresh_realm_download)
5,062✔
1140
    , m_schema_version(config.schema_version)
5,062✔
1141
    , m_flx_subscription_store(std::move(flx_sub_store))
5,062✔
1142
    , m_migration_store(std::move(migration_store))
5,062✔
1143
{
10,466✔
1144
    REALM_ASSERT(m_db);
10,466✔
1145
    REALM_ASSERT(m_db->get_replication());
10,466✔
1146
    REALM_ASSERT(dynamic_cast<ClientReplication*>(m_db->get_replication()));
10,466✔
1147

1148
    // SessionWrapper begins at +1 retain count because Client retains and
1149
    // releases it while performing async operations, and these need to not
1150
    // take it to 0 or it could be deleted before the caller can retain it.
1151
    bind_ptr();
10,466✔
1152
    m_client.register_unactualized_session_wrapper(this);
10,466✔
1153
}
10,466✔
1154

1155
SessionWrapper::~SessionWrapper() noexcept
1156
{
10,466✔
1157
    // We begin actualization in the constructor and do not delete the wrapper
1158
    // until both the Client is done with it and the Session has abandoned it,
1159
    // so at this point we must have actualized, finalized, and been abandoned.
1160
    REALM_ASSERT(m_actualized);
10,466✔
1161
    REALM_ASSERT(m_abandoned);
10,466✔
1162
    REALM_ASSERT(m_finalized);
10,466✔
1163
    REALM_ASSERT(m_closed);
10,466✔
1164
    REALM_ASSERT(!m_db);
10,466✔
1165
}
10,466✔
1166

1167

1168
inline ClientReplication& SessionWrapper::get_replication() noexcept
1169
{
124,480✔
1170
    REALM_ASSERT(m_db);
124,480✔
1171
    return static_cast<ClientReplication&>(*m_replication);
124,480✔
1172
}
124,480✔
1173

1174

1175
inline ClientImpl& SessionWrapper::get_client() noexcept
1176
{
×
1177
    return m_client;
×
1178
}
×
1179

1180
bool SessionWrapper::has_flx_subscription_store() const
1181
{
2,624✔
1182
    return static_cast<bool>(m_flx_subscription_store);
2,624✔
1183
}
2,624✔
1184

1185
void SessionWrapper::on_flx_sync_error(int64_t version, std::string_view err_msg)
1186
{
20✔
1187
    REALM_ASSERT(!m_finalized);
20✔
1188
    get_flx_subscription_store()->update_state(version, SubscriptionSet::State::Error, err_msg);
20✔
1189
}
20✔
1190

1191
void SessionWrapper::on_flx_sync_version_complete(int64_t version)
1192
{
2,648✔
1193
    REALM_ASSERT(!m_finalized);
2,648✔
1194
    m_flx_last_seen_version = version;
2,648✔
1195
    m_flx_active_version = version;
2,648✔
1196
}
2,648✔
1197

1198
void SessionWrapper::on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state)
1199
{
2,624✔
1200
    if (!has_flx_subscription_store()) {
2,624✔
1201
        return;
×
1202
    }
×
1203

1204
    REALM_ASSERT(!m_finalized);
2,624✔
1205
    if (batch_state == DownloadBatchState::SteadyState) {
2,624✔
NEW
1206
        throw IntegrationException(ErrorCodes::SyncProtocolInvariantFailed,
×
NEW
1207
                                   "Unexpected batch state of SteadyState while downloading bootstrap");
×
NEW
1208
    }
×
1209
    // Is this a server-initiated bootstrap? Skip notifying the subscription store
1210
    if (new_version == m_flx_active_version) {
2,624✔
1211
        return;
92✔
1212
    }
92✔
1213
    if (new_version < m_flx_active_version) {
2,532✔
NEW
1214
        throw IntegrationException(ErrorCodes::SyncProtocolInvariantFailed,
×
NEW
1215
                                   util::format("Bootstrap query version %1 is less than active version %2",
×
NEW
1216
                                                new_version, m_flx_active_version));
×
NEW
1217
    }
×
1218
    if (new_version < m_flx_last_seen_version) {
2,532✔
NEW
1219
        throw IntegrationException(
×
NEW
1220
            ErrorCodes::SyncProtocolInvariantFailed,
×
NEW
1221
            util::format("Download message query version %1 is less than current bootstrap version %2", new_version,
×
NEW
1222
                         m_flx_last_seen_version));
×
NEW
1223
    }
×
1224

1225
    SubscriptionSet::State new_state = SubscriptionSet::State::Uncommitted; // Initialize to make compiler happy
2,532✔
1226

1227
    switch (batch_state) {
2,532✔
1228
        case DownloadBatchState::SteadyState:
✔
1229
            // Cannot be called with this value.
1230
            REALM_UNREACHABLE();
1231
        case DownloadBatchState::LastInBatch:
2,300✔
1232
            on_flx_sync_version_complete(new_version);
2,300✔
1233
            if (new_version == 0) {
2,300✔
1234
                new_state = SubscriptionSet::State::Complete;
1,100✔
1235
            }
1,100✔
1236
            else {
1,200✔
1237
                new_state = SubscriptionSet::State::AwaitingMark;
1,200✔
1238
                m_flx_pending_mark_version = new_version;
1,200✔
1239
            }
1,200✔
1240
            break;
2,300✔
1241
        case DownloadBatchState::MoreToCome:
232✔
1242
            if (m_flx_last_seen_version == new_version) {
232✔
1243
                return;
12✔
1244
            }
12✔
1245

1246
            m_flx_last_seen_version = new_version;
220✔
1247
            new_state = SubscriptionSet::State::Bootstrapping;
220✔
1248
            break;
220✔
1249
    }
2,532✔
1250

1251
    get_flx_subscription_store()->update_state(new_version, new_state);
2,520✔
1252
}
2,520✔
1253

1254
SubscriptionStore* SessionWrapper::get_flx_subscription_store()
1255
{
26,892✔
1256
    REALM_ASSERT(!m_finalized);
26,892✔
1257
    return m_flx_subscription_store.get();
26,892✔
1258
}
26,892✔
1259

1260
PendingBootstrapStore* SessionWrapper::get_flx_pending_bootstrap_store()
1261
{
8,226✔
1262
    REALM_ASSERT(!m_finalized);
8,226✔
1263
    return m_flx_pending_bootstrap_store.get();
8,226✔
1264
}
8,226✔
1265

1266
MigrationStore* SessionWrapper::get_migration_store()
1267
{
75,024✔
1268
    REALM_ASSERT(!m_finalized);
75,024✔
1269
    return m_migration_store.get();
75,024✔
1270
}
75,024✔
1271

1272
inline bool SessionWrapper::mark_abandoned()
1273
{
10,466✔
1274
    REALM_ASSERT(!m_abandoned);
10,466✔
1275
    m_abandoned = true;
10,466✔
1276
    return m_finalized;
10,466✔
1277
}
10,466✔
1278

1279

1280
void SessionWrapper::on_commit(version_type new_version)
1281
{
121,842✔
1282
    // Thread safety required
1283
    m_client.post([self = util::bind_ptr{this}, new_version] {
121,842✔
1284
        REALM_ASSERT(self->m_actualized);
121,842✔
1285
        if (REALM_UNLIKELY(!self->m_sess))
121,842✔
1286
            return; // Already finalized
484✔
1287
        SessionImpl& sess = *self->m_sess;
121,358✔
1288
        sess.recognize_sync_version(new_version); // Throws
121,358✔
1289
        self->check_progress();                   // Throws
121,358✔
1290
    });
121,358✔
1291
}
121,842✔
1292

1293

1294
void SessionWrapper::cancel_reconnect_delay()
1295
{
32✔
1296
    // Thread safety required
1297

1298
    m_client.post([self = util::bind_ptr{this}] {
32✔
1299
        REALM_ASSERT(self->m_actualized);
32✔
1300
        if (REALM_UNLIKELY(self->m_closed)) {
32✔
1301
            return;
×
1302
        }
×
1303

1304
        if (REALM_UNLIKELY(!self->m_sess))
32✔
1305
            return; // Already finalized
×
1306
        SessionImpl& sess = *self->m_sess;
32✔
1307
        sess.cancel_resumption_delay(); // Throws
32✔
1308
        ClientImpl::Connection& conn = sess.get_connection();
32✔
1309
        conn.cancel_reconnect_delay(); // Throws
32✔
1310
    });                                // Throws
32✔
1311
}
32✔
1312

1313
void SessionWrapper::async_wait_for(bool upload_completion, bool download_completion,
1314
                                    WaitOperCompletionHandler handler)
1315
{
28,696✔
1316
    REALM_ASSERT(upload_completion || download_completion);
28,696✔
1317

1318
    m_client.post([self = util::bind_ptr{this}, handler = std::move(handler), upload_completion,
28,696✔
1319
                   download_completion](Status status) mutable {
28,698✔
1320
        REALM_ASSERT(self->m_actualized);
28,698✔
1321
        if (!status.is_ok()) {
28,698✔
1322
            handler(status); // Throws
×
1323
            return;
×
1324
        }
×
1325
        if (REALM_UNLIKELY(!self->m_sess)) {
28,698✔
1326
            // Already finalized
1327
            handler({ErrorCodes::OperationAborted, "Session finalized before callback could run"}); // Throws
184✔
1328
            return;
184✔
1329
        }
184✔
1330
        if (upload_completion) {
28,514✔
1331
            self->m_upload_completion_requested_version = self->m_db->get_version_of_latest_snapshot();
15,650✔
1332
            if (download_completion) {
15,650✔
1333
                // Wait for upload and download completion
1334
                self->m_sync_completion_handlers.push_back(std::move(handler)); // Throws
364✔
1335
            }
364✔
1336
            else {
15,286✔
1337
                // Wait for upload completion only
1338
                self->m_upload_completion_handlers.push_back(std::move(handler)); // Throws
15,286✔
1339
            }
15,286✔
1340
        }
15,650✔
1341
        else {
12,864✔
1342
            // Wait for download completion only
1343
            self->m_download_completion_handlers.push_back(std::move(handler)); // Throws
12,864✔
1344
        }
12,864✔
1345
        SessionImpl& sess = *self->m_sess;
28,514✔
1346
        if (upload_completion)
28,514✔
1347
            self->check_progress();
15,650✔
1348
        if (download_completion)
28,514✔
1349
            sess.request_download_completion_notification(); // Throws
13,228✔
1350
    });                                                      // Throws
28,514✔
1351
}
28,696✔
1352

1353

1354
bool SessionWrapper::wait_for_upload_complete_or_client_stopped()
1355
{
12,912✔
1356
    // Thread safety required
1357
    REALM_ASSERT(!m_abandoned);
12,912✔
1358

1359
    auto pf = util::make_promise_future<bool>();
12,912✔
1360
    async_wait_for(true, false, [promise = std::move(pf.promise)](Status status) mutable {
12,912✔
1361
        promise.emplace_value(status.is_ok());
12,912✔
1362
    });
12,912✔
1363
    return pf.future.get();
12,912✔
1364
}
12,912✔
1365

1366

1367
bool SessionWrapper::wait_for_download_complete_or_client_stopped()
1368
{
10,004✔
1369
    // Thread safety required
1370
    REALM_ASSERT(!m_abandoned);
10,004✔
1371

1372
    auto pf = util::make_promise_future<bool>();
10,004✔
1373
    async_wait_for(false, true, [promise = std::move(pf.promise)](Status status) mutable {
10,004✔
1374
        promise.emplace_value(status.is_ok());
10,004✔
1375
    });
10,004✔
1376
    return pf.future.get();
10,004✔
1377
}
10,004✔
1378

1379

1380
void SessionWrapper::refresh(std::string_view signed_access_token)
1381
{
216✔
1382
    // Thread safety required
1383
    REALM_ASSERT(!m_abandoned);
216✔
1384

1385
    m_client.post([self = util::bind_ptr{this}, token = std::string(signed_access_token)] {
216✔
1386
        REALM_ASSERT(self->m_actualized);
216✔
1387
        if (REALM_UNLIKELY(!self->m_sess))
216✔
1388
            return; // Already finalized
×
1389
        self->m_signed_access_token = std::move(token);
216✔
1390
        SessionImpl& sess = *self->m_sess;
216✔
1391
        ClientImpl::Connection& conn = sess.get_connection();
216✔
1392
        // FIXME: This only makes sense when each session uses a separate connection.
1393
        conn.update_connect_info(self->m_http_request_path_prefix, self->m_signed_access_token); // Throws
216✔
1394
        sess.cancel_resumption_delay();                                                          // Throws
216✔
1395
        conn.cancel_reconnect_delay();                                                           // Throws
216✔
1396
    });
216✔
1397
}
216✔
1398

1399

1400
void SessionWrapper::abandon(util::bind_ptr<SessionWrapper> wrapper) noexcept
1401
{
10,466✔
1402
    ClientImpl& client = wrapper->m_client;
10,466✔
1403
    client.register_abandoned_session_wrapper(std::move(wrapper));
10,466✔
1404
}
10,466✔
1405

1406

1407
// Must be called from event loop thread
1408
void SessionWrapper::actualize()
1409
{
10,392✔
1410
    // actualize() can only ever be called once
1411
    REALM_ASSERT(!m_actualized);
10,392✔
1412
    REALM_ASSERT(!m_sess);
10,392✔
1413
    // The client should have removed this wrapper from those pending
1414
    // actualization if it called force_close() or finalize_before_actualize()
1415
    REALM_ASSERT(!m_finalized);
10,392✔
1416
    REALM_ASSERT(!m_closed);
10,392✔
1417

1418
    m_actualized = true;
10,392✔
1419

1420
    ScopeExitFail close_on_error([&]() noexcept {
10,392✔
1421
        m_closed = true;
4✔
1422
    });
4✔
1423

1424
    m_db->claim_sync_agent();
10,392✔
1425
    m_db->add_commit_listener(this);
10,392✔
1426
    ScopeExitFail remove_commit_listener([&]() noexcept {
10,392✔
1427
        m_db->remove_commit_listener(this);
×
1428
    });
×
1429

1430
    ServerEndpoint endpoint{m_protocol_envelope, m_server_address, m_server_port,
10,392✔
1431
                            m_user_id,           m_sync_mode,      m_server_verified};
10,392✔
1432
    bool was_created = false;
10,392✔
1433
    ClientImpl::Connection& conn = m_client.get_connection(
10,392✔
1434
        std::move(endpoint), m_authorization_header_name, m_custom_http_headers, m_verify_servers_ssl_certificate,
10,392✔
1435
        m_ssl_trust_certificate_path, m_ssl_verify_callback, m_proxy_config,
10,392✔
1436
        was_created); // Throws
10,392✔
1437
    ScopeExitFail remove_connection([&]() noexcept {
10,392✔
1438
        if (was_created)
×
1439
            m_client.remove_connection(conn);
×
1440
    });
×
1441

1442
    // FIXME: This only makes sense when each session uses a separate connection.
1443
    conn.update_connect_info(m_http_request_path_prefix, m_signed_access_token);    // Throws
10,392✔
1444
    std::unique_ptr<SessionImpl> sess = std::make_unique<SessionImpl>(*this, conn); // Throws
10,392✔
1445
    if (m_sync_mode == SyncServerMode::FLX) {
10,392✔
1446
        m_flx_pending_bootstrap_store = std::make_unique<PendingBootstrapStore>(m_db, sess->logger);
1,794✔
1447
    }
1,794✔
1448

1449
    sess->logger.info("Binding '%1' to '%2'", m_db->get_path(), m_virt_path); // Throws
10,392✔
1450
    m_sess = sess.get();
10,392✔
1451
    ScopeExitFail clear_sess([&]() noexcept {
10,392✔
1452
        m_sess = nullptr;
×
1453
    });
×
1454
    conn.activate_session(std::move(sess)); // Throws
10,392✔
1455

1456
    // Initialize the variables relying on the bootstrap store from the event loop to guarantee that a previous
1457
    // session cannot change the state of the bootstrap store at the same time.
1458
    update_subscription_version_info();
10,392✔
1459

1460
    if (was_created)
10,392✔
1461
        conn.activate(); // Throws
2,824✔
1462

1463
    if (m_connection_state_change_listener) {
10,392✔
1464
        ConnectionState state = conn.get_state();
10,380✔
1465
        if (state != ConnectionState::disconnected) {
10,380✔
1466
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,386✔
1467
            if (state == ConnectionState::connected)
7,386✔
1468
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
7,262✔
1469
        }
7,386✔
1470
    }
10,380✔
1471

1472
    if (!m_client_reset_config)
10,392✔
1473
        check_progress(); // Throws
9,966✔
1474
}
10,392✔
1475

1476
void SessionWrapper::force_close()
1477
{
10,496✔
1478
    if (m_closed) {
10,496✔
1479
        return;
106✔
1480
    }
106✔
1481
    REALM_ASSERT(m_actualized);
10,390✔
1482
    REALM_ASSERT(m_sess);
10,390✔
1483
    m_closed = true;
10,390✔
1484

1485
    ClientImpl::Connection& conn = m_sess->get_connection();
10,390✔
1486
    conn.initiate_session_deactivation(m_sess); // Throws
10,390✔
1487

1488
    // We need to keep the DB open until finalization, but we no longer want to
1489
    // know when commits are made
1490
    m_db->remove_commit_listener(this);
10,390✔
1491

1492
    // Delete the pending bootstrap store since it uses a reference to the logger in m_sess
1493
    m_flx_pending_bootstrap_store.reset();
10,390✔
1494
    // Clear the subscription and migration store refs since they are owned by SyncSession
1495
    m_flx_subscription_store.reset();
10,390✔
1496
    m_migration_store.reset();
10,390✔
1497
    m_sess = nullptr;
10,390✔
1498
    // Everything is being torn down, no need to report connection state anymore
1499
    m_connection_state_change_listener = {};
10,390✔
1500

1501
    // All outstanding wait operations must be canceled
1502
    while (!m_upload_completion_handlers.empty()) {
10,754✔
1503
        auto handler = std::move(m_upload_completion_handlers.back());
364✔
1504
        m_upload_completion_handlers.pop_back();
364✔
1505
        handler({ErrorCodes::OperationAborted, "Sync session is being closed before upload was complete"}); // Throws
364✔
1506
    }
364✔
1507
    while (!m_download_completion_handlers.empty()) {
10,786✔
1508
        auto handler = std::move(m_download_completion_handlers.back());
396✔
1509
        m_download_completion_handlers.pop_back();
396✔
1510
        handler(
396✔
1511
            {ErrorCodes::OperationAborted, "Sync session is being closed before download was complete"}); // Throws
396✔
1512
    }
396✔
1513
    while (!m_sync_completion_handlers.empty()) {
10,402✔
1514
        auto handler = std::move(m_sync_completion_handlers.back());
12✔
1515
        m_sync_completion_handlers.pop_back();
12✔
1516
        handler({ErrorCodes::OperationAborted, "Sync session is being closed before sync was complete"}); // Throws
12✔
1517
    }
12✔
1518
}
10,390✔
1519

1520
// Must be called from event loop thread
1521
//
1522
// `m_client.m_mutex` is not held while this is called, but it is guaranteed to
1523
// have been acquired at some point in between the final read or write ever made
1524
// from a different thread and when this is called.
1525
void SessionWrapper::finalize()
1526
{
10,394✔
1527
    REALM_ASSERT(m_actualized);
10,394✔
1528
    REALM_ASSERT(m_abandoned);
10,394✔
1529
    REALM_ASSERT(!m_finalized);
10,394✔
1530

1531
    force_close();
10,394✔
1532

1533
    m_finalized = true;
10,394✔
1534

1535
    // The Realm file can be closed now, as no access to the Realm file is
1536
    // supposed to happen on behalf of a session after initiation of
1537
    // deactivation.
1538
    m_db->release_sync_agent();
10,394✔
1539
    m_db = nullptr;
10,394✔
1540
}
10,394✔
1541

1542

1543
// Must be called only when an unactualized session wrapper becomes abandoned.
1544
//
1545
// Called with a lock on `m_client.m_mutex`.
1546
inline void SessionWrapper::finalize_before_actualization() noexcept
1547
{
72✔
1548
    REALM_ASSERT(!m_finalized);
72✔
1549
    REALM_ASSERT(!m_sess);
72✔
1550
    m_actualized = true;
72✔
1551
    m_finalized = true;
72✔
1552
    m_closed = true;
72✔
1553
    m_db->remove_commit_listener(this);
72✔
1554
    m_db->release_sync_agent();
72✔
1555
    m_db = nullptr;
72✔
1556
}
72✔
1557

1558
void SessionWrapper::on_download_completion()
1559
{
16,800✔
1560
    // Ensure that progress handlers get called before completion handlers. The
1561
    // download completing performed a commit and will trigger progress
1562
    // notifications asynchronously, but they would arrive after the download
1563
    // completion without this.
1564
    check_progress();
16,800✔
1565

1566
    while (!m_download_completion_handlers.empty()) {
29,522✔
1567
        auto handler = std::move(m_download_completion_handlers.back());
12,722✔
1568
        m_download_completion_handlers.pop_back();
12,722✔
1569
        handler(Status::OK()); // Throws
12,722✔
1570
    }
12,722✔
1571
    while (!m_sync_completion_handlers.empty()) {
16,898✔
1572
        auto handler = std::move(m_sync_completion_handlers.back());
98✔
1573
        m_upload_completion_handlers.push_back(std::move(handler)); // Throws
98✔
1574
        m_sync_completion_handlers.pop_back();
98✔
1575
    }
98✔
1576

1577
    if (m_flx_subscription_store && m_flx_pending_mark_version != SubscriptionSet::EmptyVersion) {
16,800✔
1578
        m_sess->logger.debug("Marking query version %1 as complete after receiving MARK message",
1,090✔
1579
                             m_flx_pending_mark_version);
1,090✔
1580
        m_flx_subscription_store->update_state(m_flx_pending_mark_version, SubscriptionSet::State::Complete);
1,090✔
1581
        m_flx_pending_mark_version = SubscriptionSet::EmptyVersion;
1,090✔
1582
    }
1,090✔
1583
}
16,800✔
1584

1585

1586
void SessionWrapper::on_suspended(const SessionErrorInfo& error_info)
1587
{
828✔
1588
    REALM_ASSERT(!m_finalized);
828✔
1589
    m_suspended = true;
828✔
1590
    if (m_connection_state_change_listener) {
828✔
1591
        m_connection_state_change_listener(ConnectionState::disconnected, error_info); // Throws
828✔
1592
    }
828✔
1593
}
828✔
1594

1595

1596
void SessionWrapper::on_resumed()
1597
{
168✔
1598
    REALM_ASSERT(!m_finalized);
168✔
1599
    m_suspended = false;
168✔
1600
    if (m_connection_state_change_listener) {
168✔
1601
        ClientImpl::Connection& conn = m_sess->get_connection();
168✔
1602
        if (conn.get_state() != ConnectionState::disconnected) {
168✔
1603
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
154✔
1604
            if (conn.get_state() == ConnectionState::connected)
154✔
1605
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
148✔
1606
        }
154✔
1607
    }
168✔
1608
}
168✔
1609

1610

1611
void SessionWrapper::on_connection_state_changed(ConnectionState state,
1612
                                                 const std::optional<SessionErrorInfo>& error_info)
1613
{
12,006✔
1614
    if (m_connection_state_change_listener && !m_suspended) {
12,006✔
1615
        m_connection_state_change_listener(state, error_info); // Throws
11,952✔
1616
    }
11,952✔
1617
}
12,006✔
1618

1619
void SessionWrapper::init_progress_handler()
1620
{
10,734✔
1621
    ClientHistory::get_upload_download_state(m_db.get(), m_final_downloaded, m_final_uploaded);
10,734✔
1622
}
10,734✔
1623

1624
void SessionWrapper::check_progress()
1625
{
163,770✔
1626
    REALM_ASSERT(!m_finalized);
163,770✔
1627
    REALM_ASSERT(m_sess);
163,770✔
1628

1629
    if (!m_progress_handler && m_upload_completion_handlers.empty() && m_sync_completion_handlers.empty())
163,770✔
1630
        return;
74,266✔
1631

1632
    version_type uploaded_version;
89,504✔
1633
    ReportedProgress p;
89,504✔
1634
    DownloadableProgress downloadable;
89,504✔
1635
    ClientHistory::get_upload_download_state(*m_db, p.downloaded, downloadable, p.uploaded, p.uploadable, p.snapshot,
89,504✔
1636
                                             uploaded_version);
89,504✔
1637
    p.query_version = m_flx_last_seen_version;
89,504✔
1638

1639
    report_progress(p, downloadable);
89,504✔
1640
    report_upload_completion(uploaded_version);
89,504✔
1641
}
89,504✔
1642

1643
void SessionWrapper::report_upload_completion(version_type uploaded_version)
1644
{
89,506✔
1645
    if (uploaded_version < m_upload_completion_requested_version)
89,506✔
1646
        return;
68,724✔
1647

1648
    std::move(m_sync_completion_handlers.begin(), m_sync_completion_handlers.end(),
20,782✔
1649
              std::back_inserter(m_download_completion_handlers));
20,782✔
1650
    m_sync_completion_handlers.clear();
20,782✔
1651

1652
    while (!m_upload_completion_handlers.empty()) {
35,802✔
1653
        auto handler = std::move(m_upload_completion_handlers.back());
15,020✔
1654
        m_upload_completion_handlers.pop_back();
15,020✔
1655
        handler(Status::OK()); // Throws
15,020✔
1656
    }
15,020✔
1657
}
20,782✔
1658

1659
void SessionWrapper::report_progress(ReportedProgress& p, DownloadableProgress downloadable)
1660
{
89,506✔
1661
    if (!m_progress_handler)
89,506✔
1662
        return;
27,922✔
1663

1664
    // Ignore progress messages from before we first receive a DOWNLOAD message
1665
    if (!m_reliable_download_progress)
61,584✔
1666
        return;
31,788✔
1667

1668
    auto calculate_progress = [](uint64_t transferred, uint64_t transferable, uint64_t final_transferred) {
29,796✔
1669
        REALM_ASSERT_DEBUG_EX(final_transferred <= transferred, final_transferred, transferred, transferable);
19,262✔
1670
        REALM_ASSERT_DEBUG_EX(transferred <= transferable, final_transferred, transferred, transferable);
19,262✔
1671

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

1680
        double progress_estimate = 1.0;
19,262✔
1681
        if (final_transferred < transferable && transferred < transferable)
19,262✔
1682
            progress_estimate = (transferred - final_transferred) / double(transferable - final_transferred);
9,996✔
1683
        return progress_estimate;
19,262✔
1684
    };
19,262✔
1685

1686
    bool upload_completed = p.uploaded == p.uploadable;
29,796✔
1687
    double upload_estimate = 1.0;
29,796✔
1688
    if (!upload_completed)
29,796✔
1689
        upload_estimate = calculate_progress(p.uploaded, p.uploadable, m_final_uploaded);
9,948✔
1690

1691
    bool download_completed = p.downloaded == 0;
29,796✔
1692
    p.download_estimate = 1.00;
29,796✔
1693
    if (m_flx_pending_bootstrap_store) {
29,796✔
1694
        p.download_estimate = downloadable.as_estimate();
17,192✔
1695
        if (m_flx_pending_bootstrap_store->has_pending()) {
17,192✔
1696
            p.downloaded += m_flx_pending_bootstrap_store->pending_stats().pending_changeset_bytes;
3,102✔
1697
        }
3,102✔
1698
        download_completed = p.download_estimate >= 1.0;
17,192✔
1699

1700
        // for flx with download estimate these bytes are not known
1701
        // provide some sensible value for non-streaming version of object-store callbacks
1702
        // until these field are completely removed from the api after pbs deprecation
1703
        p.downloadable = p.downloaded;
17,192✔
1704
        if (p.download_estimate > 0 && p.download_estimate < 1.0 && p.downloaded > m_final_downloaded)
17,192✔
1705
            p.downloadable = m_final_downloaded + uint64_t((p.downloaded - m_final_downloaded) / p.download_estimate);
3,120✔
1706
    }
17,192✔
1707
    else {
12,604✔
1708
        // uploadable_bytes is uploaded + remaining to upload, while downloadable_bytes
1709
        // is only the remaining to download. This is confusing, so make them use
1710
        // the same units.
1711
        p.downloadable = downloadable.as_bytes() + p.downloaded;
12,604✔
1712
        if (!download_completed)
12,604✔
1713
            p.download_estimate = calculate_progress(p.downloaded, p.downloadable, m_final_downloaded);
9,314✔
1714
    }
12,604✔
1715

1716
    if (download_completed)
29,796✔
1717
        m_final_downloaded = p.downloaded;
17,354✔
1718
    if (upload_completed)
29,796✔
1719
        m_final_uploaded = p.uploaded;
19,848✔
1720

1721
    if (p == m_reported_progress)
29,796✔
1722
        return;
20,700✔
1723

1724
    m_reported_progress = p;
9,096✔
1725

1726
    if (m_sess->logger.would_log(Logger::Level::debug)) {
9,096✔
1727
        auto to_str = [](double d) {
17,720✔
1728
            std::ostringstream ss;
17,720✔
1729
            // progress estimate string in the DOWNLOAD message isn't expected to have more than 4 digits of precision
1730
            ss << std::fixed << std::setprecision(4) << d;
17,720✔
1731
            return ss.str();
17,720✔
1732
        };
17,720✔
1733
        m_sess->logger.debug(
8,860✔
1734
            "Progress handler called, downloaded = %1, downloadable = %2, estimate = %3, "
8,860✔
1735
            "uploaded = %4, uploadable = %5, estimate = %6, snapshot version = %7, query_version = %8",
8,860✔
1736
            p.downloaded, p.downloadable, to_str(p.download_estimate), p.uploaded, p.uploadable,
8,860✔
1737
            to_str(upload_estimate), p.snapshot, p.query_version);
8,860✔
1738
    }
8,860✔
1739

1740
    m_progress_handler(p.downloaded, p.downloadable, p.uploaded, p.uploadable, p.snapshot, p.download_estimate,
9,096✔
1741
                       upload_estimate, p.query_version);
9,096✔
1742
}
9,096✔
1743

1744
util::Future<std::string> SessionWrapper::send_test_command(std::string body)
1745
{
68✔
1746
    if (!m_sess) {
68✔
1747
        return Status{ErrorCodes::RuntimeError, "session must be activated to send a test command"};
×
1748
    }
×
1749

1750
    return m_sess->send_test_command(std::move(body));
68✔
1751
}
68✔
1752

1753
void SessionWrapper::handle_pending_client_reset_acknowledgement()
1754
{
10,734✔
1755
    REALM_ASSERT(!m_finalized);
10,734✔
1756

1757
    auto has_pending_reset = PendingResetStore::has_pending_reset(m_db->start_frozen());
10,734✔
1758
    if (!has_pending_reset) {
10,734✔
1759
        return; // nothing to do
10,364✔
1760
    }
10,364✔
1761

1762
    m_sess->logger.info(util::LogCategory::reset, "Tracking %1", *has_pending_reset);
370✔
1763

1764
    // Now that the client reset merge is complete, wait for the changes to synchronize with the server
1765
    async_wait_for(
370✔
1766
        true, true, [self = util::bind_ptr(this), pending_reset = std::move(*has_pending_reset)](Status status) {
370✔
1767
            if (status == ErrorCodes::OperationAborted) {
370✔
1768
                return;
164✔
1769
            }
164✔
1770
            auto& logger = self->m_sess->logger;
206✔
1771
            if (!status.is_ok()) {
206✔
1772
                logger.error(util::LogCategory::reset, "Error while tracking client reset acknowledgement: %1",
×
1773
                             status);
×
1774
                return;
×
1775
            }
×
1776

1777
            logger.debug(util::LogCategory::reset, "Server has acknowledged %1", pending_reset);
206✔
1778

1779
            auto tr = self->m_db->start_write();
206✔
1780
            auto cur_pending_reset = PendingResetStore::has_pending_reset(tr);
206✔
1781
            if (!cur_pending_reset) {
206✔
1782
                logger.debug(util::LogCategory::reset, "Client reset cycle detection tracker already removed.");
4✔
1783
                return;
4✔
1784
            }
4✔
1785
            if (*cur_pending_reset == pending_reset) {
202✔
1786
                logger.debug(util::LogCategory::reset, "Removing client reset cycle detection tracker.");
202✔
1787
            }
202✔
1788
            else {
×
1789
                logger.info(util::LogCategory::reset, "Found new %1", cur_pending_reset);
×
1790
            }
×
1791
            PendingResetStore::clear_pending_reset(tr);
202✔
1792
            tr->commit();
202✔
1793
        });
202✔
1794
}
370✔
1795

1796
void SessionWrapper::update_subscription_version_info()
1797
{
10,732✔
1798
    if (!m_flx_subscription_store)
10,732✔
1799
        return;
8,792✔
1800
    auto versions_info = m_flx_subscription_store->get_version_info();
1,940✔
1801
    m_flx_active_version = versions_info.active;
1,940✔
1802
    m_flx_pending_mark_version = versions_info.pending_mark;
1,940✔
1803
}
1,940✔
1804

1805
std::string SessionWrapper::get_appservices_connection_id()
1806
{
72✔
1807
    auto pf = util::make_promise_future<std::string>();
72✔
1808

1809
    m_client.post([self = util::bind_ptr{this}, promise = std::move(pf.promise)](Status status) mutable {
72✔
1810
        if (!status.is_ok()) {
72✔
1811
            promise.set_error(status);
×
1812
            return;
×
1813
        }
×
1814

1815
        if (!self->m_sess) {
72✔
1816
            promise.set_error({ErrorCodes::RuntimeError, "session already finalized"});
×
1817
            return;
×
1818
        }
×
1819

1820
        promise.emplace_value(self->m_sess->get_connection().get_active_appservices_connection_id());
72✔
1821
    });
72✔
1822

1823
    return pf.future.get();
72✔
1824
}
72✔
1825

1826
// ################ ClientImpl::Connection ################
1827

1828
ClientImpl::Connection::Connection(ClientImpl& client, connection_ident_type ident, ServerEndpoint endpoint,
1829
                                   const std::string& authorization_header_name,
1830
                                   const std::map<std::string, std::string>& custom_http_headers,
1831
                                   bool verify_servers_ssl_certificate,
1832
                                   Optional<std::string> ssl_trust_certificate_path,
1833
                                   std::function<SSLVerifyCallback> ssl_verify_callback,
1834
                                   Optional<ProxyConfig> proxy_config, ReconnectInfo reconnect_info)
1835
    : logger_ptr{std::make_shared<util::PrefixLogger>(util::LogCategory::session, make_logger_prefix(ident),
1,346✔
1836
                                                      client.logger_ptr)} // Throws
1,346✔
1837
    , logger{*logger_ptr}
1,346✔
1838
    , m_client{client}
1,346✔
1839
    , m_verify_servers_ssl_certificate{verify_servers_ssl_certificate}    // DEPRECATED
1,346✔
1840
    , m_ssl_trust_certificate_path{std::move(ssl_trust_certificate_path)} // DEPRECATED
1,346✔
1841
    , m_ssl_verify_callback{std::move(ssl_verify_callback)}               // DEPRECATED
1,346✔
1842
    , m_proxy_config{std::move(proxy_config)}                             // DEPRECATED
1,346✔
1843
    , m_reconnect_info{reconnect_info}
1,346✔
1844
    , m_ident{ident}
1,346✔
1845
    , m_server_endpoint{std::move(endpoint)}
1,346✔
1846
    , m_authorization_header_name{authorization_header_name} // DEPRECATED
1,346✔
1847
    , m_custom_http_headers{custom_http_headers}             // DEPRECATED
1,346✔
1848
{
2,826✔
1849
    m_on_idle = m_client.create_trigger([this](Status status) {
2,832✔
1850
        if (status == ErrorCodes::OperationAborted)
2,832✔
1851
            return;
×
1852
        else if (!status.is_ok())
2,832✔
1853
            throw Exception(status);
×
1854

1855
        REALM_ASSERT(m_activated);
2,832✔
1856
        if (m_state == ConnectionState::disconnected && m_num_active_sessions == 0) {
2,832✔
1857
            on_idle(); // Throws
2,822✔
1858
            // Connection object may be destroyed now.
1859
        }
2,822✔
1860
    });
2,832✔
1861
}
2,826✔
1862

1863
inline connection_ident_type ClientImpl::Connection::get_ident() const noexcept
1864
{
12✔
1865
    return m_ident;
12✔
1866
}
12✔
1867

1868

1869
inline const ServerEndpoint& ClientImpl::Connection::get_server_endpoint() const noexcept
1870
{
2,826✔
1871
    return m_server_endpoint;
2,826✔
1872
}
2,826✔
1873

1874
inline void ClientImpl::Connection::update_connect_info(const std::string& http_request_path_prefix,
1875
                                                        const std::string& signed_access_token)
1876
{
10,606✔
1877
    m_http_request_path_prefix = http_request_path_prefix; // Throws (copy)
10,606✔
1878
    m_signed_access_token = signed_access_token;           // Throws (copy)
10,606✔
1879
}
10,606✔
1880

1881

1882
void ClientImpl::Connection::resume_active_sessions()
1883
{
1,876✔
1884
    auto handler = [=](ClientImpl::Session& sess) {
3,748✔
1885
        sess.cancel_resumption_delay(); // Throws
3,748✔
1886
    };
3,748✔
1887
    for_each_active_session(std::move(handler)); // Throws
1,876✔
1888
}
1,876✔
1889

1890
void ClientImpl::Connection::on_idle()
1891
{
2,822✔
1892
    logger.debug(util::LogCategory::session, "Destroying connection object");
2,822✔
1893
    ClientImpl& client = get_client();
2,822✔
1894
    client.remove_connection(*this);
2,822✔
1895
    // NOTE: This connection object is now destroyed!
1896
}
2,822✔
1897

1898

1899
std::string ClientImpl::Connection::get_http_request_path() const
1900
{
3,796✔
1901
    using namespace std::string_view_literals;
3,796✔
1902
    const auto param = m_http_request_path_prefix.find('?') == std::string::npos ? "?baas_at="sv : "&baas_at="sv;
2,147,485,445✔
1903

1904
    std::string path;
3,796✔
1905
    path.reserve(m_http_request_path_prefix.size() + param.size() + m_signed_access_token.size());
3,796✔
1906
    path += m_http_request_path_prefix;
3,796✔
1907
    path += param;
3,796✔
1908
    path += m_signed_access_token;
3,796✔
1909

1910
    return path;
3,796✔
1911
}
3,796✔
1912

1913

1914
std::string ClientImpl::Connection::make_logger_prefix(connection_ident_type ident)
1915
{
2,826✔
1916
    return util::format("Connection[%1] ", ident);
2,826✔
1917
}
2,826✔
1918

1919

1920
void ClientImpl::Connection::report_connection_state_change(ConnectionState state,
1921
                                                            std::optional<SessionErrorInfo> error_info)
1922
{
11,186✔
1923
    if (m_force_closed) {
11,186✔
1924
        return;
2,456✔
1925
    }
2,456✔
1926
    auto handler = [=](ClientImpl::Session& sess) {
11,850✔
1927
        SessionImpl& sess_2 = static_cast<SessionImpl&>(sess);
11,850✔
1928
        sess_2.on_connection_state_changed(state, error_info); // Throws
11,850✔
1929
    };
11,850✔
1930
    for_each_active_session(std::move(handler)); // Throws
8,730✔
1931
}
8,730✔
1932

1933

1934
Client::Client(Config config)
1935
    : m_impl{new ClientImpl{std::move(config)}} // Throws
4,908✔
1936
{
9,954✔
1937
}
9,954✔
1938

1939

1940
Client::Client(Client&& client) noexcept
1941
    : m_impl{std::move(client.m_impl)}
1942
{
×
1943
}
×
1944

1945

1946
Client::~Client() noexcept {}
9,954✔
1947

1948

1949
void Client::shutdown() noexcept
1950
{
10,036✔
1951
    m_impl->shutdown();
10,036✔
1952
}
10,036✔
1953

1954
void Client::shutdown_and_wait()
1955
{
772✔
1956
    m_impl->shutdown_and_wait();
772✔
1957
}
772✔
1958

1959
void Client::cancel_reconnect_delay()
1960
{
1,880✔
1961
    m_impl->cancel_reconnect_delay();
1,880✔
1962
}
1,880✔
1963

1964
void Client::voluntary_disconnect_all_connections()
1965
{
12✔
1966
    m_impl->voluntary_disconnect_all_connections();
12✔
1967
}
12✔
1968

1969
bool Client::wait_for_session_terminations_or_client_stopped()
1970
{
9,628✔
1971
    return m_impl->wait_for_session_terminations_or_client_stopped();
9,628✔
1972
}
9,628✔
1973

1974
util::Future<void> Client::notify_session_terminated()
1975
{
56✔
1976
    return m_impl->notify_session_terminated();
56✔
1977
}
56✔
1978

1979
bool Client::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
1980
                                  port_type& port, std::string& path) const
1981
{
4,366✔
1982
    return m_impl->decompose_server_url(url, protocol, address, port, path); // Throws
4,366✔
1983
}
4,366✔
1984

1985

1986
Session::Session(Client& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1987
                 std::shared_ptr<MigrationStore> migration_store, Config&& config)
1988
{
10,466✔
1989
    m_impl = new SessionWrapper{*client.m_impl, std::move(db), std::move(flx_sub_store), std::move(migration_store),
10,466✔
1990
                                std::move(config)}; // Throws
10,466✔
1991
}
10,466✔
1992

1993

1994
void Session::nonsync_transact_notify(version_type new_version)
1995
{
21,178✔
1996
    m_impl->on_commit(new_version); // Throws
21,178✔
1997
}
21,178✔
1998

1999

2000
void Session::cancel_reconnect_delay()
2001
{
32✔
2002
    m_impl->cancel_reconnect_delay(); // Throws
32✔
2003
}
32✔
2004

2005

2006
void Session::async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler handler)
2007
{
5,412✔
2008
    m_impl->async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws
5,412✔
2009
}
5,412✔
2010

2011

2012
bool Session::wait_for_upload_complete_or_client_stopped()
2013
{
12,912✔
2014
    return m_impl->wait_for_upload_complete_or_client_stopped(); // Throws
12,912✔
2015
}
12,912✔
2016

2017

2018
bool Session::wait_for_download_complete_or_client_stopped()
2019
{
10,004✔
2020
    return m_impl->wait_for_download_complete_or_client_stopped(); // Throws
10,004✔
2021
}
10,004✔
2022

2023

2024
void Session::refresh(std::string_view signed_access_token)
2025
{
216✔
2026
    m_impl->refresh(signed_access_token); // Throws
216✔
2027
}
216✔
2028

2029

2030
void Session::abandon() noexcept
2031
{
10,466✔
2032
    REALM_ASSERT(m_impl);
10,466✔
2033
    // Reabsorb the ownership assigned to the applications naked pointer by
2034
    // Session constructor
2035
    util::bind_ptr<SessionWrapper> wrapper{m_impl, util::bind_ptr_base::adopt_tag{}};
10,466✔
2036
    SessionWrapper::abandon(std::move(wrapper));
10,466✔
2037
}
10,466✔
2038

2039
util::Future<std::string> Session::send_test_command(std::string body)
2040
{
68✔
2041
    return m_impl->send_test_command(std::move(body));
68✔
2042
}
68✔
2043

2044
std::string Session::get_appservices_connection_id()
2045
{
72✔
2046
    return m_impl->get_appservices_connection_id();
72✔
2047
}
72✔
2048

2049
std::ostream& operator<<(std::ostream& os, ProxyConfig::Type proxyType)
2050
{
×
2051
    switch (proxyType) {
×
2052
        case ProxyConfig::Type::HTTP:
×
2053
            return os << "HTTP";
×
2054
        case ProxyConfig::Type::HTTPS:
×
2055
            return os << "HTTPS";
×
2056
    }
×
2057
    REALM_TERMINATE("Invalid Proxy Type object.");
2058
}
×
2059

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

© 2026 Coveralls, Inc