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

realm / realm-core / 2466

02 Jul 2024 04:06AM UTC coverage: 90.974% (-0.2%) from 91.147%
2466

push

Evergreen

web-flow
Merge pull request #7576 from realm/tg/multi-process-launch-actions

RCORE-1900 Make "next launch" metadata actions multiprocess-safe

102260 of 180446 branches covered (56.67%)

348 of 356 new or added lines in 15 files covered. (97.75%)

334 existing lines in 18 files now uncovered.

215128 of 236473 relevant lines covered (90.97%)

5909897.4 hits per line

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

90.94
/src/realm/sync/client.cpp
1
#include <realm/sync/client.hpp>
2

3
#include <realm/sync/config.hpp>
4
#include <realm/sync/noinst/client_impl_base.hpp>
5
#include <realm/sync/noinst/client_reset.hpp>
6
#include <realm/sync/noinst/pending_bootstrap_store.hpp>
7
#include <realm/sync/noinst/pending_reset_store.hpp>
8
#include <realm/sync/protocol.hpp>
9
#include <realm/sync/subscriptions.hpp>
10
#include <realm/util/bind_ptr.hpp>
11

12
namespace realm::sync {
13
namespace {
14
using namespace realm::util;
15

16

17
// clang-format off
18
using SessionImpl                     = ClientImpl::Session;
19
using SyncTransactCallback            = Session::SyncTransactCallback;
20
using ProgressHandler                 = Session::ProgressHandler;
21
using WaitOperCompletionHandler       = Session::WaitOperCompletionHandler;
22
using ConnectionStateChangeListener   = Session::ConnectionStateChangeListener;
23
using port_type                       = Session::port_type;
24
using connection_ident_type           = std::int_fast64_t;
25
using ProxyConfig                     = SyncConfig::ProxyConfig;
26
// clang-format on
27

28
} // unnamed namespace
29

30

31
// Life cycle states of a session wrapper:
32
//
33
// The session wrapper begins life with an associated Client, but no underlying
34
// SessionImpl. On construction, it begins the actualization process by posting
35
// a job to the client's event loop. That job will set `m_sess` to a session impl
36
// and then set `m_actualized = true`. Once this happens `m_actualized` will
37
// never change again.
38
//
39
// When the external reference to the session (`sync::Session`, which in
40
// non-test code is always owned by a `SyncSession`) is destroyed, the wrapper
41
// begins finalization. If the wrapper has not yet been actualized this takes
42
// place immediately and `m_finalized = true` is set directly on the calling
43
// thread. If it has been actualized, a job is posted to the client's event loop
44
// which will tear down the session and then set `m_finalized = true`. Regardless
45
// of whether or not the session has been actualized, `m_abandoned = true` is
46
// immediately set when the external reference is released.
47
//
48
// When the associated Client is destroyed it calls force_close() on all
49
// actualized wrappers from its event loop. This causes the wrapper to tear down
50
// the session, but not not make it proceed to the finalized state. In normal
51
// usage the client will outlive all sessions, but in tests getting the teardown
52
// correct and race-free can be tricky so we permit either order.
53
//
54
// The wrapper will exist with `m_abandoned = true` and `m_finalized = false`
55
// only while waiting for finalization to happen. It will exist with
56
// `m_finalized = true` only while there are pending post handlers yet to be
57
// executed.
58
class SessionWrapper final : public util::AtomicRefCountBase, DB::CommitListener {
59
public:
60
    SessionWrapper(ClientImpl&, DBRef db, std::shared_ptr<SubscriptionStore>, std::shared_ptr<MigrationStore>,
61
                   Session::Config&&);
62
    ~SessionWrapper() noexcept;
63

64
    ClientReplication& get_replication() noexcept;
65
    ClientImpl& get_client() noexcept;
66

67
    bool has_flx_subscription_store() const;
68
    SubscriptionStore* get_flx_subscription_store();
69
    PendingBootstrapStore* get_flx_pending_bootstrap_store();
70

71
    MigrationStore* get_migration_store();
72

73
    // Immediately initiate deactivation of the wrapped session. Sets m_closed
74
    // but *not* m_finalized.
75
    // Must be called from event loop thread.
76
    void force_close();
77

78
    // Can be called from any thread.
79
    void on_commit(version_type new_version) override;
80
    // Can be called from any thread.
81
    void cancel_reconnect_delay();
82

83
    // Can be called from any thread.
84
    void async_wait_for(bool upload_completion, bool download_completion, WaitOperCompletionHandler);
85
    // Can be called from any thread.
86
    bool wait_for_upload_complete_or_client_stopped();
87
    // Can be called from any thread.
88
    bool wait_for_download_complete_or_client_stopped();
89

90
    // Can be called from any thread.
91
    void refresh(std::string_view signed_access_token);
92

93
    // Can be called from any thread.
94
    static void abandon(util::bind_ptr<SessionWrapper>) noexcept;
95

96
    // These are called from ClientImpl
97
    // Must be called from event loop thread.
98
    void actualize();
99
    void finalize();
100
    void finalize_before_actualization() noexcept;
101

102
    // Can be called from any thread.
103
    util::Future<std::string> send_test_command(std::string body);
104

105
    void handle_pending_client_reset_acknowledgement();
106

107
    void update_subscription_version_info();
108

109
    // Can be called from any thread.
110
    std::string get_appservices_connection_id();
111

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

116
private:
117
    ClientImpl& m_client;
118
    DBRef m_db;
119
    Replication* m_replication;
120

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

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

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

146
    struct ReportedProgress {
147
        uint64_t snapshot;
148
        uint64_t uploaded;
149
        uint64_t uploadable;
150
        uint64_t downloaded;
151
        uint64_t downloadable;
152

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

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

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

170
    const SessionReason m_session_reason;
171

172
    const uint64_t m_schema_version;
173

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

180
    std::shared_ptr<MigrationStore> m_migration_store;
181

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

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

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

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

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

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

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

231
    version_type m_upload_completion_requested_version = -1;
232

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

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

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

250

251
// ################ SessionWrapperStack ################
252

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

258

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

266

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

277

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

286

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

301

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

307

308
// ################ ClientImpl ################
309

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

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

323

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

353

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

384

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

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

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

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

430

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

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

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

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

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

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

469
    m_drained = true;
9,934✔
470
}
9,934✔
471

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

482
    drain_connections_on_loop();
9,934✔
483
}
9,934✔
484

485

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

498
        REALM_ASSERT(m_actualize_and_finalize);
10,130✔
499
        m_unactualized_session_wrappers.push(util::bind_ptr(wrapper));
10,130✔
500
    }
