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

realm / realm-core / 1812

03 Nov 2023 02:11PM UTC coverage: 91.664% (-0.02%) from 91.68%
1812

push

Evergreen

web-flow
Merge pull request #7117 from realm/release/13.23.3

Core v13.23.3

92098 of 168856 branches covered (0.0%)

230713 of 251695 relevant lines covered (91.66%)

6287111.86 hits per line

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

90.93
/src/realm/sync/client.cpp
1

2
#include <memory>
3
#include <tuple>
4
#include <atomic>
5

6
#include "realm/sync/client_base.hpp"
7
#include "realm/sync/protocol.hpp"
8
#include "realm/util/optional.hpp"
9
#include <realm/sync/client.hpp>
10
#include <realm/sync/config.hpp>
11
#include <realm/sync/noinst/client_reset.hpp>
12
#include <realm/sync/noinst/client_history_impl.hpp>
13
#include <realm/sync/noinst/client_impl_base.hpp>
14
#include <realm/sync/noinst/pending_bootstrap_store.hpp>
15
#include <realm/sync/subscriptions.hpp>
16
#include <realm/util/bind_ptr.hpp>
17
#include <realm/util/circular_buffer.hpp>
18
#include <realm/util/platform_info.hpp>
19
#include <realm/util/thread.hpp>
20
#include <realm/util/uri.hpp>
21
#include <realm/util/value_reset_guard.hpp>
22
#include <realm/version.hpp>
23

24
namespace realm {
25
namespace sync {
26

27
namespace {
28
using namespace realm::util;
29

30

31
// clang-format off
32
using SessionImpl                     = ClientImpl::Session;
33
using SyncTransactCallback            = Session::SyncTransactCallback;
34
using ProgressHandler                 = Session::ProgressHandler;
35
using WaitOperCompletionHandler       = Session::WaitOperCompletionHandler;
36
using ConnectionStateChangeListener   = Session::ConnectionStateChangeListener;
37
using port_type                       = Session::port_type;
38
using connection_ident_type           = std::int_fast64_t;
39
using ProxyConfig                     = SyncConfig::ProxyConfig;
40
// clang-format on
41

42
} // unnamed namespace
43

44

45
// Life cycle states of a session wrapper:
46
//
47
//  - Uninitiated
48
//  - Unactualized
49
//  - Actualized
50
//  - Finalized
51
//
52
// The session wrapper moves from the Uninitiated to the Unactualized state when
53
// it is initiated, i.e., when initiate() is called. This may happen on any
54
// thread.
55
//
56
// The session wrapper moves from the Unactualized to the Actualized state when
57
// it is associated with a session object, i.e., when `m_sess` is made to refer
58
// to an object of type SessionImpl. This always happens on the event loop
59
// thread.
60
//
61
// The session wrapper moves from the Actualized to the Finalized state when it
62
// is dissociated from the session object. This happens in response to the
63
// session wrapper having been abandoned by the application. This always happens
64
// on the event loop thread.
65
//
66
// The session wrapper will exist in the Finalized state only while referenced
67
// from a post handler waiting to be executed.
68
//
69
// If the session wrapper is abandoned by the application while in the
70
// Uninitiated state, it will be destroyed immediately, since no post handlers
71
// can have been scheduled prior to initiation.
72
//
73
// If the session wrapper is abandoned while in the Unactivated state, it will
74
// move immediately to the Finalized state. This may happen on any thread.
75
//
76
// The moving of a session wrapper to, or from the Actualized state always
77
// happen on the event loop thread. All other state transitions may happen on
78
// any thread.
79
//
80
// NOTE: Activation of the session happens no later than during actualization,
81
// and initiation of deactivation happens no earlier than during
82
// finalization. See also activate_session() and initiate_session_deactivation()
83
// in ClientImpl::Connection.
84
class SessionWrapper final : public util::AtomicRefCountBase, DB::CommitListener {
85
public:
86
    SessionWrapper(ClientImpl&, DBRef db, std::shared_ptr<SubscriptionStore>, std::shared_ptr<MigrationStore>,
87
                   Session::Config);
88
    ~SessionWrapper() noexcept;
89

90
    ClientReplication& get_replication() noexcept;
91
    ClientImpl& get_client() noexcept;
92

93
    bool has_flx_subscription_store() const;
94
    SubscriptionStore* get_flx_subscription_store();
95
    PendingBootstrapStore* get_flx_pending_bootstrap_store();
96

97
    MigrationStore* get_migration_store();
98

99
    void set_progress_handler(util::UniqueFunction<ProgressHandler>);
100
    void set_connection_state_change_listener(util::UniqueFunction<ConnectionStateChangeListener>);
101

102
    void initiate();
103

104
    void force_close();
105

106
    void on_commit(version_type new_version) override;
107
    void cancel_reconnect_delay();
108

109
    void async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler);
110
    bool wait_for_upload_complete_or_client_stopped();
111
    bool wait_for_download_complete_or_client_stopped();
112

113
    void refresh(std::string signed_access_token);
114

115
    static void abandon(util::bind_ptr<SessionWrapper>) noexcept;
116

117
    // These are called from ClientImpl
118
    void actualize(ServerEndpoint);
119
    void finalize();
120
    void finalize_before_actualization() noexcept;
121

122
    util::Future<std::string> send_test_command(std::string body);
123

124
    void handle_pending_client_reset_acknowledgement();
125

126
    void update_subscription_version_info();
127

128
    std::string get_appservices_connection_id();
129

130
private:
131
    ClientImpl& m_client;
132
    DBRef m_db;
133
    Replication* m_replication;
134

135
    const ProtocolEnvelope m_protocol_envelope;
136
    const std::string m_server_address;
137
    const port_type m_server_port;
138
    const std::string m_user_id;
139
    const SyncServerMode m_sync_mode;
140
    const std::string m_authorization_header_name;
141
    const std::map<std::string, std::string> m_custom_http_headers;
142
    const bool m_verify_servers_ssl_certificate;
143
    const bool m_simulate_integration_error;
144
    const Optional<std::string> m_ssl_trust_certificate_path;
145
    const std::function<SyncConfig::SSLVerifyCallback> m_ssl_verify_callback;
146
    const size_t m_flx_bootstrap_batch_size_bytes;
147

148
    // This one is different from null when, and only when the session wrapper
149
    // is in ClientImpl::m_abandoned_session_wrappers.
150
    SessionWrapper* m_next = nullptr;
151

152
    // After initiation, these may only be accessed by the event loop thread.
153
    std::string m_http_request_path_prefix;
154
    std::string m_virt_path;
155
    std::string m_signed_access_token;
156

157
    util::Optional<ClientReset> m_client_reset_config;
158

159
    util::Optional<ProxyConfig> m_proxy_config;
160

161
    uint_fast64_t m_last_reported_uploadable_bytes = 0;
162
    util::UniqueFunction<ProgressHandler> m_progress_handler;
163
    util::UniqueFunction<ConnectionStateChangeListener> m_connection_state_change_listener;
164

165
    std::function<SyncClientHookAction(SyncClientHookData data)> m_debug_hook;
166
    bool m_in_debug_hook = false;
167

168
    SessionReason m_session_reason;
169

170
    std::shared_ptr<SubscriptionStore> m_flx_subscription_store;
171
    int64_t m_flx_active_version = 0;
172
    int64_t m_flx_last_seen_version = 0;
173
    int64_t m_flx_pending_mark_version = 0;
174
    std::unique_ptr<PendingBootstrapStore> m_flx_pending_bootstrap_store;
175

176
    std::shared_ptr<MigrationStore> m_migration_store;
177

178
    bool m_initiated = false;
179

180
    // Set to true when this session wrapper is actualized (or when it is
181
    // finalized before proper actualization). It is then never modified again.
182
    //
183
    // A session specific post handler submitted after the initiation of the
184
    // session wrapper (initiate()) will always find that `m_actualized` is
185
    // true. This is the case, because the scheduling of such a post handler
186
    // will have been preceded by the triggering of
187
    // `ClientImpl::m_actualize_and_finalize` (in
188
    // ClientImpl::register_unactualized_session_wrapper()), which ensures that
189
    // ClientImpl::actualize_and_finalize_session_wrappers() gets to execute
190
    // before the post handler. If the session wrapper is no longer in
191
    // `ClientImpl::m_unactualized_session_wrappers` when
192
    // ClientImpl::actualize_and_finalize_session_wrappers() executes, it must
193
    // have been abandoned already, but in that case,
194
    // finalize_before_actualization() has already been called.
195
    bool m_actualized = false;
196

197
    bool m_force_closed = false;
198

199
    bool m_suspended = false;
200

201
    // Has the SessionWrapper been finalized?
202
    bool m_finalized = false;
203

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

210
    // Set to point to an activated session object during actualization of the
211
    // session wrapper. Set to null during finalization of the session
212
    // wrapper. Both modifications are guaranteed to be performed by the event
213
    // loop thread.
214
    //
215
    // If a session specific post handler, that is submitted after the
216
    // initiation of the session wrapper, sees that `m_sess` is null, it can
217
    // conclude that the session wrapper has been both abandoned and
218
    // finalized. This is true, because the scheduling of such a post handler
219
    // will have been preceded by the triggering of
220
    // `ClientImpl::m_actualize_and_finalize` (in
221
    // ClientImpl::register_unactualized_session_wrapper()), which ensures that
222
    // ClientImpl::actualize_and_finalize_session_wrappers() gets to execute
223
    // before the post handler, so the session wrapper must have been actualized
224
    // unless it was already abandoned by the application. If it was abandoned
225
    // before it was actualized, it will already have been finalized by
226
    // finalize_before_actualization().
227
    //
228
    // Must only be accessed from the event loop thread.
229
    SessionImpl* m_sess = nullptr;
230

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

236
    // `m_target_*load_mark` and `m_reached_*load_mark` are protected by
237
    // `m_client.m_mutex`. `m_staged_*load_mark` must only be accessed by the
238
    // event loop thread.
239
    std::int_fast64_t m_target_upload_mark = 0, m_target_download_mark = 0;
240
    std::int_fast64_t m_staged_upload_mark = 0, m_staged_download_mark = 0;
241
    std::int_fast64_t m_reached_upload_mark = 0, m_reached_download_mark = 0;
242

243
    void on_sync_progress();
244
    void on_upload_completion();
245
    void on_download_completion();
246
    void on_suspended(const SessionErrorInfo& error_info);
247
    void on_resumed();
248
    void on_connection_state_changed(ConnectionState, const util::Optional<SessionErrorInfo>&);
249
    void on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state);
250
    void on_flx_sync_error(int64_t version, std::string_view err_msg);
251
    void on_flx_sync_version_complete(int64_t version);
252

253
    void report_progress(bool only_if_new_uploadable_data = false);
254

255
    friend class SessionWrapperStack;
256
    friend class ClientImpl::Session;
257
};
258

259

260
// ################ SessionWrapperStack ################
261

262
inline bool SessionWrapperStack::empty() const noexcept
263
{
×
264
    return !m_back;
×
265
}
×
266

267

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

275