10,130✔
UNCOV
501
    m_actualize_and_finalize->trigger();
×
502
}
10,130✔
503

504

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

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

529

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

568

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

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

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

611

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

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

644

645
// ################ SessionImpl ################
646

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

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

664

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

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

679
DBRef SessionImpl::get_db() const noexcept
680
{
26,090✔
681
    // Can only be called if the session is active or being activated
682
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
26,090!
683
    return m_wrapper.m_db;
26,090✔
684
}
26,090✔
685

686
ClientReplication& SessionImpl::get_repl() const noexcept
687
{
119,642✔
688
    // Can only be called if the session is active or being activated
689
    REALM_ASSERT_EX(m_state == State::Active || m_state == State::Unactivated, m_state);
119,642✔
690
    return m_wrapper.get_replication();
119,642✔
691
}
119,642✔
692

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

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

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

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

719
void SessionImpl::initiate_integrate_changesets(std::uint_fast64_t downloadable_bytes, DownloadBatchState batch_state,
720
                                                const SyncProgress& progress, const ReceivedChangesets& changesets)
721
{
45,286✔
722
    // Ignore the call if the session is not active
723
    if (m_state != State::Active) {
45,286✔
UNCOV
724
        return;
×
UNCOV
725
    }
×
726

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

749

750
void SessionImpl::on_download_completion()
751
{
16,146✔
752
    // Ignore the call if the session is not active
753
    if (m_state == State::Active) {
16,146✔
754
        m_wrapper.on_download_completion(); // Throws
16,146✔
755
    }
16,146✔
756
}
16,146✔
757

758

759
void SessionImpl::on_suspended(const SessionErrorInfo& error_info)
760
{
666✔
761
    // Ignore the call if the session is not active
762
    if (m_state == State::Active) {
666✔
763
        m_wrapper.on_suspended(error_info); // Throws
666✔
764
    }
666✔
765
}
666✔
766

767

768
void SessionImpl::on_resumed()
769
{
54✔
770
    // Ignore the call if the session is not active
771
    if (m_state == State::Active) {
54✔
772
        m_wrapper.on_resumed(); // Throws
54✔
773
    }
54✔
774
}
54✔
775

776
void SessionImpl::handle_pending_client_reset_acknowledgement()
777
{
10,358✔
778
    // Ignore the call if the session is not active
779
    if (m_state == State::Active) {
10,358✔
780
        m_wrapper.handle_pending_client_reset_acknowledgement();
10,358✔
781
    }
10,358✔
782
}
10,358✔
783

784
void SessionImpl::update_subscription_version_info()
785
{
296✔
786
    // Ignore the call if the session is not active
787
    if (m_state == State::Active) {
296✔
788
        m_wrapper.update_subscription_version_info();
296✔
789
    }
296✔
790
}
296✔
791

792
bool SessionImpl::process_flx_bootstrap_message(const SyncProgress& progress, DownloadBatchState batch_state,
793
                                                int64_t query_version, const ReceivedChangesets& received_changesets)
794
{
47,406✔
795
    // Ignore the call if the session is not active
796
    if (m_state != State::Active) {
47,406✔
UNCOV
797
        return false;
×
UNCOV
798
    }
×
799

800
    if (is_steady_state_download_message(batch_state, query_version)) {
47,406✔
801
        return false;
45,288✔
802
    }
45,288✔
803

804
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
2,118✔
805
    std::optional<SyncProgress> maybe_progress;
2,118✔
806
    if (batch_state == DownloadBatchState::LastInBatch) {
2,118✔
807
        maybe_progress = progress;
1,936✔
808
    }
1,936✔
809

810
    bool new_batch = false;
2,118✔
811
    try {
2,118✔
812
        bootstrap_store->add_batch(query_version, std::move(maybe_progress), received_changesets, &new_batch);
2,118✔
813
    }
2,118✔
814
    catch (const LogicError& ex) {
2,118✔
UNCOV
815
        if (ex.code() == ErrorCodes::LimitExceeded) {
×
UNCOV
816
            IntegrationException ex(ErrorCodes::LimitExceeded,
×
UNCOV
817
                                    "bootstrap changeset too large to store in pending bootstrap store",
×
UNCOV
818
                                    ProtocolError::bad_changeset_size);
×
UNCOV
819
            on_integration_failure(ex);
×
UNCOV
820
            return true;
×
UNCOV
821
        }
×
UNCOV
822
        throw;
×
UNCOV
823
    }
×
824

825
    // If we've started a new batch and there is more to come, call on_flx_sync_progress to mark the subscription as
826
    // bootstrapping.
827
    if (new_batch && batch_state == DownloadBatchState::MoreToCome) {
2,120✔
828
        on_flx_sync_progress(query_version, DownloadBatchState::MoreToCome);
48✔
829
    }
48✔
830

831
    auto hook_action = call_debug_hook(SyncClientHookEvent::BootstrapMessageProcessed, progress, query_version,
2,120✔
832
                                       batch_state, received_changesets.size());
2,120✔
833
    if (hook_action == SyncClientHookAction::EarlyReturn) {
2,120✔
834
        return true;
12✔
835
    }
12✔
836
    REALM_ASSERT_EX(hook_action == SyncClientHookAction::NoAction, hook_action);
2,108✔
837

838
    if (batch_state == DownloadBatchState::MoreToCome) {
2,108✔
839
        return true;
180✔
840
    }
180✔
841

842
    try {
1,928✔
843
        process_pending_flx_bootstrap();
1,928✔
844
    }
1,928✔
845
    catch (const IntegrationException& e) {
1,928✔
846
        on_integration_failure(e);
12✔
847
    }
12✔
848
    catch (...) {
1,928✔
UNCOV
849
        on_integration_failure(IntegrationException(exception_to_status()));
×
UNCOV
850
    }
×
851

852
    return true;
1,928✔
853
}
1,928✔
854

855

856
void SessionImpl::process_pending_flx_bootstrap()
857
{
11,990✔
858
    // Ignore the call if not a flx session or session is not active
859
    if (!m_is_flx_sync_session || m_state != State::Active) {
11,990✔
860
        return;
8,556✔
861
    }
8,556✔
862
    // Should never be called if session is not active
863
    REALM_ASSERT_EX(m_state == SessionImpl::Active, m_state);
3,434✔
864
    auto bootstrap_store = m_wrapper.get_flx_pending_bootstrap_store();
3,434✔
865
    if (!bootstrap_store->has_pending()) {
3,434✔
866
        return;
1,486✔
867
    }
1,486✔
868

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

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

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

904
        call_debug_hook(SyncClientHookEvent::BootstrapBatchAboutToProcess, *pending_batch.progress, query_version,
2,088✔
905
                        batch_state, pending_batch.changesets.size());
2,088✔
906

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

917
        auto action = call_debug_hook(SyncClientHookEvent::DownloadMessageIntegrated, progress, query_version,
2,088✔
918
                                      batch_state, pending_batch.changesets.size());
2,088✔
919
        REALM_ASSERT_EX(action == SyncClientHookAction::NoAction, action);
2,088✔
920

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

928
    REALM_ASSERT_3(query_version, !=, -1);
1,936✔
929
    on_flx_sync_progress(query_version, DownloadBatchState::LastInBatch);
1,936✔
930

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

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

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

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

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

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

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

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

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

996
            auto err_processing_err = receive_error_message(err_info);
12✔
997
            REALM_ASSERT_EX(err_processing_err.is_ok(), err_processing_err);
12✔
998
            return SyncClientHookAction::EarlyReturn;
12✔
UNCOV
999
        }
×
1000
        case realm::SyncClientHookAction::TriggerReconnect: {
24✔
1001
            get_connection().voluntary_disconnect();
24✔
1002
            return SyncClientHookAction::EarlyReturn;
24✔
UNCOV
1003
        }
×
1004
        default:
2,438✔
1005
            return action;
2,438✔
1006
    }
2,482✔
1007
}
2,482✔
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
{
120,032✔
1013
    if (REALM_LIKELY(!m_wrapper.m_debug_hook)) {
120,032✔
1014
        return SyncClientHookAction::NoAction;
117,720✔
1015
    }
117,720✔
1016
    if (REALM_UNLIKELY(m_state != State::Active)) {
2,312✔
1017
        return SyncClientHookAction::NoAction;
×
UNCOV
1018
    }
×
1019

1020
    SyncClientHookData data;
2,312✔
1021
    data.event = event;
2,312✔
1022
    data.batch_state = batch_state;
2,312✔
1023
    data.progress = progress;
2,312✔
1024
    data.num_changesets = num_changesets;
2,312✔
1025
    data.query_version = query_version;
2,312✔
1026

1027
    return call_debug_hook(data);
2,312✔
1028
}
2,312✔
1029

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

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

1047
    return call_debug_hook(data);
200✔
1048
}
200✔
1049

1050
SyncClientHookAction SessionImpl::call_debug_hook(SyncClientHookEvent event)
1051
{
19,108✔
1052
    return call_debug_hook(event, m_progress, m_last_sent_flx_query_version, DownloadBatchState::SteadyState, 0);
19,108✔
1053
}
19,108✔
1054

1055
bool SessionImpl::is_steady_state_download_message(DownloadBatchState batch_state, int64_t query_version)
1056
{
94,830✔
1057
    // Should never be called if session is not active
1058
    REALM_ASSERT_EX(m_state == State::Active, m_state);
94,830✔
1059
    if (batch_state == DownloadBatchState::SteadyState) {
94,830✔
1060
        return true;
45,288✔
1061
    }
45,288✔
1062

1063
    if (!m_is_flx_sync_session) {
49,542✔
1064
        return true;
43,976✔
1065
    }
43,976✔
1066

1067
    // If this is a steady state DOWNLOAD, no need for special handling.
1068
    if (batch_state == DownloadBatchState::LastInBatch && query_version == m_wrapper.m_flx_active_version) {
5,566✔
1069
        return true;
1,316✔
1070
    }
1,316✔
1071

1072
    return false;
4,250✔
1073
}
5,566✔
1074