276
inline util::bind_ptr<SessionWrapper> SessionWrapperStack::pop() noexcept
277
{
24,006✔
278
    util::bind_ptr<SessionWrapper> w{m_back, util::bind_ptr_base::adopt_tag{}};
24,006✔
279
    if (m_back) {
24,006✔
280
        m_back = m_back->m_next;
9,632✔
281
        w->m_next = nullptr;
9,632✔
282
    }
9,632✔
283
    return w;
24,006✔
284
}
24,006✔
285

286

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

295

296
inline SessionWrapperStack::SessionWrapperStack(SessionWrapperStack&& q) noexcept
297
    : m_back{q.m_back}
298
{
299
    q.m_back = nullptr;
300
}
301

302

303
SessionWrapperStack::~SessionWrapperStack()
304
{
23,352✔
305
    clear();
23,352✔
306
}
23,352✔
307

308

309
// ################ ClientImpl ################
310

311

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

4,420✔
317
    shutdown_and_wait();
8,978✔
318
    // Session wrappers are removed from m_unactualized_session_wrappers as they
4,420✔
319
    // are abandoned.
4,420✔
320
    REALM_ASSERT(m_stopped);
8,978✔
321
    REALM_ASSERT(m_unactualized_session_wrappers.empty());
8,978✔
322
}
8,978✔
323

324

325
void ClientImpl::cancel_reconnect_delay()
326
{
1,664✔
327
    // Thread safety required
946✔
328
    post([this](Status status) {
1,664✔
329
        if (status == ErrorCodes::OperationAborted)
1,664✔
330
            return;
×
331
        else if (!status.is_ok())
1,664✔
332
            throw Exception(status);
×
333

946✔
334
        for (auto& p : m_server_slots) {
1,664✔
335
            ServerSlot& slot = p.second;
1,664✔
336
            if (m_one_connection_per_session) {
1,664✔
337
                REALM_ASSERT(!slot.connection);
×
338
                for (const auto& p : slot.alt_connections) {
×
339
                    ClientImpl::Connection& conn = *p.second;
×
340
                    conn.resume_active_sessions(); // Throws
×
341
                    conn.cancel_reconnect_delay(); // Throws
×
342
                }
×
343
            }
×
344
            else {
1,664✔
345
                REALM_ASSERT(slot.alt_connections.empty());
1,664✔
346
                if (slot.connection) {
1,664✔
347
                    ClientImpl::Connection& conn = *slot.connection;
1,660✔
348
                    conn.resume_active_sessions(); // Throws
1,660✔
349
                    conn.cancel_reconnect_delay(); // Throws
1,660✔
350
                }
1,660✔
351
                else {
4✔
352
                    slot.reconnect_info.reset();
4✔
353
                }
4✔
354
            }
1,664✔
355
        }
1,664✔
356
    }); // Throws
1,664✔
357
}
1,664✔
358

359

360
void ClientImpl::voluntary_disconnect_all_connections()
361
{
12✔
362
    auto done_pf = util::make_promise_future<void>();
12✔
363
    post([this, promise = std::move(done_pf.promise)](Status status) mutable {
12✔
364
        if (status == ErrorCodes::OperationAborted) {
12✔
365
            return;
×
366
        }
×
367

6✔
368
        REALM_ASSERT(status.is_ok());
12✔
369

6✔
370
        try {
12✔
371
            for (auto& p : m_server_slots) {
12✔
372
                ServerSlot& slot = p.second;
12✔
373
                if (m_one_connection_per_session) {
12✔
374
                    REALM_ASSERT(!slot.connection);
×
375
                    for (const auto& p : slot.alt_connections) {
×
376
                        ClientImpl::Connection& conn = *p.second;
×
377
                        if (conn.get_state() == ConnectionState::disconnected) {
×
378
                            continue;
×
379
                        }
×
380
                        conn.voluntary_disconnect();
×
381
                    }
×
382
                }
×
383
                else {
12✔
384
                    REALM_ASSERT(slot.alt_connections.empty());
12✔
385
                    if (!slot.connection) {
12✔
386
                        continue;
×
387
                    }
×
388
                    ClientImpl::Connection& conn = *slot.connection;
12✔
389
                    if (conn.get_state() == ConnectionState::disconnected) {
12✔
390
                        continue;
×
391
                    }
×
392
                    conn.voluntary_disconnect();
12✔
393
                }
12✔
394
            }
12✔
395
        }
12✔
396
        catch (...) {
6✔
397
            promise.set_error(exception_to_status());
×
398
            return;
×
399
        }
×
400
        promise.emplace_value();
12✔
401
    });
12✔
402
    done_pf.future.get();
12✔
403
}
12✔
404

405

406
bool ClientImpl::wait_for_session_terminations_or_client_stopped()
407
{
370✔
408
    // Thread safety required
34✔
409

34✔
410
    {
370✔
411
        std::lock_guard lock{m_mutex};
370✔
412
        m_sessions_terminated = false;
370✔
413
    }
370✔
414

34✔
415
    // The technique employed here relies on the fact that
34✔
416
    // actualize_and_finalize_session_wrappers() must get to execute at least
34✔
417
    // once before the post handler submitted below gets to execute, but still
34✔
418
    // at a time where all session wrappers, that are abandoned prior to the
34✔
419
    // execution of wait_for_session_terminations_or_client_stopped(), have been
34✔
420
    // added to `m_abandoned_session_wrappers`.
34✔
421
    //
34✔
422
    // To see that this is the case, consider a session wrapper that was
34✔
423
    // abandoned before wait_for_session_terminations_or_client_stopped() was
34✔
424
    // invoked. Then the session wrapper will have been added to
34✔
425
    // `m_abandoned_session_wrappers`, and an invocation of
34✔
426
    // actualize_and_finalize_session_wrappers() will have been scheduled. The
34✔
427
    // guarantees mentioned in the documentation of Trigger then ensure
34✔
428
    // that at least one execution of actualize_and_finalize_session_wrappers()
34✔
429
    // will happen after the session wrapper has been added to
34✔
430
    // `m_abandoned_session_wrappers`, but before the post handler submitted
34✔
431
    // below gets to execute.
34✔
432
    post([this](Status status) mutable {
370✔
433
        if (status == ErrorCodes::OperationAborted)
370✔
434
            return;
×
435
        else if (!status.is_ok())
370✔
436
            throw Exception(status);
×
437

34✔
438
        std::lock_guard lock{m_mutex};
370✔
439
        m_sessions_terminated = true;
370✔
440
        m_wait_or_client_stopped_cond.notify_all();
370✔
441
    }); // Throws
370✔
442

34✔
443
    bool completion_condition_was_satisfied;
370✔
444
    {
370✔
445
        std::unique_lock lock{m_mutex};
370✔
446
        while (!m_sessions_terminated && !m_stopped)
702✔
447
            m_wait_or_client_stopped_cond.wait(lock);
332✔
448
        completion_condition_was_satisfied = !m_stopped;
370✔
449
    }
370✔
450
    return completion_condition_was_satisfied;
370✔
451
}
370✔
452

453

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

462
void ClientImpl::shutdown_and_wait()
463
{
9,738✔
464
    shutdown();
9,738✔
465
    std::unique_lock lock{m_drain_mutex};
9,738✔
466
    if (m_drained) {
9,738✔
467
        return;
756✔
468
    }
756✔
469

4,422✔
470
    logger.debug("Waiting for %1 connections to drain", m_num_connections);
8,982✔
471
    m_drain_cv.wait(lock, [&] {
19,704✔
472
        return m_num_connections == 0 && m_outstanding_posts == 0;
19,704✔
473
    });
19,704✔
474

4,422✔
475
    m_drained = true;
8,982✔
476
}
8,982✔
477

478
void ClientImpl::shutdown() noexcept
479
{
18,794✔
480
    {
18,794✔
481
        std::lock_guard lock{m_mutex};
18,794✔
482
        if (m_stopped)
18,794✔
483
            return;
9,816✔
484
        m_stopped = true;
8,978✔
485
        m_wait_or_client_stopped_cond.notify_all();
8,978✔
486
    }
8,978✔
487

4,420✔
488
    drain_connections_on_loop();
8,978✔
489
}
8,978✔
490

491

492
void ClientImpl::register_unactualized_session_wrapper(SessionWrapper* wrapper, ServerEndpoint endpoint)
493
{
9,804✔
494
    // Thread safety required.
4,730✔
495

4,730✔
496
    std::lock_guard lock{m_mutex};
9,804✔
497
    REALM_ASSERT(m_actualize_and_finalize);
9,804✔
498
    m_unactualized_session_wrappers.emplace(wrapper, std::move(endpoint)); // Throws
9,804✔
499
    bool retrigger = !m_actualize_and_finalize_needed;
9,804✔
500
    m_actualize_and_finalize_needed = true;
9,804✔
501
    // The conditional triggering needs to happen before releasing the mutex,
4,730✔
502
    // because if two threads call register_unactualized_session_wrapper()
4,730✔
503
    // roughly concurrently, then only the first one is guaranteed to be asked
4,730✔
504
    // to retrigger, but that retriggering must have happened before the other
4,730✔
505
    // thread returns from register_unactualized_session_wrapper().
4,730✔
506
    //
4,730✔
507
    // Note that a similar argument applies when two threads call
4,730✔
508
    // register_abandoned_session_wrapper(), and when one thread calls one of
4,730✔
509
    // them and another thread call the other.
4,730✔
510
    if (retrigger)
9,804✔
511
        m_actualize_and_finalize->trigger();
5,476✔
512
}
9,804✔
513

514

515
void ClientImpl::register_abandoned_session_wrapper(util::bind_ptr<SessionWrapper> wrapper) noexcept
516
{
9,802✔
517
    // Thread safety required.
4,728✔
518

4,728✔
519
    std::lock_guard lock{m_mutex};
9,802✔
520
    REALM_ASSERT(m_actualize_and_finalize);
9,802✔
521

4,728✔
522
    // If the session wrapper has not yet been actualized (on the event loop
4,728✔
523
    // thread), it can be immediately finalized. This ensures that we will
4,728✔
524
    // generally not actualize a session wrapper that has already been
4,728✔
525
    // abandoned.
4,728✔
526
    auto i = m_unactualized_session_wrappers.find(wrapper.get());
9,802✔
527
    if (i != m_unactualized_session_wrappers.end()) {
9,802✔
528
        m_unactualized_session_wrappers.erase(i);
172✔
529
        wrapper->finalize_before_actualization();
172✔
530
        return;
172✔
531
    }
172✔
532
    m_abandoned_session_wrappers.push(std::move(wrapper));
9,630✔
533
    bool retrigger = !m_actualize_and_finalize_needed;
9,630✔
534
    m_actualize_and_finalize_needed = true;
9,630✔
535
    // The conditional triggering needs to happen before releasing the
4,640✔
536
    // mutex. See implementation of register_unactualized_session_wrapper() for
4,640✔
537
    // details.
4,640✔
538
    if (retrigger)
9,630✔
539
        m_actualize_and_finalize->trigger();
8,898✔
540
}
9,630✔
541

542