1075
void SessionImpl::init_progress_handler()
1076
{
10,358✔
1077
    REALM_ASSERT_EX(m_state == State::Unactivated || m_state == State::Active, m_state);
10,358✔
1078
    m_wrapper.init_progress_handler();
10,358✔
1079
}
10,358✔
1080

1081
void SessionImpl::enable_progress_notifications()
1082
{
45,790✔
1083
    m_wrapper.m_reliable_download_progress = true;
45,790✔
1084
}
45,790✔
1085

1086
util::Future<std::string> SessionImpl::send_test_command(std::string body)
1087
{
60✔
1088
    if (m_state != State::Active) {
60✔
UNCOV
1089
        return Status{ErrorCodes::RuntimeError, "Cannot send a test command for a session that is not active"};
×
UNCOV
1090
    }
×
1091

1092
    try {
60✔
1093
        auto json_body = nlohmann::json::parse(body.begin(), body.end());
60✔
1094
        if (auto it = json_body.find("command"); it == json_body.end() || !it->is_string()) {
60✔
1095
            return Status{ErrorCodes::LogicError,
4✔
1096
                          "Must supply command name in \"command\" field of test command json object"};
4✔
1097
        }
4✔
1098
        if (json_body.size() > 1 && json_body.find("args") == json_body.end()) {
56✔
UNCOV
1099
            return Status{ErrorCodes::LogicError, "Only valid fields in a test command are \"command\" and \"args\""};
×
UNCOV
1100
        }
×
1101
    }
56✔
1102
    catch (const nlohmann::json::parse_error& e) {
60✔
1103
        return Status{ErrorCodes::LogicError, util::format("Invalid json input to send_test_command: %1", e.what())};
4✔
1104
    }
4✔
1105

1106
    auto pf = util::make_promise_future<std::string>();
52✔
1107
    get_client().post([this, promise = std::move(pf.promise), body = std::move(body)](Status status) mutable {
52✔
1108
        // Includes operation_aborted
1109
        if (!status.is_ok()) {
52✔
UNCOV
1110
            promise.set_error(status);
×
1111
            return;
×
1112
        }
×
1113

1114
        auto id = ++m_last_pending_test_command_ident;
52✔
1115
        m_pending_test_commands.push_back(PendingTestCommand{id, std::move(body), std::move(promise)});
52✔
1116
        ensure_enlisted_to_send();
52✔
1117
    });
52✔
1118

1119
    return std::move(pf.future);
52✔
1120
}
60✔
1121

1122
// ################ SessionWrapper ################
1123

1124
// The SessionWrapper class is held by a sync::Session (which is owned by the SyncSession instance) and
1125
// provides a link to the ClientImpl::Session that creates and receives messages with the server with
1126
// the ClientImpl::Connection that owns the ClientImpl::Session.
1127
SessionWrapper::SessionWrapper(ClientImpl& client, DBRef db, std::shared_ptr<SubscriptionStore> flx_sub_store,
1128
                               std::shared_ptr<MigrationStore> migration_store, Session::Config&& config)
1129
    : m_client{client}
4,894✔
1130
    , m_db(std::move(db))
4,894✔
1131
    , m_replication(m_db->get_replication())
4,894✔
1132
    , m_protocol_envelope{config.protocol_envelope}
4,894✔
1133
    , m_server_address{std::move(config.server_address)}
4,894✔
1134
    , m_server_port{config.server_port}
4,894✔
1135
    , m_server_verified{config.server_verified}
4,894✔
1136
    , m_user_id(std::move(config.user_id))
4,894✔
1137
    , m_sync_mode(flx_sub_store ? SyncServerMode::FLX : SyncServerMode::PBS)
4,894✔
1138
    , m_authorization_header_name{config.authorization_header_name}
4,894✔
1139
    , m_custom_http_headers{std::move(config.custom_http_headers)}
4,894✔
1140
    , m_verify_servers_ssl_certificate{config.verify_servers_ssl_certificate}
4,894✔
1141
    , m_simulate_integration_error{config.simulate_integration_error}