543
// Must be called from the event loop thread.
544
void ClientImpl::actualize_and_finalize_session_wrappers()
545
{
14,370✔
546
    std::map<SessionWrapper*, ServerEndpoint> unactualized_session_wrappers;
14,370✔
547
    SessionWrapperStack abandoned_session_wrappers;
14,370✔
548
    bool stopped;
14,370✔
549
    {
14,370✔
550
        std::lock_guard lock{m_mutex};
14,370✔
551
        m_actualize_and_finalize_needed = false;
14,370✔
552
        swap(m_unactualized_session_wrappers, unactualized_session_wrappers);
14,370✔
553
        swap(m_abandoned_session_wrappers, abandoned_session_wrappers);
14,370✔
554
        stopped = m_stopped;
14,370✔
555
    }
14,370✔
556
    // Note, we need to finalize old session wrappers before we actualize new
7,334✔
557
    // ones. This ensures that deactivation of old sessions is initiated before
7,334✔
558
    // new session are activated. This, in turn, ensures that the server does
7,334✔
559
    // not see two overlapping sessions for the same local Realm file.
7,334✔
560
    while (util::bind_ptr<SessionWrapper> wrapper = abandoned_session_wrappers.pop())
24,000✔
561
        wrapper->finalize(); // Throws
9,630✔
562
    if (stopped) {
14,370✔
563
        for (auto& p : unactualized_session_wrappers) {
402✔
564
            SessionWrapper& wrapper = *p.first;
4✔
565
            wrapper.finalize_before_actualization();
4✔
566
        }
4✔
567
        return;
758✔
568
    }
758✔
569
    for (auto& p : unactualized_session_wrappers) {
13,612✔
570
        SessionWrapper& wrapper = *p.first;
9,628✔
571
        ServerEndpoint server_endpoint = std::move(p.second);
9,628✔
572
        wrapper.actualize(std::move(server_endpoint)); // Throws
9,628✔
573
    }
9,628✔
574
}
13,612✔
575

576

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

4,636✔
589
    // TODO: enable multiplexing with proxies
4,636✔
590
    if (server_slot.connection && !m_one_connection_per_session && !proxy_config) {
9,620✔
591
        // Use preexisting connection
3,476✔
592
        REALM_ASSERT(server_slot.alt_connections.empty());
7,162✔
593
        return *server_slot.connection;
7,162✔
594
    }
7,162✔
595

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

619

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

1,162✔
641
    {
2,462✔
642
        std::lock_guard lk(m_drain_mutex);
2,462✔
643
        REALM_ASSERT(m_num_connections);
2,462✔
644
        --m_num_connections;
2,462✔
645
        m_drain_cv.notify_all();
2,462✔
646
    }
2,462✔
647
}
2,462✔
648

649

650
// ################ SessionImpl ################
651

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

660
void SessionImpl::on_connection_state_changed(ConnectionState state,
661
                                              const util::Optional<SessionErrorInfo>& error_info)
662
{
10,358✔
663
    // Only used to report errors back to the SyncSession while the Session is active
5,390✔
664
    if (m_state == SessionImpl::Active) {
10,358✔
665
        m_wrapper.on_connection_state_changed(state, error_info); // Throws
10,358✔
666
    }
10,358✔
667
}
10,358✔
668

669

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

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

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

691
ClientReplication& SessionImpl::access_realm()
692
{
109,846✔
693
    // Can only be called if the session is active or being activated
56,608✔
694
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
109,846✔
695
    return m_wrapper.get_replication();
109,846✔
696
}
109,846✔
697

698
util::Optional<ClientReset>& SessionImpl::get_client_reset_config() noexcept
699
{
9,622✔
700
    // Can only be called if the session is active or being activated
4,638✔
701
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
9,622✔
702
    return m_wrapper.m_client_reset_config;
9,622✔
703
}
9,622✔
704

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

712
void SessionImpl::initiate_integrate_changesets(std::uint_fast64_t downloadable_bytes, DownloadBatchState batch_state,
713
                                                const SyncProgress& progress, const ReceivedChangesets& changesets)
714
{
41,560✔
715
    // Ignore the call if the session is not active
22,312✔
716
    if (m_state != State::Active) {
41,560✔
717
        return;
×
718
    }
×
719

22,312✔
720
    try {
41,560✔
721
        bool simulate_integration_error = (m_wrapper.m_simulate_integration_error && !changesets.empty());
41,560!
722
        if (simulate_integration_error) {
41,560✔
723
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
×
724
        }
×
725
        version_type client_version;
41,560✔
726
        if (REALM_LIKELY(!get_client().is_dry_run())) {
41,560✔
727
            VersionInfo version_info;
41,560✔
728
            ClientReplication& repl = access_realm(); // Throws
41,560✔
729
            integrate_changesets(repl, progress, downloadable_bytes, changesets, version_info,
41,560✔
730
                                 batch_state); // Throws
41,560✔
731
            client_version = version_info.realm_version;
41,560✔
732
        }
41,560✔
733
        else {
×
734
            // Fake it for "dry run" mode
735
            client_version = m_last_version_available + 1;
×
736
        }
×
737
        on_changesets_integrated(client_version, progress); // Throws
41,560✔
738
    }
41,560✔
739
    catch (const IntegrationException& e) {
22,324✔
740
        on_integration_failure(e);
24✔
741
    }
24✔
742
    m_wrapper.on_sync_progress(); // Throws
41,560✔
743
}
41,558✔
744

745

746
void SessionImpl::on_upload_completion()
747
{
14,662✔
748
    // Ignore the call if the session is not active
7,248✔
749
    if (m_state == State::Active) {
14,662✔
750
        m_wrapper.on_upload_completion(); // Throws
14,662✔
751
    }
14,662✔
752
}
14,662✔
753

754

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

763

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

772

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

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

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

797
bool SessionImpl::process_flx_bootstrap_message(const SyncProgress& progress, DownloadBatchState batch_state,
798
                                                int64_t query_version, const ReceivedChangesets& received_changesets)
799
{
43,142✔
800
    // Ignore the call if the session is not active
23,104✔
801
    if (m_state != State::Active) {
43,142✔
802
        return false;
×
803
    }
×
804

23,104✔
805
    if (is_steady_state_download_message(batch_state, query_version)) {
43,142✔
806
        return false;
41,560✔
807
    }
41,560✔
808

792✔
809
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
1,582✔
810
    util::Optional<SyncProgress> maybe_progress;
1,582✔
811
    if (batch_state == DownloadBatchState::LastInBatch) {
1,582✔
812
        maybe_progress = progress;
1,422✔
813
    }
1,422✔
814

792✔
815
    bool new_batch = false;
1,582✔
816
    try {
1,582✔
817
        bootstrap_store->add_batch(query_version, std::move(maybe_progress), received_changesets, &new_batch);
1,582✔
818
    }
1,582✔
819
    catch (const LogicError& ex) {
792✔
820
        if (ex.code() == ErrorCodes::LimitExceeded) {
×
821
            IntegrationException ex(ErrorCodes::LimitExceeded,
×
822
                                    "bootstrap changeset too large to store in pending bootstrap store",
×
823
                                    ProtocolError::bad_changeset_size);
×
824
            on_integration_failure(ex);
×
825
            return true;
×
826
        }
×
827
        throw;
×
828
    }
×
829

792✔
830
    // If we've started a new batch and there is more to come, call on_flx_sync_progress to mark the subscription as
792✔
831
    // bootstrapping.
792✔
832
    if (new_batch && batch_state == DownloadBatchState::MoreToCome) {
1,582✔
833
        on_flx_sync_progress(query_version, DownloadBatchState::MoreToCome);
40✔
834
    }
40✔
835

792✔
836
    auto hook_action = call_debug_hook(SyncClientHookEvent::BootstrapMessageProcessed, progress, query_version,
1,582✔
837
                                       batch_state, received_changesets.size());
1,582✔
838
    if (hook_action == SyncClientHookAction::EarlyReturn) {
1,582✔
839
        return true;
12✔
840
    }
12✔
841
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
1,570✔
842

786✔
843
    if (batch_state == DownloadBatchState::MoreToCome) {
1,570✔
844
        return true;
156✔
845
    }
156✔
846

708✔
847
    try {
1,414✔
848
        process_pending_flx_bootstrap();
1,414✔
849
    }
1,414✔
850
    catch (const IntegrationException& e) {
712✔
851
        on_integration_failure(e);
8✔
852
    }
8✔
853

708✔
854
    return true;
1,414✔
855
}
1,414✔
856

857

858
void SessionImpl::process_pending_flx_bootstrap()
859
{
11,038✔
860
    // Ignore the call if not a flx session or session is not active
5,346✔
861
    if (!m_is_flx_sync_session || m_state != State::Active) {
11,038✔
862
        return;
8,614✔
863
    }
8,614✔
864
    // Should never be called if session is not active
1,212✔
865
    REALM_ASSERT_EX(m_state == SessionImpl::Active, m_state);
2,424✔
866
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
2,424✔
867
    if (!bootstrap_store->has_pending()) {
2,424✔
868
        return;
990✔
869
    }
990✔
870

716✔
871
    auto pending_batch_stats = bootstrap_store->pending_stats();
1,434✔
872
    logger.info("Begin processing pending FLX bootstrap for query version %1. (changesets: %2, original total "
1,434✔
873
                "changeset size: %3)",
1,434✔
874
                pending_batch_stats.query_version, pending_batch_stats.pending_changesets,
1,434✔
875
                pending_batch_stats.pending_changeset_bytes);
1,434✔
876
    auto& history = access_realm().get_history();
1,434✔
877
    VersionInfo new_version;
1,434✔
878
    SyncProgress progress;
1,434✔
879
    int64_t query_version = -1;
1,434✔
880
    size_t changesets_processed = 0;
1,434✔
881

716✔
882
    // Used to commit each batch after it was transformed.
716✔
883
    TransactionRef transact = get_db()->start_write();
1,434✔
884
    while (bootstrap_store->has_pending()) {
2,980✔
885
        auto start_time = std::chrono::steady_clock::now();
1,562✔
886
        auto pending_batch = bootstrap_store->peek_pending(m_wrapper.m_flx_bootstrap_batch_size_bytes);
1,562✔
887
        if (!pending_batch.progress) {
1,562✔
888
            logger.info("Incomplete pending bootstrap found for query version %1", pending_batch.query_version);
8✔
889
            // Close the write transation before clearing the bootstrap store to avoid a deadlock because the
4✔
890
            // bootstrap store requires a write transaction itself.
4✔
891
            transact->close();
8✔
892
            bootstrap_store->clear();
8✔
893
            return;
8✔
894
        }
8✔
895

778✔
896
        auto batch_state =
1,554✔
897
            pending_batch.remaining_changesets > 0 ? DownloadBatchState::MoreToCome : DownloadBatchState::LastInBatch;
1,486✔
898
        uint64_t downloadable_bytes = 0;
1,554✔
899
        query_version = pending_batch.query_version;
1,554✔
900
        bool simulate_integration_error =
1,554✔
901
            (m_wrapper.m_simulate_integration_error && !pending_batch.changesets.empty());
1,554✔
902
        if (simulate_integration_error) {
1,554✔
903
            throw IntegrationException(ErrorCodes::BadChangeset, "simulated failure", ProtocolError::bad_changeset);
8✔
904
        }
8✔
905

774✔
906
        history.integrate_server_changesets(
1,546✔
907
            *pending_batch.progress, &downloadable_bytes, pending_batch.changesets, new_version, batch_state, logger,
1,546✔
908
            transact, [&](const TransactionRef& tr, util::Span<Changeset> changesets_applied) {
1,544✔
909
                REALM_ASSERT_3(changesets_applied.size(), <=, pending_batch.changesets.size());
1,542✔
910
                bootstrap_store->pop_front_pending(tr, changesets_applied.size());
1,542✔
911
            });
1,542✔
912
        progress = *pending_batch.progress;
1,546✔
913
        changesets_processed += pending_batch.changesets.size();
1,546✔
914
        auto duration = std::chrono::steady_clock::now() - start_time;
1,546✔
915

774✔
916
        auto action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
1,546✔
917
                                      batch_state, pending_batch.changesets.size());
1,546✔
918
        REALM_ASSERT_EX(action == SyncClientHookAction::NoAction, action);
1,546✔
919

774✔
920
        logger.info("Integrated %1 changesets from pending bootstrap for query version %2, producing client version "
1,546✔
921
                    "%3 in %4 ms. %5 changesets remaining in bootstrap",
1,546✔
922
                    pending_batch.changesets.size(), pending_batch.query_version, new_version.realm_version,
1,546✔
923
                    std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(),
1,546✔
924
                    pending_batch.remaining_changesets);
1,546✔
925
    }