4,894✔
1142
    , m_ssl_trust_certificate_path{std::move(config.ssl_trust_certificate_path)}
4,894✔
1143
    , m_ssl_verify_callback{std::move(config.ssl_verify_callback)}
4,894✔
1144
    , m_flx_bootstrap_batch_size_bytes(config.flx_bootstrap_batch_size_bytes)
4,894✔
1145
    , m_http_request_path_prefix{std::move(config.service_identifier)}
4,894✔
1146
    , m_virt_path{std::move(config.realm_identifier)}
4,894✔
1147
    , m_proxy_config{std::move(config.proxy_config)}
4,894✔
1148
    , m_signed_access_token{std::move(config.signed_user_token)}
4,894✔
1149
    , m_client_reset_config{std::move(config.client_reset_config)}
4,894✔
1150
    , m_progress_handler(std::move(config.progress_handler))
4,894✔
1151
    , m_connection_state_change_listener(std::move(config.connection_state_change_listener))
4,894✔
1152
    , m_debug_hook(std::move(config.on_sync_client_event_hook))
4,894✔
1153
    , m_session_reason(m_client_reset_config ? SessionReason::ClientReset : config.session_reason)
4,894✔
1154
    , m_schema_version(config.schema_version)
4,894✔
1155
    , m_flx_subscription_store(std::move(flx_sub_store))
4,894✔
1156
    , m_migration_store(std::move(migration_store))
4,894✔
1157
{
10,132✔
1158
    REALM_ASSERT(m_db);
10,132✔
1159
    REALM_ASSERT(m_db->get_replication());
10,132✔
1160
    REALM_ASSERT(dynamic_cast<ClientReplication*>(m_db->get_replication()));
10,132✔
1161

1162
    // SessionWrapper begins at +1 retain count because Client retains and
1163
    // releases it while performing async operations, and these need to not
1164
    // take it to 0 or it could be deleted before the caller can retain it.
1165
    bind_ptr();
10,132✔
1166
    m_client.register_unactualized_session_wrapper(this);
10,132✔
1167
}
10,132✔
1168

1169
SessionWrapper::~SessionWrapper() noexcept
1170
{
10,130✔
1171
    // We begin actualization in the constructor and do not delete the wrapper
1172
    // until both the Client is done with it and the Session has abandoned it,
1173
    // so at this point we must have actualized, finalized, and been abandoned.
1174
    REALM_ASSERT(m_actualized);
10,130✔
1175
    REALM_ASSERT(m_abandoned);
10,130✔
1176
    REALM_ASSERT(m_finalized);
10,130✔
1177
    REALM_ASSERT(m_closed);
10,130✔
1178
    REALM_ASSERT(!m_db);
10,130✔
1179
}
10,130✔
1180

1181

1182
inline ClientReplication& SessionWrapper::get_replication() noexcept
1183
{
119,640✔
1184
    REALM_ASSERT(m_db);
119,640✔
1185
    return static_cast<ClientReplication&>(*m_replication);
119,640✔
1186
}
119,640✔
1187

1188

1189
inline ClientImpl& SessionWrapper::get_client() noexcept
UNCOV
1190
{
×
UNCOV
1191
    return m_client;
×
UNCOV
1192
}
×
1193

1194
bool SessionWrapper::has_flx_subscription_store() const
1195
{
1,972✔
1196
    return static_cast<bool>(m_flx_subscription_store);
1,972✔
1197
}
1,972✔
1198

1199
void SessionWrapper::on_flx_sync_error(int64_t version, std::string_view err_msg)
1200
{
20✔
1201
    REALM_ASSERT(!m_finalized);
20✔
1202
    get_flx_subscription_store()->update_state(version, SubscriptionSet::State::Error, err_msg);
20✔
1203
}
20✔
1204

1205
void SessionWrapper::on_flx_sync_version_complete(int64_t version)
1206
{
2,224✔
1207
    REALM_ASSERT(!m_finalized);
2,224✔
1208
    m_flx_last_seen_version = version;
2,224✔
1209
    m_flx_active_version = version;
2,224✔
1210
}
2,224✔
1211

1212
void SessionWrapper::on_flx_sync_progress(int64_t new_version, DownloadBatchState batch_state)
1213
{
1,972✔
1214
    if (!has_flx_subscription_store()) {
1,972✔
UNCOV
1215
        return;
×
UNCOV
1216
    }
×
1217
    REALM_ASSERT(!m_finalized);
1,972✔
1218
    REALM_ASSERT(new_version >= m_flx_last_seen_version);
1,972✔
1219
    REALM_ASSERT(new_version >= m_flx_active_version);
1,972✔
1220
    REALM_ASSERT(batch_state != DownloadBatchState::SteadyState);
1,972✔
1221

1222
    SubscriptionSet::State new_state = SubscriptionSet::State::Uncommitted; // Initialize to make compiler happy
1,972✔
1223

1224
    switch (batch_state) {
1,972✔
UNCOV
1225
        case DownloadBatchState::SteadyState:
✔
1226
            // Cannot be called with this value.
1227
            REALM_UNREACHABLE();
1228
        case DownloadBatchState::LastInBatch:
1,924✔
1229
            if (m_flx_active_version == new_version) {
1,924✔
UNCOV
1230
                return;
×
UNCOV
1231
            }
×
1232
            on_flx_sync_version_complete(new_version);
1,924✔
1233
            if (new_version == 0) {
1,924✔
1234
                new_state = SubscriptionSet::State::Complete;
924✔
1235
            }
924✔
1236
            else {
1,000✔
1237
                new_state = SubscriptionSet::State::AwaitingMark;
1,000✔
1238
                m_flx_pending_mark_version = new_version;
1,000✔
1239
            }
1,000✔
1240
            break;
1,924✔
1241
        case DownloadBatchState::MoreToCome:
48✔
1242
            if (m_flx_last_seen_version == new_version) {
48✔
UNCOV
1243
                return;
×
UNCOV
1244
            }
×
1245

1246
            m_flx_last_seen_version = new_version;
48✔
1247
            new_state = SubscriptionSet::State::Bootstrapping;
48✔
1248
            break;
48✔
1249
    }
1,972✔
1250

1251
    get_flx_subscription_store()->update_state(new_version, new_state);
1,972✔
1252
}
1,972✔
1253

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

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

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

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

1279

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

1293

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

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

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

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

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

1353

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

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

1366

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

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

1379

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

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

1399

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

1406

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

1418
    m_actualized = true;
10,064✔
1419

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

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

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

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

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

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

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

1463
    if (m_connection_state_change_listener) {
10,064✔
1464
        ConnectionState state = conn.get_state();
10,052✔
1465
        if (state != ConnectionState::disconnected) {
10,052✔
1466
            m_connection_state_change_listener(ConnectionState::connecting, util::none); // Throws
7,112✔
1467
            if (state == ConnectionState::connected)
7,112✔
1468
                m_connection_state_change_listener(ConnectionState::connected, util::none); // Throws
6,994✔
1469
        }
7,112✔
1470
    }
10,052✔
1471

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

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

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

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

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

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

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

1531
    force_close();
10,064✔
1532

1533
    m_finalized = true;
10,064✔
1534

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

1542

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

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

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

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

1585

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

1595

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

1610

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

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

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

1629
    if (!m_progress_handler && m_upload_completion_handlers.empty() && m_sync_completion_handlers.empty())
154,596✔
1630
        return;
74,086✔
1631

1632
    version_type uploaded_version;
80,510✔
1633
    ReportedProgress p;
80,510✔
1634
    DownloadableProgress downloadable;
80,510✔
1635
    ClientHistory::get_upload_download_state(*m_db, p.downloaded, downloadable, p.uploaded, p.uploadable, p.snapshot,
80,510✔
1636
                                             uploaded_version);
80,510✔
1637

1638
    report_progress(p, downloadable);
80,510✔
1639
    report_upload_completion(uploaded_version);
80,510✔
1640
}
80,510✔
1641