1,546✔
926
    on_changesets_integrated(new_version.realm_version, progress);
1,426✔
927

708✔
928
    REALM_ASSERT_3(query_version, !=, -1);
1,418✔
929
    m_wrapper.on_sync_progress();
1,418✔
930
    on_flx_sync_progress(query_version, DownloadBatchState::LastInBatch);
1,418✔
931

708✔
932
    auto action = call_debug_hook(SyncClientHookEvent::BootstrapProcessed, progress, query_version,
1,418✔
933
                                  DownloadBatchState::LastInBatch, changesets_processed);
1,418✔
934
    // NoAction/EarlyReturn are both valid no-op actions to take here.
708✔
935
    REALM_ASSERT_EX(action == SyncClientHookAction::NoAction || action == SyncClientHookAction::EarlyReturn, action);
1,418✔
936
}
1,418✔
937

938
void SessionImpl::on_flx_sync_error(int64_t version, std::string_view err_msg)
939
{
16✔
940
    // Ignore the call if the session is not active
8✔
941
    if (m_state == State::Active) {
16✔
942
        m_wrapper.on_flx_sync_error(version, err_msg);
16✔
943
    }
16✔
944
}
16✔
945

946
void SessionImpl::on_flx_sync_progress(int64_t version, DownloadBatchState batch_state)
947
{
1,450✔
948
    // Ignore the call if the session is not active
726✔
949
    if (m_state == State::Active) {
1,450✔
950
        m_wrapper.on_flx_sync_progress(version, batch_state);
1,450✔
951
    }
1,450✔
952
}
1,450✔
953

954
SubscriptionStore* SessionImpl::get_flx_subscription_store()
955
{
13,542✔
956
    // Should never be called if session is not active
6,982✔
957
    REALM_ASSERT_EX(m_state == State::Active, m_state);
13,542✔
958
    return m_wrapper.get_flx_subscription_store();
13,542✔
959
}
13,542✔
960

961
MigrationStore* SessionImpl::get_migration_store()
962
{
58,162✔
963
    // Should never be called if session is not active
30,864✔
964
    REALM_ASSERT_EX(m_state == State::Active, m_state);
58,162✔
965
    return m_wrapper.get_migration_store();
58,162✔
966
}
58,162✔
967

968
void SessionImpl::on_flx_sync_version_complete(int64_t version)
969
{
104✔
970
    // Ignore the call if the session is not active
52✔
971
    if (m_state == State::Active) {
104✔
972
        m_wrapper.on_flx_sync_version_complete(version);
104✔
973
    }
104✔
974
}
104✔
975

976
SyncClientHookAction SessionImpl::call_debug_hook(const SyncClientHookData& data)
977
{
846✔
978
    // Should never be called if session is not active
430✔
979
    REALM_ASSERT_EX(m_state == State::Active, m_state);
846✔
980

430✔
981
    // Make sure we don't call the debug hook recursively.
430✔
982
    if (m_wrapper.m_in_debug_hook) {
846✔
983
        return SyncClientHookAction::NoAction;
×
984
    }
×
985
    m_wrapper.m_in_debug_hook = true;
846✔
986
    auto in_hook_guard = util::make_scope_exit([&]() noexcept {
846✔
987
        m_wrapper.m_in_debug_hook = false;
846✔
988
    });
846✔
989

430✔
990
    auto action = m_wrapper.m_debug_hook(data);
846✔
991
    switch (action) {
846✔
992
        case realm::SyncClientHookAction::SuspendWithRetryableError: {
✔
993
            SessionErrorInfo err_info(Status{ErrorCodes::RuntimeError, "hook requested error"}, IsFatal{false});
×
994
            err_info.server_requests_action = ProtocolErrorInfo::Action::Transient;
×
995

996
            auto err_processing_err = receive_error_message(err_info);
×
997
            REALM_ASSERT_EX(err_processing_err.is_ok(), err_processing_err);
×
998
            return SyncClientHookAction::EarlyReturn;
×
999
        }
×
1000
        case realm::SyncClientHookAction::TriggerReconnect: {
24✔
1001
            get_connection().voluntary_disconnect();
24✔
1002
            return SyncClientHookAction::EarlyReturn;
24✔
1003
        }
×
1004
        default:
822✔
1005
            return action;
822✔
1006
    }
846✔
1007
}
846✔
1008

1009
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const SyncProgress& progress,
1010
                                                  int64_t query_version, DownloadBatchState batch_state,
1011
                                                  size_t num_changesets)
1012
{
89,246✔
1013
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
89,246✔
1014
        return SyncClientHookAction::NoAction;
88,478✔
1015
    }
88,478✔
1016
    if (REALM_UNLIKELY(m_state != State::Active)) {
768✔
1017
        return SyncClientHookAction::NoAction;
×
1018
    }
×
1019

388✔
1020
    SyncClientHookData data;
768✔
1021
    data.event = event;
768✔
1022
    data.batch_state = batch_state;
768✔
1023
    data.progress = progress;
768✔
1024
    data.num_changesets = num_changesets;
768✔
1025
    data.query_version = query_version;
768✔
1026

388✔
1027
    return call_debug_hook(data);
768✔
1028
}
768✔
1029

1030
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event, const ProtocolErrorInfo& error_info)
1031
{
900✔
1032
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
900✔
1033
        return SyncClientHookAction::NoAction;
822✔
1034
    }
822✔
1035
    if (REALM_UNLIKELY(m_state != State::Active)) {
78✔
1036
        return SyncClientHookAction::NoAction;
×
1037
    }
×
1038

42✔
1039
    SyncClientHookData data;
78✔
1040
    data.event = event;
78✔
1041
    data.batch_state = DownloadBatchState::SteadyState;
78✔
1042
    data.progress = m_progress;
78✔
1043
    data.num_changesets = 0;
78✔
1044
    data.query_version = 0;
78✔
1045
    data.error_info = &error_info;
78✔
1046

42✔
1047
    return call_debug_hook(data);
78✔
1048
}
78✔
1049

1050
bool SessionImpl::is_steady_state_download_message(DownloadBatchState batch_state, int64_t query_version)
1051
{
86,296✔
1052
    // Should never be called if session is not active
46,214✔
1053
    REALM_ASSERT_EX(m_state == State::Active, m_state);
86,296✔
1054
    if (batch_state == DownloadBatchState::SteadyState) {
86,296✔
1055
        return true;
41,560✔
1056
    }
41,560✔
1057

23,902✔
1058
    if (!m_is_flx_sync_session) {
44,736✔
1059
        return true;
40,540✔
1060
    }
40,540✔
1061

2,118✔
1062
    // If this is a steady state DOWNLOAD, no need for special handling.
2,118✔
1063
    if (batch_state == DownloadBatchState::LastInBatch && query_version == m_wrapper.m_flx_active_version) {
4,196✔
1064
        return true;
1,024✔
1065
    }
1,024✔
1066

1,588✔
1067
    return false;
3,172✔
1068
}
3,172✔
1069

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

26✔
1076
    try {
52✔
1077
        auto json_body = nlohmann::json::parse(body.begin(), body.end());
52✔
1078
        if (auto it = json_body.find("command"); it == json_body.end() || !it->is_string()) {
52✔
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()) {
48✔
1083
            return Status{ErrorCodes::LogicError, "Only valid fields in a test command are \"command\" and \"args\""};
×
1084
        }
×
1085
    }
4✔
1086
    catch (const nlohmann::json::parse_error& e) {
4✔
1087
        return Status{ErrorCodes::LogicError, util::format("Invalid json input to send_test_command: %1", e.what())};
4✔
1088
    }
4✔
1089

22✔
1090
    auto pf = util::make_promise_future<std::string>();
44✔
1091

22✔
1092
    get_client().post([this, promise = std::move(pf.promise), body = std::move(body)](Status status) mutable {
44✔
1093
        // Includes operation_aborted
22✔
1094
        if (!status.is_ok())
44✔
1095
            promise.set_error(status);
×
1096

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

22✔
1102
    return std::move(pf.future);
44✔
1103
}
44✔
1104

1105
// ################ SessionWrapper ################
1106

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

5,306✔
1141
    update_subscription_version_info();
10,956✔
1142
}
10,956✔
1143

1144
SessionWrapper::~SessionWrapper() noexcept
1145
{
10,956✔
1146
    if (m_db && m_actualized) {
10,956✔
1147
        m_db->remove_commit_listener(this);
172✔
1148
        m_db->release_sync_agent();
172✔
1149
    }
172✔
1150
}
10,956✔
1151

1152

1153
inline ClientReplication& SessionWrapper::get_replication() noexcept
1154
{
109,852✔
1155
    REALM_ASSERT(m_db);
109,852✔
1156
    return static_cast<ClientReplication&>(*m_replication);
109,852✔
1157
}
109,852✔
1158

1159

1160
inline ClientImpl& SessionWrapper::get_client() noexcept
1161
{
72✔
1162
    return m_client;
72✔
1163
}
72✔
1164

1165
bool SessionWrapper::has_flx_subscription_store() const
1166
{
1,450✔
1167
    return static_cast<bool>(m_flx_subscription_store);
1,450✔
1168
}
1,450✔
1169

1170
void SessionWrapper::on_flx_sync_error(int64_t version, std::string_view err_msg)
1171
{
16✔
1172
    REALM_ASSERT(!m_finalized);
16✔
1173
    auto mut_subs = get_flx_subscription_store()->get_mutable_by_version(version);
16✔
1174
    mut_subs.update_state(SubscriptionSet::State::Error, err_msg);
16✔
1175
    mut_subs.commit();
16✔
1176
}
16✔
1177

1178
void SessionWrapper::on_flx_sync_version_complete(int64_t version)
1179
{
1,514✔
1180
    REALM_ASSERT(!m_finalized);
1,514✔
1181
    m_flx_last_seen_version = version;
1,514✔
1182
    m_flx_active_version = version;
1,514✔
1183
}
1,514✔
1184

1185
void SessionWrapper::on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state)
1186
{
1,450✔
1187
    if (!has_flx_subscription_store()) {
1,450✔
1188
        return;
×
1189
    }
×
1190
    REALM_ASSERT(!m_finalized);
1,450✔
1191
    REALM_ASSERT(new_version >= m_flx_last_seen_version);
1,450✔
1192
    REALM_ASSERT(new_version >= m_flx_active_version);
1,450✔
1193
    REALM_ASSERT(batch_state != DownloadBatchState::SteadyState);
1,450✔
1194

726✔
1195
    SubscriptionSet::State new_state = SubscriptionSet::State::Uncommitted; // Initialize to make compiler happy
1,450✔
1196

726✔
1197
    switch (batch_state) {
1,450✔
1198
        case DownloadBatchState::SteadyState:
✔
1199
            // Cannot be called with this value.
1200
            REALM_UNREACHABLE();
1201
        case DownloadBatchState::LastInBatch:
1,410✔
1202
            if (m_flx_active_version == new_version) {
1,410✔
1203
                return;
×
1204
            }
×
1205
            on_flx_sync_version_complete(new_version);
1,410✔
1206
            if (new_version == 0) {
1,410✔
1207
                new_state = SubscriptionSet::State::Complete;
640✔
1208
            }
640✔
1209
            else {
770✔
1210
                new_state = SubscriptionSet::State::AwaitingMark;
770✔
1211
                m_flx_pending_mark_version = new_version;
770✔
1212
            }
770✔
1213
            break;
1,410✔
1214
        case DownloadBatchState::MoreToCome:
726✔
1215
            if (m_flx_last_seen_version == new_version) {
40✔
1216
                return;
×
1217
            }
×
1218

20✔
1219
            m_flx_last_seen_version = new_version;
40✔
1220
            new_state = SubscriptionSet::State::Bootstrapping;
40✔
1221
            break;
40✔
1222
    }
1,450✔
1223

726✔
1224
    auto mut_subs = get_flx_subscription_store()->get_mutable_by_version(new_version);
1,450✔
1225
    mut_subs.update_state(new_state);
1,450✔
1226
    mut_subs.commit();
1,450✔
1227
}
1,450✔
1228

1229
SubscriptionStore* SessionWrapper::get_flx_subscription_store()
1230
{
15,008✔
1231
    REALM_ASSERT(!m_finalized);
15,008✔
1232
    return m_flx_subscription_store.get();
15,008✔
1233
}
15,008✔
1234

1235
PendingBootstrapStore* SessionWrapper::get_flx_pending_bootstrap_store()
1236
{
4,002✔
1237
    REALM_ASSERT(!m_finalized);
4,002✔
1238
    return m_flx_pending_bootstrap_store.get();
4,002✔
1239
}
4,002✔
1240

1241
MigrationStore* SessionWrapper::get_migration_store()
1242
{
58,164✔
1243
    REALM_ASSERT(!m_finalized);
58,164✔
1244
    return m_migration_store.get();
58,164✔
1245
}
58,164✔
1246

1247
inline void SessionWrapper::set_progress_handler(util::UniqueFunction<ProgressHandler> handler)
1248
{
3,424✔
1249
    REALM_ASSERT(!m_initiated);
3,424✔
1250
    m_progress_handler = std::move(handler);
3,424✔
1251
}
3,424✔
1252

1253

1254
inline void
1255
SessionWrapper::set_connection_state_change_listener(util::UniqueFunction<ConnectionStateChangeListener> listener)
1256
{
11,052✔
1257
    REALM_ASSERT(!m_initiated);
11,052✔
1258
    m_connection_state_change_listener = std::move(listener);
11,052✔
1259
}
11,052✔
1260

1261

1262
void SessionWrapper::initiate()
1263
{
9,804✔
1264
    REALM_ASSERT(!m_initiated);
9,804✔
1265
    ServerEndpoint server_endpoint{m_protocol_envelope, m_server_address, m_server_port, m_user_id, m_sync_mode};
9,804✔
1266
    m_client.register_unactualized_session_wrapper(this, std::move(server_endpoint)); // Throws
9,804✔
1267
    m_initiated = true;
9,804✔
1268
    m_db->add_commit_listener(this);
9,804✔
1269
}
9,804✔
1270

1271

1272
void SessionWrapper::on_commit(version_type new_version)
1273
{
104,038✔
1274
    // Thread safety required
52,666✔
1275
    REALM_ASSERT(m_initiated);
104,038✔
1276

52,666✔
1277
    if (REALM_UNLIKELY(m_finalized || m_force_closed)) {
104,038✔
1278
        return;
4✔
1279
    }
4✔
1280

52,664✔
1281
    util::bind_ptr<SessionWrapper> self{this};
104,034✔
1282
    m_client.post([self = std::move(self), new_version](Status status) {
104,040✔
1283
        if (status == ErrorCodes::OperationAborted)
104,040✔
1284
            return;
×
1285
        else if (!status.is_ok())
104,040✔
1286
            throw Exception(status);
×
1287

52,664✔
1288
        REALM_ASSERT(self->m_actualized);
104,040✔
1289
        if (REALM_UNLIKELY(!self->m_sess))
104,040✔
1290
            return; // Already finalized
53,170✔
1291
        SessionImpl& sess = *self->m_sess;
103,140✔
1292
        sess.recognize_sync_version(new_version); // Throws
103,140✔
1293
        bool only_if_new_uploadable_data = true;
103,140✔
1294
        self->report_progress(only_if_new_uploadable_data); // Throws
103,140✔
1295
    });
103,140✔
1296
}
104,034✔
1297

1298

1299
void SessionWrapper::cancel_reconnect_delay()
1300
{
12✔
1301
    // Thread safety required
6✔
1302
    REALM_ASSERT(m_initiated);
12✔
1303

6✔
1304
    if (REALM_UNLIKELY(m_finalized || m_force_closed)) {
12✔
1305
        return;
×
1306
    }
×
1307

6✔
1308
    util::bind_ptr<SessionWrapper> self{this};
12✔
1309
    m_client.post([self = std::move(self)](Status status) {
12✔
1310
        if (status == ErrorCodes::OperationAborted)
12✔
1311
            return;
×
1312
        else if (!status.is_ok())
12✔
1313
            throw Exception(status);
×
1314

6✔
1315
        REALM_ASSERT(self->m_actualized);
12✔
1316
        if (REALM_UNLIKELY(!self->m_sess))
12✔
1317
            return; // Already finalized
6✔
1318
        SessionImpl& sess = *self->m_sess;
12✔
1319
        sess.cancel_resumption_delay(); // Throws
12✔
1320
        ClientImpl::Connection& conn = sess.get_connection();
12✔
1321
        conn.cancel_reconnect_delay(); // Throws
12✔
1322
    });                                // Throws
12✔
1323
}
12✔
1324

1325
void SessionWrapper::async_wait_for(bool upload_completion, bool download_completion,
1326
                                    WaitOperCompletionHandler handler)
1327
{
4,352✔
1328
    REALM_ASSERT(upload_completion || download_completion);
4,352✔
1329
    REALM_ASSERT(m_initiated);
4,352✔
1330
    REALM_ASSERT(!m_finalized);
4,352✔
1331

2,090✔
1332
    util::bind_ptr<SessionWrapper> self{this};
4,352✔
1333
    m_client.post([self = std::move(self), handler = std::move(handler), upload_completion,
4,352✔
1334
                   download_completion](Status status) mutable {
4,352✔
1335
        if (status == ErrorCodes::OperationAborted)
4,352✔
1336
            return;
×
1337
        else if (!status.is_ok())
4,352✔
1338
            throw Exception(status);
×
1339

2,090✔
1340
        REALM_ASSERT(self->m_actualized);
4,352✔
1341
        if (REALM_UNLIKELY(!self->m_sess)) {
4,352✔
1342
            // Already finalized
38✔
1343
            handler({ErrorCodes::OperationAborted, "Session finalized before callback could run"}); // Throws
76✔
1344
            return;
76✔
1345
        }
76✔
1346
        if (upload_completion) {
4,276✔
1347
            if (download_completion) {
2,272✔
1348
                // Wait for upload and download completion
140✔
1349
                self->m_sync_completion_handlers.push_back(std::move(handler)); // Throws
278✔
1350
            }
278✔
1351
            else {
1,994✔
1352
                // Wait for upload completion only
910✔
1353
                self->m_upload_completion_handlers.push_back(std::move(handler)); // Throws
1,994✔
1354
            }
1,994✔
1355
        }
2,272✔
1356
        else {
2,004✔
1357
            // Wait for download completion only
1,002✔
1358
            self->m_download_completion_handlers.push_back(std::move(handler)); // Throws
2,004✔
1359
        }
2,004✔
1360
        SessionImpl& sess = *self->m_sess;
4,276✔
1361
        if (upload_completion)
4,276✔
1362
            sess.request_upload_completion_notification(); // Throws
2,272✔
1363
        if (download_completion)
4,276✔
1364
            sess.request_download_completion_notification(); // Throws
2,282✔
1365
    });                                                      // Throws
4,276✔
1366
}
4,352✔
1367

1368

1369
bool SessionWrapper::wait_for_upload_complete_or_client_stopped()
1370
{
12,996✔
1371
    // Thread safety required
6,498✔
1372
    REALM_ASSERT(m_initiated);
12,996✔
1373
    REALM_ASSERT(!m_finalized);
12,996✔
1374

6,498✔
1375
    std::int_fast64_t target_mark;
12,996✔
1376
    {
12,996✔
1377
        std::lock_guard lock{m_client.m_mutex};
12,996✔
1378
        target_mark = ++m_target_upload_mark;
12,996✔
1379
    }
12,996✔
1380

6,498✔
1381
    util::bind_ptr<SessionWrapper> self{this};
12,996✔
1382
    m_client.post([self = std::move(self), target_mark](Status status) {
12,996✔
1383
        if (status == ErrorCodes::OperationAborted)
12,996✔
1384
            return;
×
1385
        else if (!status.is_ok())
12,996✔
1386
            throw Exception(status);
×
1387

6,498✔
1388
        REALM_ASSERT(self->m_actualized);
12,996✔
1389
        // The session wrapper may already have been finalized. This can only
6,498✔
1390
        // happen if it was abandoned, but in that case, the call of
6,498✔
1391
        // wait_for_upload_complete_or_client_stopped() must have returned
6,498✔
1392
        // already.
6,498✔
1393
        if (REALM_UNLIKELY(!self->m_sess))
12,996✔
1394
            return;
6,508✔
1395
        if (target_mark > self->m_staged_upload_mark) {
12,986✔
1396
            self->m_staged_upload_mark = target_mark;
12,986✔
1397
            SessionImpl& sess = *self->m_sess;
12,986✔
1398
            sess.request_upload_completion_notification(); // Throws
12,986✔
1399
        }
12,986✔
1400
    }); // Throws
12,986✔
1401

6,498✔
1402
    bool completion_condition_was_satisfied;
12,996✔
1403
    {
12,996✔
1404
        std::unique_lock lock{m_client.m_mutex};
12,996✔
1405
        while (m_reached_upload_mark < target_mark && !m_client.m_stopped)
33,070✔
1406
            m_client.m_wait_or_client_stopped_cond.wait(lock);
20,074✔
1407
        completion_condition_was_satisfied = !m_client.m_stopped;
12,996✔
1408
    }
12,996✔
1409
    return completion_condition_was_satisfied;
12,996✔
1410
}
12,996✔
1411

1412

1413
bool SessionWrapper::wait_for_download_complete_or_client_stopped()
1414
{
10,092✔
1415
    // Thread safety required
5,048✔
1416
    REALM_ASSERT(m_initiated);
10,092✔
1417
    REALM_ASSERT(!m_finalized);
10,092✔
1418

5,048✔
1419
    std::int_fast64_t target_mark;
10,092✔
1420
    {
10,092✔
1421
        std::lock_guard lock{m_client.m_mutex};
10,092✔
1422
        target_mark = ++m_target_download_mark;
10,092✔
1423
    }
10,092✔
1424

5,048✔
1425
    util::bind_ptr<SessionWrapper> self{this};
10,092✔
1426
    m_client.post([self = std::move(self), target_mark](Status status) {
10,092✔
1427
        if (status == ErrorCodes::OperationAborted)
10,092✔
1428
            return;
×
1429
        else if (!status.is_ok())
10,092✔
1430
            throw Exception(status);
×
1431

5,048✔
1432
        REALM_ASSERT(self->m_actualized);
10,092✔
1433
        // The session wrapper may already have been finalized. This can only
5,048✔
1434
        // happen if it was abandoned, but in that case, the call of
5,048✔
1435
        // wait_for_download_complete_or_client_stopped() must have returned
5,048✔
1436
        // already.
5,048✔
1437
        if (REALM_UNLIKELY(!self->m_sess))
10,092✔
1438
            return;
5,078✔
1439
        if (target_mark > self->m_staged_download_mark) {
10,032✔
1440
            self->m_staged_download_mark = target_mark;
10,032✔
1441
            SessionImpl& sess = *self->m_sess;
10,032✔
1442
            sess.request_download_completion_notification(); // Throws
10,032✔
1443
        }
10,032✔
1444
    }); // Throws
10,032✔
1445

5,048✔
1446
    bool completion_condition_was_satisfied;
10,092✔
1447
    {
10,092✔
1448
        std::unique_lock lock{m_client.m_mutex};
10,092✔
1449
        while (m_reached_download_mark < target_mark && !m_client.m_stopped)
20,622✔
1450
            m_client.m_wait_or_client_stopped_cond.wait(lock);
10,530✔
1451
        completion_condition_was_satisfied = !m_client.m_stopped;
10,092✔
1452
    }
10,092✔
1453
    return completion_condition_was_satisfied;
10,092✔
1454
}
10,092✔
1455

1456

1457
void SessionWrapper::refresh(std::string signed_access_token)
1458
{
208✔
1459
    // Thread safety required
104✔
1460
    REALM_ASSERT(m_initiated);
208✔
1461
    REALM_ASSERT(!m_finalized);
208✔
1462

104✔
1463
    m_client.post([self = util::bind_ptr(this), token = std::move(signed_access_token)](Status status) {
208✔
1464
        if (status == ErrorCodes::OperationAborted)
208✔
1465
            return;
×
1466
        else if (!status.is_ok())
208✔
1467
            throw Exception(status);
×
1468

104✔
1469
        REALM_ASSERT(self->m_actualized);
208✔
1470
        if (REALM_UNLIKELY(!self->m_sess))
208✔
1471
            return; // Already finalized
104✔
1472
        self->m_signed_access_token = std::move(token);
208✔
1473
        SessionImpl& sess = *self->m_sess;
208✔
1474
        ClientImpl::Connection& conn = sess.get_connection();
208✔
1475
        // FIXME: This only makes sense when each session uses a separate connection.
104✔
1476
        conn.update_connect_info(self->m_http_request_path_prefix, self->m_signed_access_token); // Throws
208✔
1477
        sess.cancel_resumption_delay();                                                          // Throws
208✔
1478
        conn.cancel_reconnect_delay();                                                           // Throws
208✔
1479
    });
208✔
1480
}
208✔
1481

1482

1483
inline void SessionWrapper::abandon(util::bind_ptr<SessionWrapper> wrapper) noexcept
1484
{
10,954✔
1485
    if (wrapper->m_initiated) {
10,954✔
1486
        ClientImpl& client = wrapper->m_client;
9,802✔
1487
        client.register_abandoned_session_wrapper(std::move(wrapper));
9,802✔
1488
    }
9,802✔
1489
}
10,954✔
1490

1491

1492
// Must be called from event loop thread
1493
void SessionWrapper::actualize(ServerEndpoint endpoint)
1494
{
9,628✔
1495
    REALM_ASSERT(!m_actualized);
9,628✔
1496
    REALM_ASSERT(!m_sess);
9,628✔
1497
    // Cannot be actualized if it's already been finalized or force closed
4,640✔
1498
    REALM_ASSERT(!m_finalized);
9,628✔
1499
    REALM_ASSERT(!m_force_closed);
9,628✔
1500
    try {
9,628✔
1501
        m_db->claim_sync_agent();
9,628✔
1502
    }
9,628✔
1503
    catch (const MultipleSyncAgents&) {
4,642✔
1504
        finalize_before_actualization();
4✔
1505
        throw;
4✔
1506
    }
4✔
1507
    auto sync_mode = endpoint.server_mode;
9,624✔
1508

4,638✔
1509
    bool was_created = false;
9,624✔
1510
    ClientImpl::Connection& conn = m_client.get_connection(
9,624✔
1511
        std::move(endpoint), m_authorization_header_name, m_custom_http_headers, m_verify_servers_ssl_certificate,
9,624✔
1512
        m_ssl_trust_certificate_path, m_ssl_verify_callback, m_proxy_config,
9,624✔
1513
        was_created); // Throws
9,624✔
1514
    try {
9,624✔
1515
        // FIXME: This only makes sense when each session uses a separate connection.
4,638✔
1516
        conn.update_connect_info(m_http_request_path_prefix, m_signed_access_token);    // Throws
9,624✔
1517
        std::unique_ptr<SessionImpl> sess = std::make_unique<SessionImpl>(*this, conn); // Throws
9,624✔
1518
        if (sync_mode == SyncServerMode::FLX) {
9,624✔
1519
            m_flx_pending_bootstrap_store = std::make_unique<PendingBootstrapStore>(m_db, sess->logger);
1,006✔
1520
        }
1,006✔
1521

4,638✔
1522
        sess->logger.info("Binding '%1' to '%2'", m_db->get_path(), m_virt_path); // Throws
9,624✔
1523
        m_sess = sess.get();
9,624✔
1524
        conn.activate_session(std::move(sess)); // Throws
9,624✔
1525
    }
9,624✔
1526
    catch (...) {
4,638✔
1527
        if (was_created)
×
1528
            m_client.remove_connection(conn);
×
1529

1530
        finalize_before_actualization();
×
1531
        throw;
×
1532
    }
×
1533

4,638✔
1534
    m_actualized = true;
9,624✔
1535
    if (was_created)
9,624✔
1536
        conn.activate(); // Throws
2,462✔
1537

4,638✔
1538
    if (m_connection_state_change_listener) {
9,624✔
1539
        ConnectionState state = conn.get_state();
9,604✔
1540
        if (state != ConnectionState::disconnected) {
9,604✔
1541
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,002✔
1542
            if (state == ConnectionState::connected)
7,002✔
1543
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
6,760✔
1544
        }
7,002✔
1545
    }
9,604✔
1546

4,638✔
1547
    if (!m_client_reset_config)
9,624✔
1548
        report_progress(); // Throws
9,286✔
1549
}
9,624✔
1550

1551
void SessionWrapper::force_close()
1552
{
150✔
1553
    if (m_force_closed || m_finalized) {
150✔
1554
        return;
×
1555
    }
×
1556
    REALM_ASSERT(m_actualized);
150✔
1557
    REALM_ASSERT(m_sess);
150✔
1558
    m_force_closed = true;
150✔
1559

74✔
1560
    ClientImpl::Connection& conn = m_sess->get_connection();
150✔
1561
    conn.initiate_session_deactivation(m_sess); // Throws
150✔
1562

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

1573
// Must be called from event loop thread
1574
void SessionWrapper::finalize()
1575
{
9,632✔
1576
    REALM_ASSERT(m_actualized);
9,632✔
1577

4,642✔
1578
    // Already finalized?
4,642✔
1579
    if (m_finalized) {
9,632✔
1580
        return;
×
1581
    }
×
1582

4,642✔
1583
    // Must be before marking as finalized as we expect m_finalized == false in on_change()
4,642✔
1584
    m_db->remove_commit_listener(this);
9,632✔
1585

4,642✔
1586
    m_finalized = true;
9,632✔
1587

4,642✔
1588
    if (!m_force_closed) {
9,632✔
1589
        REALM_ASSERT(m_sess);
9,474✔
1590
        ClientImpl::Connection& conn = m_sess->get_connection();
9,474✔
1591
        conn.initiate_session_deactivation(m_sess); // Throws
9,474✔
1592

4,564✔
1593
        // Delete the pending bootstrap store since it uses a reference to the logger in m_sess
4,564✔
1594
        m_flx_pending_bootstrap_store.reset();
9,474✔
1595
        // Clear the subscription and migration store refs since they are owned by SyncSession
4,564✔
1596
        m_flx_subscription_store.reset();
9,474✔
1597
        m_migration_store.reset();
9,474✔
1598
        m_sess = nullptr;
9,474✔
1599
    }
9,474✔
1600

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

4,642✔
1607
    // All outstanding wait operations must be canceled
4,642✔
1608
    while (!m_upload_completion_handlers.empty()) {
10,006✔
1609
        auto handler = std::move(m_upload_completion_handlers.back());
374✔
1610
        m_upload_completion_handlers.pop_back();
374✔
1611
        handler(
374✔
1612
            {ErrorCodes::OperationAborted, "Sync session is being finalized before upload was complete"}); // Throws
374✔
1613
    }
374✔
1614
    while (!m_download_completion_handlers.empty()) {
9,792✔
1615
        auto handler = std::move(m_download_completion_handlers.back());
160✔
1616
        m_download_completion_handlers.pop_back();
160✔
1617
        handler(
160✔
1618
            {ErrorCodes::OperationAborted, "Sync session is being finalized before download was complete"}); // Throws
160✔
1619
    }
160✔
1620
    while (!m_sync_completion_handlers.empty()) {
9,646✔
1621
        auto handler = std::move(m_sync_completion_handlers.back());
14✔
1622
        m_sync_completion_handlers.pop_back();
14✔
1623
        handler({ErrorCodes::OperationAborted, "Sync session is being finalized before sync was complete"}); // Throws
14✔
1624
    }
14✔
1625
}
9,632✔
1626

1627

1628
// Must be called only when an unactualized session wrapper becomes abandoned.
1629
//
1630
// Called with a lock on `m_client.m_mutex`.
1631
inline void SessionWrapper::finalize_before_actualization() noexcept
1632
{
180✔
1633
    REALM_ASSERT(!m_sess);
180✔
1634
    m_actualized = true;
180✔
1635
    m_force_closed = true;
180✔
1636
}
180✔
1637

1638

1639
inline void SessionWrapper::on_sync_progress()
1640
{
42,968✔
1641
    REALM_ASSERT(!m_finalized);
42,968✔
1642
    m_reliable_download_progress = true;
42,968✔
1643
    report_progress(); // Throws
42,968✔
1644
}
42,968✔
1645

1646

1647
void SessionWrapper::on_upload_completion()
1648
{
14,662✔
1649
    REALM_ASSERT(!m_finalized);
14,662✔
1650
    while (!m_upload_completion_handlers.empty()) {
16,366✔
1651
        auto handler = std::move(m_upload_completion_handlers.back());
1,704✔
1652
        m_upload_completion_handlers.pop_back();
1,704✔
1653
        handler(Status::OK()); // Throws
1,704✔
1654
    }
1,704✔
1655
    while (!m_sync_completion_handlers.empty()) {
14,842✔
1656
        auto handler = std::move(m_sync_completion_handlers.back());
180✔
1657
        m_download_completion_handlers.push_back(std::move(handler)); // Throws
180✔
1658
        m_sync_completion_handlers.pop_back();
180✔
1659
    }
180✔
1660
    std::lock_guard lock{m_client.m_mutex};
14,662✔
1661
    if (m_staged_upload_mark > m_reached_upload_mark) {
14,662✔
1662
        m_reached_upload_mark = m_staged_upload_mark;
12,958✔
1663
        m_client.m_wait_or_client_stopped_cond.notify_all();
12,958✔
1664
    }
12,958✔
1665
}
14,662✔
1666

1667

1668
void SessionWrapper::on_download_completion()
1669
{
15,416✔
1670
    while (!m_download_completion_handlers.empty()) {
17,440✔
1671
        auto handler = std::move(m_download_completion_handlers.back());
2,024✔
1672
        m_download_completion_handlers.pop_back();
2,024✔
1673
        handler(Status::OK()); // Throws
2,024✔
1674
    }
2,024✔
1675
    while (!m_sync_completion_handlers.empty()) {
15,500✔
1676
        auto handler = std::move(m_sync_completion_handlers.back());
84✔
1677
        m_upload_completion_handlers.push_back(std::move(handler)); // Throws
84✔
1678
        m_sync_completion_handlers.pop_back();
84✔
1679
    }
84✔
1680

7,602✔
1681
    if (m_flx_subscription_store && m_flx_pending_mark_version != SubscriptionSet::EmptyVersion) {
15,416✔
1682
        m_sess->logger.debug("Marking query version %1 as complete after receiving MARK message",
656✔
1683
                             m_flx_pending_mark_version);
656✔
1684
        auto mutable_subs = m_flx_subscription_store->get_mutable_by_version(m_flx_pending_mark_version);
656✔
1685
        mutable_subs.update_state(SubscriptionSet::State::Complete);
656✔
1686
        mutable_subs.commit();
656✔
1687
        m_flx_pending_mark_version = SubscriptionSet::EmptyVersion;
656✔
1688
    }
656✔
1689

7,602✔
1690
    std::lock_guard lock{m_client.m_mutex};
15,416✔
1691
    if (m_staged_download_mark > m_reached_download_mark) {
15,416✔
1692
        m_reached_download_mark = m_staged_download_mark;
9,962✔
1693
        m_client.m_wait_or_client_stopped_cond.notify_all();
9,962✔
1694
    }
9,962✔
1695
}
15,416✔
1696

1697

1698
void SessionWrapper::on_suspended(const SessionErrorInfo& error_info)
1699
{
924✔
1700
    REALM_ASSERT(!m_finalized);
924✔
1701
    m_suspended = true;
924✔
1702
    if (m_connection_state_change_listener) {
924✔
1703
        m_connection_state_change_listener(ConnectionState::disconnected, error_info); // Throws
924✔
1704
    }
924✔
1705
}
924✔
1706

1707

1708
void SessionWrapper::on_resumed()
1709
{
392✔
1710
    REALM_ASSERT(!m_finalized);
392✔
1711
    m_suspended = false;
392✔
1712
    if (m_connection_state_change_listener) {
392✔
1713
        ClientImpl::Connection& conn = m_sess->get_connection();
392✔
1714
        if (conn.get_state() != ConnectionState::disconnected) {
392✔
1715
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
392✔
1716
            if (conn.get_state() == ConnectionState::connected)
392✔
1717
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
392✔
1718
        }
392✔
1719
    }
392✔
1720
}
392✔
1721

1722

1723
void SessionWrapper::on_connection_state_changed(ConnectionState state,
1724
                                                 const util::Optional<SessionErrorInfo>& error_info)
1725
{
10,354✔
1726
    if (m_connection_state_change_listener) {
10,354✔
1727
        if (!m_suspended)
10,344✔
1728
            m_connection_state_change_listener(state, error_info); // Throws
10,344✔
1729
    }
10,344✔
1730
}
10,354✔
1731

1732

1733
void SessionWrapper::report_progress(bool only_if_new_uploadable_data)
1734
{
155,390✔
1735
    REALM_ASSERT(!m_finalized);
155,390✔
1736
    REALM_ASSERT(m_sess);
155,390✔
1737

79,756✔
1738
    if (!m_progress_handler)
155,390✔
1739
        return;
110,964✔
1740

20,382✔
1741
    std::uint_fast64_t downloaded_bytes = 0;
44,426✔
1742
    std::uint_fast64_t downloadable_bytes = 0;
44,426✔
1743
    std::uint_fast64_t uploaded_bytes = 0;
44,426✔
1744
    std::uint_fast64_t uploadable_bytes = 0;
44,426✔
1745
    std::uint_fast64_t snapshot_version = 0;
44,426✔
1746
    ClientHistory::get_upload_download_bytes(m_db.get(), downloaded_bytes, downloadable_bytes, uploaded_bytes,
44,426✔
1747
                                             uploadable_bytes, snapshot_version);
44,426✔
1748

20,382✔
1749
    // If this progress notification was triggered by a commit being made we
20,382✔
1750
    // only want to send it if the uploadable bytes has actually increased,
20,382✔
1751
    // and not if it was an empty commit.
20,382✔
1752
    if (only_if_new_uploadable_data && m_last_reported_uploadable_bytes == uploadable_bytes)
44,426✔
1753
        return;
30,962✔
1754
    m_last_reported_uploadable_bytes = uploadable_bytes;
13,464✔
1755

5,674✔
1756
    // uploadable_bytes is uploaded + remaining to upload, while downloadable_bytes
5,674✔
1757
    // is only the remaining to download. This is confusing, so make them use
5,674✔
1758
    // the same units.
5,674✔
1759
    std::uint_fast64_t total_bytes = downloaded_bytes + downloadable_bytes;
13,464✔
1760

5,674✔
1761
    m_sess->logger.debug("Progress handler called, downloaded = %1, "
13,464✔
1762
                         "downloadable(total) = %2, uploaded = %3, "
13,464✔
1763
                         "uploadable = %4, reliable_download_progress = %5, "
13,464✔
1764
                         "snapshot version = %6",
13,464✔
1765
                         downloaded_bytes, total_bytes, uploaded_bytes, uploadable_bytes,
13,464✔
1766
                         m_reliable_download_progress, snapshot_version);
13,464✔
1767

5,674✔
1768
    // FIXME: Why is this boolean status communicated to the application as
5,674✔
1769
    // a 64-bit integer? Also, the name `progress_version` is confusing.
5,674✔
1770
    std::uint_fast64_t progress_version = (m_reliable_download_progress ? 1 : 0);
9,958✔
1771
    m_progress_handler(downloaded_bytes, total_bytes, uploaded_bytes, uploadable_bytes, progress_version,
13,464✔
1772
                       snapshot_version);
13,464✔
1773
}
13,464✔
1774

1775
util::Future<std::string> SessionWrapper::send_test_command(std::string body)
1776
{
52✔
1777
    if (!m_sess) {
52✔
1778
        return Status{ErrorCodes::RuntimeError, "session must be activated to send a test command"};
×
1779
    }
×
1780

26✔
1781
    return m_sess->send_test_command(std::move(body));
52✔
1782
}
52✔
1783

1784
void SessionWrapper::handle_pending_client_reset_acknowledgement()
1785
{
292✔
1786
    REALM_ASSERT(!m_finalized);
292✔
1787

146✔
1788
    auto pending_reset = [&] {
292✔
1789
        auto ft = m_db->start_frozen();
292✔
1790
        return _impl::client_reset::has_pending_reset(ft);
292✔
1791
    }();
292✔
1792
    REALM_ASSERT(pending_reset);
292✔
1793
    m_sess->logger.info("Tracking pending client reset of type \"%1\" from %2", pending_reset->type,
292✔
1794
                        pending_reset->time);
292✔
1795
    util::bind_ptr<SessionWrapper> self(this);
292✔
1796
    async_wait_for(true, true, [self = std::move(self), pending_reset = *pending_reset](Status status) {
292✔
1797
        if (status == ErrorCodes::OperationAborted) {
292✔
1798
            return;
152✔
1799
        }
152✔
1800
        auto& logger = self->m_sess->logger;
140✔
1801
        if (!status.is_ok()) {
140✔
1802
            logger.error("Error while tracking client reset acknowledgement: %1", status);
×
1803
            return;
×
1804
        }
×
1805

70✔
1806
        auto wt = self->m_db->start_write();
140✔
1807
        auto cur_pending_reset = _impl::client_reset::has_pending_reset(wt);
140✔
1808
        if (!cur_pending_reset) {
140✔
1809
            logger.debug(
×
1810
                "Was going to remove client reset tracker for type \"%1\" from %2, but it was already removed",
×
1811
                pending_reset.type, pending_reset.time);
×
1812
            return;
×
1813
        }
×
1814
        else if (cur_pending_reset->type != pending_reset.type || cur_pending_reset->time != pending_reset.time) {
140✔
1815
            logger.debug(
×
1816
                "Was going to remove client reset tracker for type \"%1\" from %2, but found type \"%3\" from %4.",
×
1817
                pending_reset.type, pending_reset.time, cur_pending_reset->type, cur_pending_reset->time);
×
1818
        }
×
1819
        else {
140✔
1820
            logger.debug("Client reset of type \"%1\" from %2 has been acknowledged by the server. "
140✔
1821
                         "Removing cycle detection tracker.",
140✔
1822
                         pending_reset.type, pending_reset.time);
140✔
1823
        }
140✔
1824
        _impl::client_reset::remove_pending_client_resets(wt);
140✔
1825
        wt->commit();
140✔
1826
    });
140✔
1827
}
292✔
1828

1829
void SessionWrapper::update_subscription_version_info()
1830
{
11,224✔
1831
    if (!m_flx_subscription_store)
11,224✔
1832
        return;
10,118✔
1833
    auto versions_info = m_flx_subscription_store->get_version_info();
1,106✔
1834
    m_flx_active_version = versions_info.active;
1,106✔
1835
    m_flx_pending_mark_version = versions_info.pending_mark;
1,106✔
1836
}
1,106✔
1837

1838
std::string SessionWrapper::get_appservices_connection_id()
1839
{
72✔
1840
    auto pf = util::make_promise_future<std::string>();
72✔
1841
    REALM_ASSERT(m_initiated);
72✔
1842

36✔
1843
    util::bind_ptr<SessionWrapper> self(this);
72✔
1844
    get_client().post([self, promise = std::move(pf.promise)](Status status) mutable {
72✔
1845
        if (!status.is_ok()) {
72✔
1846
            promise.set_error(status);
×
1847
            return;
×
1848
        }
×
1849

36✔
1850
        if (!self->m_sess) {
72✔
1851
            promise.set_error({ErrorCodes::RuntimeError, "session already finalized"});
×
1852
            return;
×
1853
        }
×
1854

36✔
1855
        promise.emplace_value(self->m_sess->get_connection().get_active_appservices_connection_id());
72✔
1856
    });
72✔
1857

36✔
1858
    return pf.future.get();
72✔
1859
}
72✔
1860

1861
// ################ ClientImpl::Connection ################
1862

1863
ClientImpl::Connection::Connection(ClientImpl& client, connection_ident_type ident, ServerEndpoint endpoint,
1864
                                   const std::string& authorization_header_name,
1865
                                   const std::map<std::string, std::string>& custom_http_headers,
1866
                                   bool verify_servers_ssl_certificate,
1867
                                   Optional<std::string> ssl_trust_certificate_path,
1868
                                   std::function<SSLVerifyCallback> ssl_verify_callback,
1869
                                   Optional<ProxyConfig> proxy_config, ReconnectInfo reconnect_info)
1870
    : logger_ptr{std::make_shared<util::PrefixLogger>(make_logger_prefix(ident), client.logger_ptr)} // Throws
1871
    , logger{*logger_ptr}
1872
    , m_client{client}
1873
    , m_verify_servers_ssl_certificate{verify_servers_ssl_certificate}    // DEPRECATED
1874
    , m_ssl_trust_certificate_path{std::move(ssl_trust_certificate_path)} // DEPRECATED
1875
    , m_ssl_verify_callback{std::move(ssl_verify_callback)}               // DEPRECATED
1876
    , m_proxy_config{std::move(proxy_config)}                             // DEPRECATED
1877
    , m_reconnect_info{reconnect_info}
1878
    , m_session_history{}
1879
    , m_ident{ident}
1880
    , m_server_endpoint{std::move(endpoint)}
1881
    , m_authorization_header_name{authorization_header_name} // DEPRECATED
1882
    , m_custom_http_headers{custom_http_headers}             // DEPRECATED
1883
{
2,462✔
1884
    m_on_idle = m_client.create_trigger([this](Status status) {
2,466✔
1885
        if (status == ErrorCodes::OperationAborted)
2,466✔
1886
            return;
×
1887
        else if (!status.is_ok())
2,466✔
1888
            throw Exception(status);
×
1889

1,162✔
1890
        REALM_ASSERT(m_activated);
2,466✔
1891
        if (m_state == ConnectionState::disconnected && m_num_active_sessions == 0) {
2,466✔
1892
            on_idle(); // Throws
2,462✔
1893
            // Connection object may be destroyed now.
1,162✔
1894
        }
2,462✔
1895
    });
2,466✔
1896
}
2,462✔
1897

1898
inline connection_ident_type ClientImpl::Connection::get_ident() const noexcept
1899
{
12✔
1900
    return m_ident;
12✔
1901
}
12✔
1902

1903

1904
inline const ServerEndpoint& ClientImpl::Connection::get_server_endpoint() const noexcept
1905
{
2,462✔
1906
    return m_server_endpoint;
2,462✔
1907
}
2,462✔
1908

1909
inline void ClientImpl::Connection::update_connect_info(const std::string& http_request_path_prefix,
1910
                                                        const std::string& signed_access_token)
1911
{
9,830✔
1912
    m_http_request_path_prefix = http_request_path_prefix; // Throws (copy)
9,830✔
1913
    m_signed_access_token = signed_access_token;           // Throws (copy)
9,830✔
1914
}
9,830✔
1915

1916

1917
void ClientImpl::Connection::resume_active_sessions()
1918
{
1,660✔
1919
    auto handler = [=](ClientImpl::Session& sess) {
3,316✔
1920
        sess.cancel_resumption_delay(); // Throws
3,316✔
1921
    };
3,316✔
1922
    for_each_active_session(std::move(handler)); // Throws
1,660✔
1923
}
1,660✔
1924

1925
void ClientImpl::Connection::on_idle()
1926
{
2,462✔
1927
    logger.debug("Destroying connection object");
2,462✔
1928
    ClientImpl& client = get_client();
2,462✔
1929
    client.remove_connection(*this);
2,462✔
1930
    // NOTE: This connection object is now destroyed!
1,162✔
1931
}
2,462✔
1932

1933

1934
std::string ClientImpl::Connection::get_http_request_path() const
1935
{
3,272✔
1936
    using namespace std::string_view_literals;
3,272✔
1937
    const auto param = m_http_request_path_prefix.find('?') == std::string::npos ? "?baas_at="sv : "&baas_at="sv;
3,268✔
1938

1,626✔
1939
    std::string path;
3,272✔
1940
    path.reserve(m_http_request_path_prefix.size() + param.size() + m_signed_access_token.size());
3,272✔
1941
    path += m_http_request_path_prefix;
3,272✔
1942
    path += param;
3,272✔
1943
    path += m_signed_access_token;
3,272✔
1944

1,626✔
1945
    return path;
3,272✔
1946
}
3,272✔
1947

1948

1949
std::string ClientImpl::Connection::make_logger_prefix(connection_ident_type ident)
1950
{
2,460✔
1951
    std::ostringstream out;
2,460✔
1952
    out.imbue(std::locale::classic());
2,460✔
1953
    out << "Connection[" << ident << "]: "; // Throws
2,460✔
1954
    return out.str();                       // Throws
2,460✔
1955
}
2,460✔
1956

1957

1958
void ClientImpl::Connection::report_connection_state_change(ConnectionState state,
1959
                                                            util::Optional<SessionErrorInfo> error_info)
1960
{
9,700✔
1961
    if (m_force_closed) {
9,700✔
1962
        return;
2,168✔
1963
    }
2,168✔
1964
    auto handler = [=](ClientImpl::Session& sess) {
10,286✔
1965
        SessionImpl& sess_2 = static_cast<SessionImpl&>(sess);
10,286✔
1966
        sess_2.on_connection_state_changed(state, error_info); // Throws
10,286✔
1967
    };
10,286✔
1968
    for_each_active_session(std::move(handler)); // Throws
7,532✔
1969
}
7,532✔
1970

1971

1972
Client::Client(Config config)
1973
    : m_impl{new ClientImpl{std::move(config)}} // Throws
1974
{
8,978✔
1975
}
8,978✔
1976

1977

1978
Client::Client(Client&& client) noexcept
1979
    : m_impl{std::move(client.m_impl)}
1980
{
×
1981
}
×
1982

1983

1984
Client::~Client() noexcept {}
8,978✔
1985

1986

1987
void Client::shutdown() noexcept
1988
{
9,056✔
1989
    m_impl->shutdown();
9,056✔
1990
}
9,056✔
1991

1992
void Client::shutdown_and_wait()
1993
{
760✔
1994
    m_impl->shutdown_and_wait();
760✔
1995
}
760✔
1996

1997
void Client::cancel_reconnect_delay()
1998
{
1,664✔
1999
    m_impl->cancel_reconnect_delay();
1,664✔
2000
}
1,664✔
2001

2002
void Client::voluntary_disconnect_all_connections()
2003
{
12✔
2004
    m_impl->voluntary_disconnect_all_connections();
12✔
2005
}
12✔
2006

2007
bool Client::wait_for_session_terminations_or_client_stopped()
2008
{
370✔
2009
    return m_impl.get()->wait_for_session_terminations_or_client_stopped();
370✔
2010
}
370✔
2011

2012

2013
bool Client::decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, std::string& address,
2014
                                  port_type& port, std::string& path) const
2015
{
3,348✔
2016
    return m_impl->decompose_server_url(url, protocol, address, port, path); // Throws
3,348✔
2017
}
3,348✔
2018

2019

2020
Session::Session(Client& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
2021
                 std::shared_ptr<MigrationStore> migration_store, Config&& config)
2022
{
10,954✔
2023
    util::bind_ptr<SessionWrapper> sess;
10,954✔
2024
    sess.reset(new SessionWrapper{*client.m_impl, std::move(db), std::move(flx_sub_store), std::move(migration_store),
10,954✔
2025
                                  std::move(config)}); // Throws
10,954✔
2026
    // The reference count passed back to the application is implicitly
5,304✔
2027
    // owned by a naked pointer. This is done to avoid exposing
5,304✔
2028
    // implementation details through the header file (that is, through the
5,304✔
2029
    // Session object).
5,304✔
2030
    m_impl = sess.release();
10,954✔
2031
}
10,954✔
2032

2033

2034
void Session::set_progress_handler(util::UniqueFunction<ProgressHandler> handler)
2035
{
3,424✔
2036
    m_impl->set_progress_handler(std::move(handler)); // Throws
3,424✔
2037
}
3,424✔
2038

2039

2040
void Session::set_connection_state_change_listener(util::UniqueFunction<ConnectionStateChangeListener> listener)
2041
{
11,052✔
2042
    m_impl->set_connection_state_change_listener(std::move(listener)); // Throws
11,052✔
2043
}
11,052✔
2044

2045

2046
void Session::bind()
2047
{
9,804✔
2048
    m_impl->initiate(); // Throws
9,804✔
2049
}
9,804✔
2050

2051

2052
void Session::nonsync_transact_notify(version_type new_version)
2053
{
14,846✔
2054
    m_impl->on_commit(new_version); // Throws
14,846✔
2055
}
14,846✔
2056

2057

2058
void Session::cancel_reconnect_delay()
2059
{
12✔
2060
    m_impl->cancel_reconnect_delay(); // Throws
12✔
2061
}
12✔
2062

2063

2064
void Session::async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler handler)
2065
{
4,060✔
2066
    m_impl->async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws
4,060✔
2067
}
4,060✔
2068

2069

2070
bool Session::wait_for_upload_complete_or_client_stopped()
2071
{
12,996✔
2072
    return m_impl->wait_for_upload_complete_or_client_stopped(); // Throws
12,996✔
2073
}
12,996✔
2074

2075

2076
bool Session::wait_for_download_complete_or_client_stopped()
2077
{
10,092✔
2078
    return m_impl->wait_for_download_complete_or_client_stopped(); // Throws
10,092✔
2079
}
10,092✔
2080

2081

2082
void Session::refresh(const std::string& signed_access_token)
2083
{
208✔
2084
    m_impl->refresh(signed_access_token); // Throws
208✔
2085
}
208✔
2086

2087

2088
void Session::abandon() noexcept
2089
{
10,956✔
2090
    REALM_ASSERT(m_impl);
10,956✔
2091
    // Reabsorb the ownership assigned to the applications naked pointer by
5,306✔
2092
    // Session constructor
5,306✔
2093
    util::bind_ptr<SessionWrapper> wrapper{m_impl, util::bind_ptr_base::adopt_tag{}};
10,956✔
2094
    SessionWrapper::abandon(std::move(wrapper));
10,956✔
2095
}
10,956✔
2096

2097
util::Future<std::string> Session::send_test_command(std::string body)
2098
{
52✔
2099
    return m_impl->send_test_command(std::move(body));
52✔
2100
}
52✔
2101

2102
std::string Session::get_appservices_connection_id()
2103
{
72✔
2104
    return m_impl->get_appservices_connection_id();
72✔
2105
}
72✔
2106

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

2118
} // namespace sync
2119
} // namespace realm
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