1642
void SessionWrapper::report_upload_completion(version_type uploaded_version)
1643
{
80,504✔
1644
    if (uploaded_version < m_upload_completion_requested_version)
80,504✔
1645
        return;
61,008✔
1646

1647
    std::move(m_sync_completion_handlers.begin(), m_sync_completion_handlers.end(),
19,496✔
1648
              std::back_inserter(m_download_completion_handlers));
19,496✔
1649
    m_sync_completion_handlers.clear();
19,496✔
1650

1651
    while (!m_upload_completion_handlers.empty()) {
34,284✔
1652
        auto handler = std::move(m_upload_completion_handlers.back());
14,788✔
1653
        m_upload_completion_handlers.pop_back();
14,788✔
1654
        handler(Status::OK()); // Throws
14,788✔
1655
    }
14,788✔
1656
}
19,496✔
1657

1658
void SessionWrapper::report_progress(ReportedProgress& p, DownloadableProgress downloadable)
1659
{
80,502✔
1660
    if (!m_progress_handler)
80,502✔
1661
        return;
27,716✔
1662

1663
    // Ignore progress messages from before we first receive a DOWNLOAD message
1664
    if (!m_reliable_download_progress)
52,786✔
1665
        return;
28,578✔
1666

1667
    auto calculate_progress = [](uint64_t transferred, uint64_t transferable, uint64_t final_transferred) {
24,208✔
1668
        REALM_ASSERT_DEBUG_EX(final_transferred <= transferred, final_transferred, transferred, transferable);
18,890✔
1669
        REALM_ASSERT_DEBUG_EX(transferred <= transferable, final_transferred, transferred, transferable);
18,890✔
1670

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

1679
        double progress_estimate = 1.0;
18,890✔
1680
        if (final_transferred < transferable && transferred < transferable)
18,890✔
1681
            progress_estimate = (transferred - final_transferred) / double(transferable - final_transferred);
9,744✔
1682
        return progress_estimate;
18,890✔
1683
    };
18,890✔
1684

1685
    bool upload_completed = p.uploaded == p.uploadable;
24,208✔
1686
    double upload_estimate = 1.0;
24,208✔
1687
    if (!upload_completed)
24,208✔
1688
        upload_estimate = calculate_progress(p.uploaded, p.uploadable, m_final_uploaded);
9,696✔
1689

1690
    bool download_completed = p.downloaded == 0;
24,208✔
1691
    double download_estimate = 1.00;
24,208✔
1692
    if (m_flx_pending_bootstrap_store) {
24,208✔
1693
        if (m_flx_pending_bootstrap_store->has_pending()) {
11,756✔
1694
            download_estimate = downloadable.as_estimate();
524✔
1695
            p.downloaded += m_flx_pending_bootstrap_store->pending_stats().pending_changeset_bytes;
524✔
1696
        }
524✔
1697
        download_completed = download_estimate >= 1.0;
11,756✔
1698

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

1715
    if (download_completed)
24,208✔
1716
        m_final_downloaded = p.downloaded;
15,014✔
1717
    if (upload_completed)
24,208✔
1718
        m_final_uploaded = p.uploaded;
14,512✔
1719

1720
    if (p == m_reported_progress)
24,208✔
1721
        return;
17,010✔
1722

1723
    m_reported_progress = p;
7,198✔
1724

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

1739
    m_progress_handler(p.downloaded, p.downloadable, p.uploaded, p.uploadable, p.snapshot, download_estimate,
7,198✔
1740
                       upload_estimate, m_flx_last_seen_version);
7,198✔
1741
}
7,198✔
1742

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1825
// ################ ClientImpl::Connection ################
1826

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

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

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

1867

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

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

1880

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

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

1897

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

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

1909
    return path;
3,798✔
1910
}
3,798✔
1911

1912

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

1918

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

1932

1933
Client::Client(Config config)
1934
    : m_impl{new ClientImpl{std::move(config)}} // Throws
4,898✔
1935
{
9,934✔
1936
}
9,934✔
1937

1938

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

1944

1945
Client::~Client() noexcept {}
9,934✔
1946

1947

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

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

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

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

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

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

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

1984

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

1992

1993
void Session::nonsync_transact_notify(version_type new_version)
1994
{
17,780✔
1995
    m_impl->on_commit(new_version); // Throws
17,780✔
1996
}
17,780✔
1997

1998

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

2004

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

2010

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

2016

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

2022

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

2028

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

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

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

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

2059
} // namespace realm::sync
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc