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

realm / realm-core / 2322

20 May 2024 08:01PM UTC coverage: 90.811% (-0.02%) from 90.833%
2322

push

Evergreen

web-flow
RCORE-2099 Restore progress notifier behavior when sync session is already caught up (#7681)

101718 of 180092 branches covered (56.48%)

742 of 768 new or added lines in 4 files covered. (96.61%)

106 existing lines in 16 files now uncovered.

214769 of 236502 relevant lines covered (90.81%)

5853734.67 hits per line

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

91.67
/src/realm/object-store/sync/sync_session.cpp
1
////////////////////////////////////////////////////////////////////////////
2
//
3
// Copyright 2016 Realm Inc.
4
//
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing, software
12
// distributed under the License is distributed on an "AS IS" BASIS,
13
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
// See the License for the specific language governing permissions and
15
// limitations under the License.
16
//
17
////////////////////////////////////////////////////////////////////////////
18

19
#include <realm/object-store/sync/sync_session.hpp>
20

21
#include <realm/object-store/thread_safe_reference.hpp>
22
#include <realm/object-store/impl/realm_coordinator.hpp>
23
#include <realm/object-store/sync/app.hpp>
24
#include <realm/object-store/sync/impl/sync_client.hpp>
25
#include <realm/object-store/sync/impl/sync_file.hpp>
26
#include <realm/object-store/sync/impl/app_metadata.hpp>
27
#include <realm/object-store/sync/sync_manager.hpp>
28
#include <realm/object-store/sync/sync_user.hpp>
29
#include <realm/object-store/util/scheduler.hpp>
30

31
#include <realm/db_options.hpp>
32
#include <realm/sync/client.hpp>
33
#include <realm/sync/config.hpp>
34
#include <realm/sync/network/http.hpp>
35
#include <realm/sync/network/websocket_error.hpp>
36
#include <realm/sync/noinst/client_history_impl.hpp>
37
#include <realm/sync/noinst/client_reset_operation.hpp>
38
#include <realm/sync/noinst/migration_store.hpp>
39
#include <realm/sync/noinst/sync_schema_migration.hpp>
40
#include <realm/sync/protocol.hpp>
41

42
using namespace realm;
43
using namespace realm::_impl;
44

45
using SessionWaiterPointer = void (sync::Session::*)(util::UniqueFunction<void(std::error_code)>);
46

47
constexpr const char SyncError::c_original_file_path_key[];
48
constexpr const char SyncError::c_recovery_file_path_key[];
49

50
/// STATES:
51
///
52
/// WAITING_FOR_ACCESS_TOKEN: a request has been initiated to ask
53
/// for an updated access token and the session is waiting for a response.
54
/// From: INACTIVE, DYING
55
/// To:
56
///    * ACTIVE: when the SDK successfully refreshes the token
57
///    * INACTIVE: if asked to log out, or if asked to close
58
///
59
/// ACTIVE: the session is connected to the Sync Server and is actively
60
/// transferring data.
61
/// From: INACTIVE, DYING, WAITING_FOR_ACCESS_TOKEN
62
/// To:
63
///    * INACTIVE: if asked to log out, or if asked to close and the stop policy
64
///                is Immediate.
65
///    * DYING: if asked to close and the stop policy is AfterChangesUploaded
66
///
67
/// DYING: the session is performing clean-up work in preparation to be destroyed.
68
/// From: ACTIVE
69
/// To:
70
///    * INACTIVE: when the clean-up work completes, if the session wasn't
71
///                revived, or if explicitly asked to log out before the
72
///                clean-up work begins
73
///    * ACTIVE: if the session is revived
74
///    * WAITING_FOR_ACCESS_TOKEN: if the session tried to enter ACTIVE,
75
///                                but the token is invalid or expired.
76
///
77
/// INACTIVE: the user owning this session has logged out, the `sync::Session`
78
/// owned by this session is destroyed, and the session is quiescent.
79
/// Note that a session briefly enters this state before being destroyed, but
80
/// it can also enter this state and stay there if the user has been logged out.
81
/// From: initial, ACTIVE, DYING, WAITING_FOR_ACCESS_TOKEN
82
/// To:
83
///    * ACTIVE: if the session is revived
84
///    * WAITING_FOR_ACCESS_TOKEN: if the session tried to enter ACTIVE,
85
///                                but the token is invalid or expired.
86

87
void SyncSession::become_active()
88
{
2,010✔
89
    REALM_ASSERT(m_state != State::Active);
2,010✔
90
    m_state = State::Active;
2,010✔
91

92
    // First time the session becomes active, register a notification on the sentinel subscription set to restart the
93
    // session and update to native FLX.
94
    if (m_migration_sentinel_query_version) {
2,010✔
95
        m_flx_subscription_store->get_by_version(*m_migration_sentinel_query_version)
2✔
96
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
97
            .get_async([=, weak_self = weak_from_this()](StatusWith<sync::SubscriptionSet::State> s) {
2✔
98
                if (!s.is_ok()) {
2✔
99
                    return;
×
100
                }
×
101
                REALM_ASSERT(s.get_value() == sync::SubscriptionSet::State::Complete);
2✔
102
                if (auto strong_self = weak_self.lock()) {
2✔
103
                    strong_self->m_migration_store->cancel_migration();
2✔
104
                    strong_self->restart_session();
2✔
105
                }
2✔
106
            });
2✔
107
        m_migration_sentinel_query_version.reset();
2✔
108
    }
2✔
109

110
    // when entering from the Dying state the session will still be bound
111
    if (!m_session) {
2,010✔
112
        create_sync_session();
2,008✔
113
        m_session->bind();
2,008✔
114
    }
2,008✔
115

116
    // Register all the pending wait-for-completion blocks. This can
117
    // potentially add a redundant callback if we're coming from the Dying
118
    // state, but that's okay (we won't call the user callbacks twice).
119
    SyncSession::CompletionCallbacks callbacks_to_register;
2,010✔
120
    std::swap(m_completion_callbacks, callbacks_to_register);
2,010✔
121

122
    for (auto& [id, callback_tuple] : callbacks_to_register) {
2,010✔
123
        add_completion_callback(std::move(callback_tuple.second), callback_tuple.first);
475✔
124
    }
475✔
125
}
2,010✔
126

127
void SyncSession::become_dying(util::CheckedUniqueLock lock)
128
{
84✔
129
    REALM_ASSERT(m_state != State::Dying);
84✔
130
    m_state = State::Dying;
84✔
131

132
    // If we have no session, we cannot possibly upload anything.
133
    if (!m_session) {
84✔
134
        become_inactive(std::move(lock));
×
135
        return;
×
136
    }
×
137

138
    size_t current_death_count = ++m_death_count;
84✔
139
    m_session->async_wait_for_upload_completion([weak_session = weak_from_this(), current_death_count](Status) {
84✔
140
        if (auto session = weak_session.lock()) {
84✔
141
            util::CheckedUniqueLock lock(session->m_state_mutex);
82✔
142
            if (session->m_state == State::Dying && session->m_death_count == current_death_count) {
82✔
143
                session->become_inactive(std::move(lock));
27✔
144
            }
27✔
145
        }
82✔
146
    });
84✔
147
    m_state_mutex.unlock(lock);
84✔
148
}
84✔
149

150
void SyncSession::become_inactive(util::CheckedUniqueLock lock, Status status, bool cancel_subscription_notifications)
151
{
1,782✔
152
    REALM_ASSERT(m_state != State::Inactive);
1,782✔
153
    m_state = State::Inactive;
1,782✔
154

155
    do_become_inactive(std::move(lock), status, cancel_subscription_notifications);
1,782✔
156
}
1,782✔
157

158
void SyncSession::become_paused(util::CheckedUniqueLock lock)
159
{
212✔
160
    REALM_ASSERT(m_state != State::Paused);
212✔
161
    auto old_state = m_state;
212✔
162
    m_state = State::Paused;
212✔
163

164
    // Nothing to do if we're already inactive besides update the state.
165
    if (old_state == State::Inactive) {
212✔
166
        m_state_mutex.unlock(lock);
2✔
167
        return;
2✔
168
    }
2✔
169

170
    do_become_inactive(std::move(lock), Status::OK(), true);
210✔
171
}
210✔
172

173
void SyncSession::restart_session()
174
{
22✔
175
    util::CheckedUniqueLock lock(m_state_mutex);
22✔
176
    switch (m_state) {
22✔
177
        case State::Active:
22✔
178
            do_restart_session(std::move(lock));
22✔
179
            break;
22✔
180
        case State::WaitingForAccessToken:
✔
181
        case State::Paused:
✔
182
        case State::Dying:
✔
183
        case State::Inactive:
✔
184
            return;
×
185
    }
22✔
186
}
22✔
187

188
void SyncSession::do_restart_session(util::CheckedUniqueLock)
189
{
22✔
190
    // Go straight to inactive so the progress completion waiters will
191
    // continue to wait until the session restarts and completes the
192
    // upload/download sync
193
    m_state = State::Inactive;
22✔
194

195
    if (m_session) {
22✔
196
        m_session.reset();
22✔
197
    }
22✔
198

199
    // Create a new session and re-register the completion callbacks
200
    // The latest server path will be retrieved from sync_manager when
201
    // the new session is created by create_sync_session() in become
202
    // active.
203
    become_active();
22✔
204
}
22✔
205

206
void SyncSession::do_become_inactive(util::CheckedUniqueLock lock, Status status,
207
                                     bool cancel_subscription_notifications)
208
{
1,992✔
209
    // Manually set the disconnected state. Sync would also do this, but
210
    // since the underlying SyncSession object already have been destroyed,
211
    // we are not able to get the callback.
212
    util::CheckedUniqueLock connection_state_lock(m_connection_state_mutex);
1,992✔
213
    auto old_state = m_connection_state;
1,992✔
214
    auto new_state = m_connection_state = SyncSession::ConnectionState::Disconnected;
1,992✔
215
    connection_state_lock.unlock();
1,992✔
216

217
    SyncSession::CompletionCallbacks waits;
1,992✔
218
    std::swap(waits, m_completion_callbacks);
1,992✔
219

220
    m_session = nullptr;
1,992✔
221
    if (m_sync_manager) {
1,992✔
222
        m_sync_manager->unregister_session(m_db->get_path());
1,992✔
223
    }
1,992✔
224

225
    auto subscription_store = m_flx_subscription_store;
1,992✔
226
    m_state_mutex.unlock(lock);
1,992✔
227

228
    // Send notifications after releasing the lock to prevent deadlocks in the callback.
229
    if (old_state != new_state) {
1,992✔
230
        m_connection_change_notifier.invoke_callbacks(old_state, connection_state());
1,556✔
231
    }
1,556✔
232

233
    if (status.is_ok())
1,992✔
234
        status = Status(ErrorCodes::OperationAborted, "Sync session became inactive");
1,875✔
235

236
    if (subscription_store && cancel_subscription_notifications) {
1,992✔
237
        subscription_store->notify_all_state_change_notifications(status);
673✔
238
    }
673✔
239

240
    // Inform any queued-up completion handlers that they were cancelled.
241
    for (auto& [id, callback] : waits)
1,992✔
242
        callback.second(status);
82✔
243
}
1,992✔
244

245
void SyncSession::become_waiting_for_access_token()
246
{
20✔
247
    REALM_ASSERT(m_state != State::WaitingForAccessToken);
20✔
248
    m_state = State::WaitingForAccessToken;
20✔
249
}
20✔
250

251
void SyncSession::handle_bad_auth(const std::shared_ptr<SyncUser>& user, Status status)
252
{
24✔
253
    // TODO: ideally this would write to the logs as well in case users didn't set up their error handler.
254
    {
24✔
255
        util::CheckedUniqueLock lock(m_state_mutex);
24✔
256
        cancel_pending_waits(std::move(lock), status);
24✔
257
    }
24✔
258
    if (user) {
24✔
259
        user->request_log_out();
24✔
260
    }
24✔
261

262
    if (auto error_handler = config(&SyncConfig::error_handler)) {
24✔
263
        auto user_facing_error = SyncError({ErrorCodes::AuthError, status.reason()}, true);
24✔
264
        error_handler(shared_from_this(), std::move(user_facing_error));
24✔
265
    }
24✔
266
}
24✔
267

268
static bool check_for_auth_failure(const app::AppError& error)
269
{
62✔
270
    using namespace realm::sync;
62✔
271
    // Auth failure is returned as a 401 (unauthorized) or 403 (forbidden) response
272
    if (error.additional_status_code) {
62✔
273
        auto status_code = HTTPStatus(*error.additional_status_code);
62✔
274
        if (status_code == HTTPStatus::Unauthorized || status_code == HTTPStatus::Forbidden)
62✔
275
            return true;
22✔
276
    }
62✔
277

278
    return false;
40✔
279
}
62✔
280

281
static bool check_for_redirect_response(const app::AppError& error)
282
{
40✔
283
    using namespace realm::sync;
40✔
284
    // Check for unhandled 301/308 permanent redirect response
285
    if (error.additional_status_code) {
40✔
286
        auto status_code = HTTPStatus(*error.additional_status_code);
40✔
287
        if (status_code == HTTPStatus::MovedPermanently || status_code == HTTPStatus::PermanentRedirect)
40✔
288
            return true;
×
289
    }
40✔
290

291
    return false;
40✔
292
}
40✔
293

294
util::UniqueFunction<void(std::optional<app::AppError>)>
295
SyncSession::handle_refresh(const std::shared_ptr<SyncSession>& session, bool restart_session)
296
{
90✔
297
    return [session, restart_session](std::optional<app::AppError> error) {
90✔
298
        auto session_user = session->user();
90✔
299
        if (!session_user) {
90✔
300
            util::CheckedUniqueLock lock(session->m_state_mutex);
×
301
            auto refresh_error = error ? error->to_status() : Status::OK();
×
302
            session->cancel_pending_waits(std::move(lock), refresh_error);
×
303
        }
×
304
        else if (error) {
90✔
305
            if (ErrorCodes::error_categories(error->code()).test(ErrorCategory::client_error)) {
64✔
306
                // any other client errors other than app_deallocated are considered fatal because
307
                // there was a problem locally before even sending the request to the server
308
                // eg. ClientErrorCode::user_not_found, ClientErrorCode::user_not_logged_in,
309
                // ClientErrorCode::too_many_redirects
310
                session->handle_bad_auth(session_user, error->to_status());
2✔
311
            }
2✔
312
            else if (check_for_auth_failure(*error)) {
62✔
313
                // A 401 response on a refresh request means that the token cannot be refreshed and we should not
314
                // retry. This can be because an admin has revoked this user's sessions, the user has been disabled,
315
                // or the refresh token has expired according to the server's clock.
316
                session->handle_bad_auth(
22✔
317
                    session_user,
22✔
318
                    {error->code(), util::format("Unable to refresh the user access token: %1", error->reason())});
22✔
319
            }
22✔
320
            else if (check_for_redirect_response(*error)) {
40✔
321
                // A 301 or 308 response is an unhandled permanent redirect response (which should not happen) - if
322
                // this is received, fail the request with an appropriate error message.
323
                // Temporary redirect responses (302, 307) are not supported
324
                session->handle_bad_auth(
×
325
                    session_user,
×
326
                    {error->code(), util::format("Unhandled redirect response when trying to reach the server: %1",
×
327
                                                 error->reason())});
×
328
            }
×
329
            else {
40✔
330
                // A refresh request has failed. This is an unexpected non-fatal error and we would
331
                // like to retry but we shouldn't do this immediately in order to not swamp the
332
                // server with requests. Consider two scenarios:
333
                // 1) If this request was spawned from the proactive token check, or a user
334
                // initiated request, the token may actually be valid. Just advance to Active
335
                // from WaitingForAccessToken if needed and let the sync server tell us if the
336
                // token is valid or not. If this also fails we will end up in case 2 below.
337
                // 2) If the sync connection initiated the request because the server is
338
                // unavailable or the connection otherwise encounters an unexpected error, we want
339
                // to let the sync client attempt to reinitialize the connection using its own
340
                // internal backoff timer which will happen automatically so nothing needs to
341
                // happen here.
342
                util::CheckedUniqueLock lock(session->m_state_mutex);
40✔
343
                // If updating access token while opening realm, just become active at this point
344
                // and try to use the current access token.
345
                if (session->m_state == State::WaitingForAccessToken) {
40✔
346
                    session->become_active();
2✔
347
                }
2✔
348
                // If `cancel_waits_on_nonfatal_error` is true, then cancel the waiters and pass along the error
349
                else if (session->config(&SyncConfig::cancel_waits_on_nonfatal_error)) {
38✔
350
                    session->cancel_pending_waits(std::move(lock), error->to_status()); // unlocks the mutex
14✔
351
                }
14✔
352
            }
40✔
353
        }
64✔
354
        else {
26✔
355
            // If the session needs to be restarted, then restart the session now
356
            // The latest access token and server url will be pulled from the sync
357
            // manager when the new session is started.
358
            if (restart_session) {
26✔
359
                session->restart_session();
14✔
360
            }
14✔
361
            // Otherwise, update the access token and reconnect
362
            else {
12✔
363
                session->update_access_token(session_user->access_token());
12✔
364
            }
12✔
365
        }
26✔
366
    };
90✔
367
}
90✔
368

369
SyncSession::SyncSession(Private, SyncClient& client, std::shared_ptr<DB> db, const RealmConfig& config,
370
                         SyncManager* sync_manager)
371
    : m_config{config}
715✔
372
    , m_db{std::move(db)}
715✔
373
    , m_original_sync_config{m_config.sync_config}
715✔
374
    , m_migration_store{sync::MigrationStore::create(m_db)}
715✔
375
    , m_client(client)
715✔
376
    , m_sync_manager(sync_manager)
715✔
377
{
1,600✔
378
    REALM_ASSERT(m_config.sync_config);
1,600✔
379
    // we don't want the following configs enabled during a client reset
380
    m_config.scheduler = nullptr;
1,600✔
381
    m_config.audit_config = nullptr;
1,600✔
382

383
    // Adjust the sync_config if using PBS sync and already in the migrated or rollback state
384
    if (m_migration_store->is_migrated() || m_migration_store->is_rollback_in_progress()) {
1,600✔
385
        m_config.sync_config = sync::MigrationStore::convert_sync_config_to_flx(m_original_sync_config);
8✔
386
    }
8✔
387

388
    // If using FLX, set up m_flx_subscription_store and the history_write_validator
389
    if (m_config.sync_config->flx_sync_requested) {
1,600✔
390
        create_subscription_store();
589✔
391
        std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
589✔
392
        set_write_validator_factory(weak_sub_mgr);
589✔
393
    }
589✔
394

395
    // After a migration to FLX, if the user opens the realm with a flexible sync configuration, we need to first
396
    // upload any unsynced changes before updating to native FLX.
397
    // A subscription set is used as sentinel so we know when to stop uploading.
398
    // Note: Currently, a sentinel subscription set is always created even if there is nothing to upload.
399
    if (m_migration_store->is_migrated() && m_original_sync_config->flx_sync_requested) {
1,600✔
400
        m_migration_store->create_sentinel_subscription_set(*m_flx_subscription_store);
2✔
401
        m_migration_sentinel_query_version = m_migration_store->get_sentinel_subscription_set_version();
2✔
402
        REALM_ASSERT(m_migration_sentinel_query_version);
2✔
403
    }
2✔
404
}
1,600✔
405

406
void SyncSession::detach_from_sync_manager()
407
{
2✔
408
    shutdown_and_wait();
2✔
409
    util::CheckedLockGuard lk(m_state_mutex);
2✔
410
    m_sync_manager = nullptr;
2✔
411
}
2✔
412

413
void SyncSession::update_error_and_mark_file_for_deletion(SyncError& error, ShouldBackup should_backup)
414
{
74✔
415
    util::CheckedLockGuard config_lock(m_config_mutex);
74✔
416
    // Add a SyncFileActionMetadata marking the Realm as needing to be deleted.
417
    auto original_path = path();
74✔
418
    error.user_info[SyncError::c_original_file_path_key] = original_path;
74✔
419
    using Action = SyncFileAction;
74✔
420
    auto action = should_backup == ShouldBackup::yes ? Action::BackUpThenDeleteRealm : Action::DeleteRealm;
74✔
421
    std::string recovery_path = m_config.sync_config->user->create_file_action(
74✔
422
        action, original_path, m_config.sync_config->recovery_directory);
74✔
423
    if (should_backup == ShouldBackup::yes) {
74✔
424
        error.user_info[SyncError::c_recovery_file_path_key] = recovery_path;
74✔
425
    }
74✔
426
}
74✔
427

428
void SyncSession::download_fresh_realm(sync::ProtocolErrorInfo::Action server_requests_action)
429
{
192✔
430
    // first check that recovery will not be prevented
431
    if (server_requests_action == sync::ProtocolErrorInfo::Action::ClientResetNoRecovery) {
192✔
432
        auto mode = config(&SyncConfig::client_resync_mode);
4✔
433
        if (mode == ClientResyncMode::Recover) {
4✔
434
            handle_fresh_realm_downloaded(
2✔
435
                nullptr,
2✔
436
                {ErrorCodes::RuntimeError,
2✔
437
                 "A client reset is required but the server does not permit recovery for this client"},
2✔
438
                server_requests_action);
2✔
439
            return;
2✔
440
        }
2✔
441
    }
4✔
442

443
    std::vector<char> encryption_key;
190✔
444
    {
190✔
445
        util::CheckedLockGuard lock(m_config_mutex);
190✔
446
        encryption_key = m_config.encryption_key;
190✔
447
    }
190✔
448

449
    DBOptions options;
190✔
450
    options.allow_file_format_upgrade = false;
190✔
451
    options.enable_async_writes = false;
190✔
452
    if (!encryption_key.empty())
190✔
453
        options.encryption_key = encryption_key.data();
2✔
454

455
    DBRef db;
190✔
456
    auto fresh_path = client_reset::get_fresh_path_for(m_db->get_path());
190✔
457
    try {
190✔
458
        // We want to attempt to use a pre-existing file to reduce the chance of
459
        // downloading the first part of the file only to then delete it over
460
        // and over, but if we fail to open it then we should just start over.
461
        try {
190✔
462
            db = DB::create(sync::make_client_replication(), fresh_path, options);
190✔
463
        }
190✔
464
        catch (...) {
190✔
465
            util::File::try_remove(fresh_path);
10✔
466
        }
10✔
467

468
        if (!db) {
190✔
469
            db = DB::create(sync::make_client_replication(), fresh_path, options);
2✔
470
        }
2✔
471
    }
182✔
472
    catch (...) {
190✔
473
        // Failed to open the fresh path after attempting to delete it, so we
474
        // just can't do automatic recovery.
475
        handle_fresh_realm_downloaded(nullptr, exception_to_status(), server_requests_action);
8✔
476
        return;
8✔
477
    }
8✔
478

479
    util::CheckedLockGuard state_lock(m_state_mutex);
182✔
480
    if (m_state != State::Active) {
182✔
481
        return;
×
482
    }
×
483
    RealmConfig fresh_config;
182✔
484
    {
182✔
485
        util::CheckedLockGuard config_lock(m_config_mutex);
182✔
486
        fresh_config = m_config;
182✔
487
        fresh_config.path = fresh_path;
182✔
488
        // in case of migrations use the migrated config
489
        auto fresh_sync_config = m_migrated_sync_config ? *m_migrated_sync_config : *m_config.sync_config;
182✔
490
        // deep copy the sync config so we don't modify the live session's config
491
        fresh_config.sync_config = std::make_shared<SyncConfig>(fresh_sync_config);
182✔
492
        fresh_config.sync_config->client_resync_mode = ClientResyncMode::Manual;
182✔
493
        fresh_config.schema_version = m_previous_schema_version.value_or(m_config.schema_version);
182✔
494
    }
182✔
495

496
    auto fresh_sync_session = m_sync_manager->get_session(db, fresh_config);
182✔
497
    auto& history = static_cast<sync::ClientReplication&>(*db->get_replication());
182✔
498
    // the fresh Realm may apply writes to this db after it has outlived its sync session
499
    // the writes are used to generate a changeset for recovery, but are never committed
500
    history.set_write_validator_factory({});
182✔
501

502
    fresh_sync_session->assert_mutex_unlocked();
182✔
503
    // The fresh realm uses flexible sync.
504
    if (auto fresh_sub_store = fresh_sync_session->get_flx_subscription_store()) {
182✔
505
        auto fresh_sub = fresh_sub_store->get_latest();
72✔
506
        // The local realm uses flexible sync as well so copy the active subscription set to the fresh realm.
507
        if (auto local_subs_store = m_flx_subscription_store) {
72✔
508
            auto fresh_mut_sub = fresh_sub.make_mutable_copy();
54✔
509
            fresh_mut_sub.import(local_subs_store->get_active());
54✔
510
            fresh_sub = fresh_mut_sub.commit();
54✔
511
        }
54✔
512

513
        auto self = shared_from_this();
72✔
514
        using SubscriptionState = sync::SubscriptionSet::State;
72✔
515
        fresh_sub.get_state_change_notification(SubscriptionState::Complete)
72✔
516
            .then([=](SubscriptionState) -> util::Future<sync::SubscriptionSet> {
72✔
517
                if (server_requests_action != sync::ProtocolErrorInfo::Action::MigrateToFLX) {
70✔
518
                    return fresh_sub;
52✔
519
                }
52✔
520
                if (!self->m_migration_store->is_migration_in_progress()) {
18✔
521
                    return fresh_sub;
×
522
                }
×
523

524
                // fresh_sync_session is using a new realm file that doesn't have the migration_store info
525
                // so the query string from the local migration store will need to be provided
526
                auto query_string = self->m_migration_store->get_query_string();
18✔
527
                REALM_ASSERT(query_string);
18✔
528
                // Create subscriptions in the fresh realm based on the schema instructions received in the bootstrap
529
                // message.
530
                fresh_sync_session->m_migration_store->create_subscriptions(*fresh_sub_store, *query_string);
18✔
531
                return fresh_sub_store->get_latest()
18✔
532
                    .get_state_change_notification(SubscriptionState::Complete)
18✔
533
                    .then([=](SubscriptionState) {
18✔
534
                        return fresh_sub_store->get_latest();
18✔
535
                    });
18✔
536
            })
18✔
537
            .get_async([=](StatusWith<sync::SubscriptionSet>&& subs) {
72✔
538
                // Keep the sync session alive while it's downloading, but then close
539
                // it immediately
540
                fresh_sync_session->force_close();
72✔
541
                if (subs.is_ok()) {
72✔
542
                    self->handle_fresh_realm_downloaded(db, Status::OK(), server_requests_action,
70✔
543
                                                        std::move(subs.get_value()));
70✔
544
                }
70✔
545
                else {
2✔
546
                    self->handle_fresh_realm_downloaded(nullptr, subs.get_status(), server_requests_action);
2✔
547
                }
2✔
548
            });
72✔
549
    }
72✔
550
    else { // pbs
110✔
551
        fresh_sync_session->wait_for_download_completion([=, weak_self = weak_from_this()](Status s) {
110✔
552
            // Keep the sync session alive while it's downloading, but then close
553
            // it immediately
554
            fresh_sync_session->force_close();
110✔
555
            if (auto strong_self = weak_self.lock()) {
110✔
556
                strong_self->handle_fresh_realm_downloaded(db, s, server_requests_action);
110✔
557
            }
110✔
558
        });
110✔
559
    }
110✔
560
    fresh_sync_session->revive_if_needed();
182✔
561
}
182✔
562

563
void SyncSession::handle_fresh_realm_downloaded(DBRef db, Status status,
564
                                                sync::ProtocolErrorInfo::Action server_requests_action,
565
                                                std::optional<sync::SubscriptionSet> new_subs)
566
{
192✔
567
    util::CheckedUniqueLock lock(m_state_mutex);
192✔
568
    if (m_state != State::Active) {
192✔
569
        return;
×
570
    }
×
571
    // The download can fail for many reasons. For example:
572
    // - unable to write the fresh copy to the file system
573
    // - during download of the fresh copy, the fresh copy itself is reset
574
    // - in FLX mode there was a problem fulfilling the previously active subscription
575
    if (!status.is_ok()) {
192✔
576
        if (status == ErrorCodes::OperationAborted) {
18✔
577
            return;
6✔
578
        }
6✔
579
        lock.unlock();
12✔
580

581
        sync::SessionErrorInfo synthetic(
12✔
582
            Status{ErrorCodes::AutoClientResetFailed,
12✔
583
                   util::format("A fatal error occurred during client reset: '%1'", status.reason())},
12✔
584
            sync::IsFatal{true});
12✔
585
        handle_error(synthetic);
12✔
586
        return;
12✔
587
    }
18✔
588

589
    // Performing a client reset requires tearing down our current
590
    // sync session and creating a new one with the relevant client reset config. This
591
    // will result in session completion handlers firing
592
    // when the old session is torn down, which we don't want as this
593
    // is supposed to be transparent to the user.
594
    //
595
    // To avoid this, we need to move the completion handlers aside temporarily so
596
    // that moving to the inactive state doesn't clear them - they will be
597
    // re-registered when the session becomes active again.
598
    {
174✔
599
        m_server_requests_action = server_requests_action;
174✔
600
        m_client_reset_fresh_copy = db;
174✔
601
        CompletionCallbacks callbacks;
174✔
602
        std::swap(m_completion_callbacks, callbacks);
174✔
603
        // always swap back, even if advance_state throws
604
        auto guard = util::make_scope_exit([&]() noexcept {
174✔
605
            util::CheckedUniqueLock lock(m_state_mutex);
174✔
606
            if (m_completion_callbacks.empty())
174✔
607
                std::swap(callbacks, m_completion_callbacks);
174✔
608
            else
×
609
                m_completion_callbacks.merge(std::move(callbacks));
×
610
        });
174✔
611
        // Do not cancel the notifications on subscriptions.
612
        bool cancel_subscription_notifications = false;
174✔
613
        become_inactive(std::move(lock), Status::OK(), cancel_subscription_notifications); // unlocks the lock
174✔
614

615
        // Once the session is inactive, update sync config and subscription store after migration.
616
        if (server_requests_action == sync::ProtocolErrorInfo::Action::MigrateToFLX ||
174✔
617
            server_requests_action == sync::ProtocolErrorInfo::Action::RevertToPBS) {
174✔
618
            apply_sync_config_after_migration_or_rollback();
26✔
619
            auto flx_sync_requested = config(&SyncConfig::flx_sync_requested);
26✔
620
            update_subscription_store(flx_sync_requested, std::move(new_subs));
26✔
621
        }
26✔
622
    }
174✔
623
    revive_if_needed();
174✔
624
}
174✔
625

626
util::Future<void> SyncSession::pause_async()
627
{
28✔
628
    {
28✔
629
        util::CheckedUniqueLock lock(m_state_mutex);
28✔
630
        // Nothing to wait for if the session is already paused or inactive.
631
        if (m_state == SyncSession::State::Paused || m_state == SyncSession::State::Inactive) {
28✔
632
            return util::Future<void>::make_ready();
×
633
        }
×
634
    }
28✔
635
    // Transition immediately to `paused` state. Calling this function must guarantee that any
636
    // sync::Session object in SyncSession::m_session that existed prior to the time of invocation
637
    // must have been destroyed upon return. This allows the caller to follow up with a call to
638
    // sync::Client::notify_session_terminated() in order to be notified when the Realm file is closed. This works
639
    // so long as this SyncSession object remains in the `paused` state after the invocation of shutdown().
640
    pause();
28✔
641
    return m_client.notify_session_terminated();
28✔
642
}
28✔
643

644
void SyncSession::OnlyForTesting::handle_error(SyncSession& session, sync::SessionErrorInfo&& error)
645
{
16✔
646
    session.handle_error(std::move(error));
16✔
647
}
16✔
648

649
util::Future<void> SyncSession::OnlyForTesting::pause_async(SyncSession& session)
650
{
2✔
651
    return session.pause_async();
2✔
652
}
2✔
653

654
// This method should only be called from within the error handler callback registered upon the underlying
655
// `m_session`.
656
void SyncSession::handle_error(sync::SessionErrorInfo error)
657
{
520✔
658
    enum class NextStateAfterError { none, inactive, error };
520✔
659
    auto next_state = error.is_fatal ? NextStateAfterError::error : NextStateAfterError::none;
520✔
660
    std::optional<ShouldBackup> delete_file;
520✔
661
    bool log_out_user = false;
520✔
662
    bool unrecognized_by_client = false;
520✔
663

664
    if (error.status == ErrorCodes::AutoClientResetFailed) {
520✔
665
        // At this point, automatic recovery has been attempted but it failed.
666
        // Fallback to a manual reset and let the user try to handle it.
667
        next_state = NextStateAfterError::inactive;
50✔
668
        delete_file = ShouldBackup::yes;
50✔
669
    }
50✔
670
    else if (error.server_requests_action != sync::ProtocolErrorInfo::Action::NoAction) {
470✔
671
        switch (error.server_requests_action) {
454✔
672
            case sync::ProtocolErrorInfo::Action::NoAction:
✔
673
                REALM_UNREACHABLE(); // This is not sent by the MongoDB server
674
            case sync::ProtocolErrorInfo::Action::ApplicationBug:
37✔
675
                [[fallthrough]];
37✔
676
            case sync::ProtocolErrorInfo::Action::ProtocolViolation:
43✔
677
                next_state = NextStateAfterError::inactive;
43✔
678
                break;
43✔
679
            case sync::ProtocolErrorInfo::Action::Warning:
30✔
680
                break; // not fatal, but should be bubbled up to the user below.
30✔
681
            case sync::ProtocolErrorInfo::Action::Transient:
65✔
682
                // Not real errors, don't need to be reported to the binding.
683
                return;
65✔
684
            case sync::ProtocolErrorInfo::Action::DeleteRealm:
✔
685
                next_state = NextStateAfterError::inactive;
×
686
                delete_file = ShouldBackup::no;
×
687
                break;
×
688
            case sync::ProtocolErrorInfo::Action::ClientReset:
184✔
689
                [[fallthrough]];
184✔
690
            case sync::ProtocolErrorInfo::Action::ClientResetNoRecovery:
188✔
691
                switch (config(&SyncConfig::client_resync_mode)) {
188✔
692
                    case ClientResyncMode::Manual:
24✔
693
                        next_state = NextStateAfterError::inactive;
24✔
694
                        delete_file = ShouldBackup::yes;
24✔
695
                        break;
24✔
696
                    case ClientResyncMode::DiscardLocal:
82✔
697
                        [[fallthrough]];
82✔
698
                    case ClientResyncMode::RecoverOrDiscard:
96✔
699
                        [[fallthrough]];
96✔
700
                    case ClientResyncMode::Recover:
164✔
701
                        download_fresh_realm(error.server_requests_action);
164✔
702
                        return; // do not propagate the error to the user at this point
164✔
703
                }
188✔
704
                break;
24✔
705
            case sync::ProtocolErrorInfo::Action::MigrateToFLX:
24✔
706
                // Should not receive this error if original sync config is FLX
707
                REALM_ASSERT(!m_original_sync_config->flx_sync_requested);
18✔
708
                REALM_ASSERT(error.migration_query_string && !error.migration_query_string->empty());
18✔
709
                // Original config was PBS, migrating to FLX
710
                m_migration_store->migrate_to_flx(*error.migration_query_string,
18✔
711
                                                  m_original_sync_config->partition_value);
18✔
712
                save_sync_config_after_migration_or_rollback();
18✔
713
                download_fresh_realm(error.server_requests_action);
18✔
714
                return;
18✔
715
            case sync::ProtocolErrorInfo::Action::RevertToPBS:
10✔
716
                // If the client was updated to use FLX natively, but the server was rolled back to PBS,
717
                // the server should be sending switch_to_flx_sync; throw exception if this error is not
718
                // received.
719
                if (m_original_sync_config->flx_sync_requested) {
10✔
720
                    throw LogicError(ErrorCodes::InvalidServerResponse,
×
721
                                     "Received 'RevertToPBS' from server after rollback while client is natively "
×
722
                                     "using FLX - expected 'SwitchToPBS'");
×
723
                }
×
724
                // Original config was PBS, rollback the migration
725
                m_migration_store->rollback_to_pbs();
10✔
726
                save_sync_config_after_migration_or_rollback();
10✔
727
                download_fresh_realm(error.server_requests_action);
10✔
728
                return;
10✔
729
            case sync::ProtocolErrorInfo::Action::RefreshUser:
22✔
730
                if (auto u = user()) {
22✔
731
                    u->request_access_token(handle_refresh(shared_from_this(), false));
22✔
732
                }
22✔
733
                return;
22✔
734
            case sync::ProtocolErrorInfo::Action::RefreshLocation:
48✔
735
                if (auto u = user()) {
48✔
736
                    u->request_refresh_location(handle_refresh(shared_from_this(), true));
48✔
737
                }
48✔
738
                return;
48✔
739
            case sync::ProtocolErrorInfo::Action::LogOutUser:
✔
740
                next_state = NextStateAfterError::inactive;
×
741
                log_out_user = true;
×
742
                break;
×
743
            case sync::ProtocolErrorInfo::Action::MigrateSchema:
30✔
744
                util::CheckedUniqueLock lock(m_state_mutex);
30✔
745
                // Should only be received for FLX sync.
746
                REALM_ASSERT(m_original_sync_config->flx_sync_requested);
30✔
747
                m_previous_schema_version = error.previous_schema_version;
30✔
748
                return; // do not propagate the error to the user at this point
30✔
749
        }
454✔
750
    }
454✔
751
    else {
16✔
752
        // Unrecognized error code.
753
        unrecognized_by_client = true;
16✔
754
    }
16✔
755

756
    util::CheckedUniqueLock lock(m_state_mutex);
163✔
757
    SyncError sync_error{error.status, error.is_fatal, error.log_url, std::move(error.compensating_writes)};
163✔
758
    // `action` is used over `shouldClientReset` and `isRecoveryModeDisabled`.
759
    sync_error.server_requests_action = error.server_requests_action;
163✔
760
    sync_error.is_unrecognized_by_client = unrecognized_by_client;
163✔
761

762
    if (delete_file)
163✔
763
        update_error_and_mark_file_for_deletion(sync_error, *delete_file);
74✔
764

765
    if (m_state == State::Dying && error.is_fatal) {
163✔
766
        become_inactive(std::move(lock), error.status);
2✔
767
        return;
2✔
768
    }
2✔
769

770
    // Don't bother invoking m_config.error_handler if the sync is inactive.
771
    // It does not make sense to call the handler when the session is closed.
772
    if (m_state == State::Inactive || m_state == State::Paused) {
161✔
773
        return;
×
774
    }
×
775

776
    switch (next_state) {
161✔
777
        case NextStateAfterError::none:
46✔
778
            if (config(&SyncConfig::cancel_waits_on_nonfatal_error)) {
46✔
779
                cancel_pending_waits(std::move(lock), sync_error.status); // unlocks the mutex
×
780
            }
×
781
            break;
46✔
782
        case NextStateAfterError::inactive: {
115✔
783
            become_inactive(std::move(lock), sync_error.status);
115✔
784
            break;
115✔
785
        }
×
786
        case NextStateAfterError::error: {
✔
787
            cancel_pending_waits(std::move(lock), sync_error.status);
×
788
            break;
×
789
        }
×
790
    }
161✔
791

792
    if (log_out_user) {
161✔
793
        if (auto u = user())
×
794
            u->request_log_out();
×
795
    }
×
796

797
    if (auto error_handler = config(&SyncConfig::error_handler)) {
161✔
798
        error_handler(shared_from_this(), std::move(sync_error));
161✔
799
    }
161✔
800
}
161✔
801

802
void SyncSession::cancel_pending_waits(util::CheckedUniqueLock lock, Status error)
803
{
38✔
804
    CompletionCallbacks callbacks;
38✔
805
    std::swap(callbacks, m_completion_callbacks);
38✔
806

807
    // Inform any waiters on pending subscription states that they were cancelled
808
    if (m_flx_subscription_store) {
38✔
809
        auto subscription_store = m_flx_subscription_store;
×
810
        m_state_mutex.unlock(lock);
×
811
        subscription_store->notify_all_state_change_notifications(error);
×
812
    }
×
813
    else {
38✔
814
        m_state_mutex.unlock(lock);
38✔
815
    }
38✔
816

817
    // Inform any queued-up completion handlers that they were cancelled.
818
    for (auto& [id, callback] : callbacks)
38✔
819
        callback.second(error);
34✔
820
}
38✔
821

822
void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded,
823
                                         uint64_t uploadable, uint64_t snapshot_version, double download_estimate,
824
                                         double upload_estimate, int64_t query_version)
825
{
4,179✔
826
    m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, snapshot_version, download_estimate,
4,179✔
827
                               upload_estimate, query_version);
4,179✔
828
}
4,179✔
829

830
static sync::Session::Config::ClientReset make_client_reset_config(const RealmConfig& base_config,
831
                                                                   const std::shared_ptr<SyncConfig>& sync_config,
832
                                                                   DBRef&& fresh_copy, bool recovery_is_allowed,
833
                                                                   bool schema_migration_detected)
834
{
174✔
835
    REALM_ASSERT(sync_config->client_resync_mode != ClientResyncMode::Manual);
174✔
836

837
    sync::Session::Config::ClientReset config;
174✔
838
    config.mode = sync_config->client_resync_mode;
174✔
839
    config.fresh_copy = std::move(fresh_copy);
174✔
840
    config.recovery_is_allowed = recovery_is_allowed;
174✔
841

842
    // The conditions here are asymmetric because if we have *either* a before
843
    // or after callback we need to make sure to initialize the local schema
844
    // before the client reset happens.
845
    if (!sync_config->notify_before_client_reset && !sync_config->notify_after_client_reset)
174✔
846
        return config;
28✔
847

848
    // We cannot initialize the local schema in case of a sync schema migration.
849
    // Currently, a schema migration involves breaking changes so opening the realm
850
    // with the new schema results in a crash.
851
    if (schema_migration_detected)
146✔
852
        return config;
4✔
853

854
    RealmConfig realm_config = base_config;
142✔
855
    realm_config.sync_config = std::make_shared<SyncConfig>(*sync_config); // deep copy
142✔
856
    realm_config.scheduler = util::Scheduler::make_dummy();
142✔
857

858
    if (sync_config->notify_after_client_reset) {
142✔
859
        config.notify_after_client_reset = [realm_config](VersionID previous_version, bool did_recover) {
138✔
860
            auto coordinator = _impl::RealmCoordinator::get_coordinator(realm_config);
104✔
861
            ThreadSafeReference active_after = coordinator->get_unbound_realm();
104✔
862
            SharedRealm frozen_before = coordinator->get_realm(realm_config, previous_version);
104✔
863
            REALM_ASSERT(frozen_before);
104✔
864
            REALM_ASSERT(frozen_before->is_frozen());
104✔
865
            realm_config.sync_config->notify_after_client_reset(std::move(frozen_before), std::move(active_after),
104✔
866
                                                                did_recover);
104✔
867
        };
104✔
868
    }
138✔
869
    config.notify_before_client_reset = [config = std::move(realm_config)]() -> VersionID {
142✔
870
        // Opening the Realm live here may make a write if the schema is different
871
        // than what exists on disk. It is necessary to pass a fully usable Realm
872
        // to the user here. Note that the schema changes made here will be considered
873
        // an "offline write" to be recovered if this is recovery mode.
874
        auto before = Realm::get_shared_realm(config);
142✔
875
        if (auto& notify_before = config.sync_config->notify_before_client_reset) {
142✔
876
            notify_before(config.sync_config->freeze_before_reset_realm ? before->freeze() : before);
140✔
877
        }
140✔
878
        // Note that if the SDK wrote to the Realm (hopefully by requesting a
879
        // live instance and not opening a secondary one), this may be a
880
        // different version than what we had before calling the callback.
881
        before->refresh();
142✔
882
        return before->read_transaction_version();
142✔
883
    };
142✔
884

885
    return config;
142✔
886
}
146✔
887

888
void SyncSession::create_sync_session()
889
{
2,008✔
890
    if (m_session)
2,008✔
891
        return;
×
892

893
    util::CheckedLockGuard config_lock(m_config_mutex);
2,008✔
894

895
    REALM_ASSERT(m_config.sync_config);
2,008✔
896
    SyncConfig& sync_config = *m_config.sync_config;
2,008✔
897
    REALM_ASSERT(sync_config.user);
2,008✔
898

899
    sync::Session::Config session_config;
2,008✔
900
    session_config.signed_user_token = sync_config.user->access_token();
2,008✔
901
    session_config.user_id = sync_config.user->user_id();
2,008✔
902
    session_config.realm_identifier = sync_config.partition_value;
2,008✔
903
    session_config.verify_servers_ssl_certificate = sync_config.client_validate_ssl;
2,008✔
904
    session_config.ssl_trust_certificate_path = sync_config.ssl_trust_certificate_path;
2,008✔
905
    session_config.ssl_verify_callback = sync_config.ssl_verify_callback;
2,008✔
906
    session_config.proxy_config = sync_config.proxy_config;
2,008✔
907
    session_config.simulate_integration_error = sync_config.simulate_integration_error;
2,008✔
908
    session_config.flx_bootstrap_batch_size_bytes = sync_config.flx_bootstrap_batch_size_bytes;
2,008✔
909
    session_config.session_reason =
2,008✔
910
        client_reset::is_fresh_path(m_config.path) ? sync::SessionReason::ClientReset : sync::SessionReason::Sync;
2,008✔
911
    session_config.schema_version = m_config.schema_version;
2,008✔
912

913
    if (sync_config.on_sync_client_event_hook) {
2,008✔
914
        session_config.on_sync_client_event_hook = [hook = sync_config.on_sync_client_event_hook,
108✔
915
                                                    anchor = weak_from_this()](const SyncClientHookData& data) {
1,060✔
916
            return hook(anchor, data);
1,060✔
917
        };
1,060✔
918
    }
108✔
919

920
    {
2,008✔
921
        // At this point the sync route was either updated when the first App request was performed, or
922
        // was populated by a generated value that will be used for first contact. If the generated sync
923
        // route is not correct, either a redirection will be received or the connection will fail,
924
        // resulting in an update to both the access token and the location.
925
        auto [sync_route, verified] = m_sync_manager->sync_route();
2,008✔
926
        REALM_ASSERT_EX(!sync_route.empty(), "Server URL cannot be empty");
2,008✔
927

928
        if (!m_client.decompose_server_url(sync_route, session_config.protocol_envelope,
2,008✔
929
                                           session_config.server_address, session_config.server_port,
2,008✔
930
                                           session_config.service_identifier)) {
2,008✔
931
            throw sync::BadServerUrl(sync_route);
×
932
        }
×
933
        session_config.server_verified = verified;
2,008✔
934

935
        m_server_url = sync_route;
2,008✔
936
        m_server_url_verified = verified;
2,008✔
937
    }
2,008✔
938

939
    if (sync_config.authorization_header_name) {
2,008✔
940
        session_config.authorization_header_name = *sync_config.authorization_header_name;
×
941
    }
×
942
    session_config.custom_http_headers = sync_config.custom_http_headers;
2,008✔
943

944
    if (m_server_requests_action != sync::ProtocolErrorInfo::Action::NoAction) {
2,008✔
945
        // Migrations are allowed to recover local data.
946
        const bool allowed_to_recover = m_server_requests_action == sync::ProtocolErrorInfo::Action::ClientReset ||
174✔
947
                                        m_server_requests_action == sync::ProtocolErrorInfo::Action::MigrateToFLX ||
174✔
948
                                        m_server_requests_action == sync::ProtocolErrorInfo::Action::RevertToPBS;
174✔
949
        // Use the original sync config, not the updated one from the migration store
950
        session_config.client_reset_config =
174✔
951
            make_client_reset_config(m_config, m_original_sync_config, std::move(m_client_reset_fresh_copy),
174✔
952
                                     allowed_to_recover, m_previous_schema_version.has_value());
174✔
953
        session_config.schema_version = m_previous_schema_version.value_or(m_config.schema_version);
174✔
954
        m_server_requests_action = sync::ProtocolErrorInfo::Action::NoAction;
174✔
955
    }
174✔
956

957
    m_session = m_client.make_session(m_db, m_flx_subscription_store, m_migration_store, std::move(session_config));
2,008✔
958

959
    std::weak_ptr<SyncSession> weak_self = weak_from_this();
2,008✔
960

961
    // Set up the wrapped progress handler callback
962
    m_session->set_progress_handler([weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable,
2,008✔
963
                                                uint_fast64_t uploaded, uint_fast64_t uploadable,
2,008✔
964
                                                uint_fast64_t snapshot_version, double download_estimate,
2,008✔
965
                                                double upload_estimate, int64_t query_version) {
4,214✔
966
        if (auto self = weak_self.lock()) {
4,214✔
967
            self->handle_progress_update(downloaded, downloadable, uploaded, uploadable, snapshot_version,
4,179✔
968
                                         download_estimate, upload_estimate, query_version);
4,179✔
969
        }
4,179✔
970
    });
4,214✔
971

972
    // Sets up the connection state listener. This callback is used for both reporting errors as well as changes to
973
    // the connection state.
974
    m_session->set_connection_state_change_listener(
2,008✔
975
        [weak_self](sync::ConnectionState state, std::optional<sync::SessionErrorInfo> error) {
4,372✔
976
            using cs = sync::ConnectionState;
4,372✔
977
            ConnectionState new_state = [&] {
4,372✔
978
                switch (state) {
4,372✔
979
                    case cs::disconnected:
432✔
980
                        return ConnectionState::Disconnected;
432✔
981
                    case cs::connecting:
2,008✔
982
                        return ConnectionState::Connecting;
2,008✔
983
                    case cs::connected:
1,932✔
984
                        return ConnectionState::Connected;
1,932✔
985
                }
4,372✔
986
                REALM_UNREACHABLE();
987
            }();
×
988
            // If the OS SyncSession object is destroyed, we ignore any events from the underlying Session as there is
989
            // nothing useful we can do with them.
990
            if (auto self = weak_self.lock()) {
4,372✔
991
                self->update_connection_state(new_state);
4,333✔
992
                if (error) {
4,333✔
993
                    self->handle_error(std::move(*error));
492✔
994
                }
492✔
995
            }
4,333✔
996
        });
4,372✔
997
}
2,008✔
998

999
void SyncSession::update_connection_state(ConnectionState new_state)
1000
{
4,333✔
1001
    if (new_state == ConnectionState::Connected) {
4,333✔
1002
        util::CheckedLockGuard lock(m_config_mutex);
1,911✔
1003
        m_server_url_verified = true;
1,911✔
1004
    }
1,911✔
1005

1006
    ConnectionState old_state;
4,333✔
1007
    {
4,333✔
1008
        util::CheckedLockGuard lock(m_connection_state_mutex);
4,333✔
1009
        old_state = m_connection_state;
4,333✔
1010
        m_connection_state = new_state;
4,333✔
1011
    }
4,333✔
1012

1013
    // Notify any registered connection callbacks of the state transition
1014
    if (old_state != new_state) {
4,333✔
1015
        m_connection_change_notifier.invoke_callbacks(old_state, new_state);
4,265✔
1016
    }
4,265✔
1017
}
4,333✔
1018

1019
void SyncSession::nonsync_transact_notify(sync::version_type version)
1020
{
9,232✔
1021
    m_progress_notifier.set_local_version(version);
9,232✔
1022

1023
    util::CheckedUniqueLock lock(m_state_mutex);
9,232✔
1024
    switch (m_state) {
9,232✔
1025
        case State::Active:
8,861✔
1026
        case State::WaitingForAccessToken:
8,863✔
1027
            if (m_session) {
8,863✔
1028
                m_session->nonsync_transact_notify(version);
8,861✔
1029
            }
8,861✔
1030
            break;
8,863✔
1031
        case State::Dying:
✔
1032
        case State::Inactive:
22✔
1033
        case State::Paused:
369✔
1034
            break;
369✔
1035
    }
9,232✔
1036
}
9,232✔
1037

1038
void SyncSession::revive_if_needed()
1039
{
2,367✔
1040
    util::CheckedUniqueLock lock(m_state_mutex);
2,367✔
1041
    switch (m_state) {
2,367✔
1042
        case State::Active:
573✔
1043
        case State::WaitingForAccessToken:
573✔
1044
        case State::Paused:
579✔
1045
            return;
579✔
1046
        case State::Dying:
2✔
1047
        case State::Inactive:
1,788✔
1048
            do_revive(std::move(lock));
1,788✔
1049
            break;
1,788✔
1050
    }
2,367✔
1051
}
2,367✔
1052

1053
void SyncSession::handle_reconnect()
1054
{
4✔
1055
    util::CheckedUniqueLock lock(m_state_mutex);
4✔
1056
    switch (m_state) {
4✔
1057
        case State::Active:
4✔
1058
            m_session->cancel_reconnect_delay();
4✔
1059
            break;
4✔
1060
        case State::Dying:
✔
1061
        case State::Inactive:
✔
1062
        case State::WaitingForAccessToken:
✔
1063
        case State::Paused:
✔
1064
            break;
×
1065
    }
4✔
1066
}
4✔
1067

1068
void SyncSession::force_close()
1069
{
309✔
1070
    util::CheckedUniqueLock lock(m_state_mutex);
309✔
1071
    switch (m_state) {
309✔
1072
        case State::Active:
239✔
1073
        case State::Dying:
292✔
1074
        case State::WaitingForAccessToken:
296✔
1075
            become_inactive(std::move(lock));
296✔
1076
            break;
296✔
1077
        case State::Inactive:
11✔
1078
        case State::Paused:
13✔
1079
            break;
13✔
1080
    }
309✔
1081
}
309✔
1082

1083
void SyncSession::pause()
1084
{
214✔
1085
    util::CheckedUniqueLock lock(m_state_mutex);
214✔
1086
    switch (m_state) {
214✔
1087
        case State::Active:
210✔
1088
        case State::Dying:
210✔
1089
        case State::WaitingForAccessToken:
210✔
1090
        case State::Inactive:
212✔
1091
            become_paused(std::move(lock));
212✔
1092
            break;
212✔
1093
        case State::Paused:
2✔
1094
            break;
2✔
1095
    }
214✔
1096
}
214✔
1097

1098
void SyncSession::resume()
1099
{
194✔
1100
    util::CheckedUniqueLock lock(m_state_mutex);
194✔
1101
    switch (m_state) {
194✔
UNCOV
1102
        case State::Active:
✔
UNCOV
1103
        case State::WaitingForAccessToken:
✔
UNCOV
1104
            return;
×
1105
        case State::Paused:
194✔
1106
        case State::Dying:
194✔
1107
        case State::Inactive:
194✔
1108
            do_revive(std::move(lock));
194✔
1109
            break;
194✔
1110
    }
194✔
1111
}
194✔
1112

1113
void SyncSession::do_revive(util::CheckedUniqueLock&& lock)
1114
{
1,998✔
1115
    auto u = user();
1,998✔
1116
    // If the sync manager has a valid route and the user and it's access token
1117
    // are valid, then revive the session.
1118
    if (!u || !u->access_token_refresh_required()) {
1,998✔
1119
        become_active();
1,978✔
1120
        m_state_mutex.unlock(lock);
1,978✔
1121
        return;
1,978✔
1122
    }
1,978✔
1123

1124
    // Otherwise, either the access token has expired or the location info hasn't
1125
    // been requested since the app was started - request a new access token to
1126
    // refresh both.
1127
    become_waiting_for_access_token();
20✔
1128
    // Release the lock for SDKs with a single threaded
1129
    // networking implementation such as our test suite
1130
    // so that the update can trigger a state change from
1131
    // the completion handler.
1132
    m_state_mutex.unlock(lock);
20✔
1133
    initiate_access_token_refresh();
20✔
1134
}
20✔
1135

1136
void SyncSession::close()
1137
{
100✔
1138
    util::CheckedUniqueLock lock(m_state_mutex);
100✔
1139
    close(std::move(lock));
100✔
1140
}
100✔
1141

1142
void SyncSession::close(util::CheckedUniqueLock lock)
1143
{
1,701✔
1144
    switch (m_state) {
1,701✔
1145
        case State::Active: {
1,167✔
1146
            switch (config(&SyncConfig::stop_policy)) {
1,167✔
1147
                case SyncSessionStopPolicy::Immediately:
1,083✔
1148
                    become_inactive(std::move(lock));
1,083✔
1149
                    break;
1,083✔
1150
                case SyncSessionStopPolicy::LiveIndefinitely:
✔
1151
                    // Don't do anything; session lives forever.
1152
                    m_state_mutex.unlock(lock);
×
1153
                    break;
×
1154
                case SyncSessionStopPolicy::AfterChangesUploaded:
84✔
1155
                    // Wait for all pending changes to upload.
1156
                    become_dying(std::move(lock));
84✔
1157
                    break;
84✔
1158
            }
1,167✔
1159
            break;
1,167✔
1160
        }
1,167✔
1161
        case State::Dying:
1,167✔
1162
            m_state_mutex.unlock(lock);
18✔
1163
            break;
18✔
1164
        case State::Paused:
18✔
1165
        case State::Inactive: {
510✔
1166
            // We need to unregister from the sync manager if it still exists so that we don't end up
1167
            // holding the DBRef open after the session is closed. Otherwise we can end up preventing
1168
            // the user from deleting the realm when it's in the paused/inactive state.
1169
            if (m_sync_manager) {
510✔
1170
                m_sync_manager->unregister_session(m_db->get_path());
506✔
1171
            }
506✔
1172
            m_state_mutex.unlock(lock);
510✔
1173
            break;
510✔
1174
        }
18✔
1175
        case State::WaitingForAccessToken:
6✔
1176
            // Immediately kill the session.
1177
            become_inactive(std::move(lock));
6✔
1178
            break;
6✔
1179
    }
1,701✔
1180
}
1,701✔
1181

1182
void SyncSession::shutdown_and_wait()
1183
{
125✔
1184
    {
125✔
1185
        // Transition immediately to `inactive` state. Calling this function must guarantee that any
1186
        // sync::Session object in SyncSession::m_session that existed prior to the time of invocation
1187
        // must have been destroyed upon return. This allows the caller to follow up with a call to
1188
        // sync::Client::wait_for_session_terminations_or_client_stopped() in order to wait for the
1189
        // Realm file to be closed. This works so long as this SyncSession object remains in the
1190
        // `inactive` state after the invocation of shutdown_and_wait().
1191
        util::CheckedUniqueLock lock(m_state_mutex);
125✔
1192
        if (m_state != State::Inactive && m_state != State::Paused) {
125✔
1193
            become_inactive(std::move(lock));
69✔
1194
        }
69✔
1195
    }
125✔
1196
    m_client.wait_for_session_terminations();
125✔
1197
}
125✔
1198

1199
void SyncSession::update_access_token(std::string_view signed_token)
1200
{
30✔
1201
    util::CheckedUniqueLock lock(m_state_mutex);
30✔
1202
    switch (m_state) {
30✔
1203
        case State::Active:
6✔
1204
            m_session->refresh(signed_token);
6✔
1205
            break;
6✔
1206
        case State::WaitingForAccessToken:
8✔
1207
            become_active();
8✔
1208
            break;
8✔
1209
        case State::Paused:
✔
1210
            // token will be pulled from user when the session is unpaused
1211
            return;
×
1212
        case State::Dying:
✔
1213
        case State::Inactive:
16✔
1214
            do_revive(std::move(lock));
16✔
1215
            break;
16✔
1216
    }
30✔
1217
}
30✔
1218

1219
void SyncSession::initiate_access_token_refresh()
1220
{
20✔
1221
    if (auto session_user = user()) {
20✔
1222
        session_user->request_access_token(handle_refresh(shared_from_this(), false));
20✔
1223
    }
20✔
1224
}
20✔
1225

1226
void SyncSession::add_completion_callback(util::UniqueFunction<void(Status)> callback, ProgressDirection direction)
1227
{
2,623✔
1228
    bool is_download = (direction == ProgressDirection::download);
2,623✔
1229

1230
    m_completion_request_counter++;
2,623✔
1231
    m_completion_callbacks.emplace_hint(m_completion_callbacks.end(), m_completion_request_counter,
2,623✔
1232
                                        std::make_pair(direction, std::move(callback)));
2,623✔
1233
    // If the state is inactive then just store the callback and return. The callback will get
1234
    // re-registered with the underlying session if/when the session ever becomes active again.
1235
    if (!m_session) {
2,623✔
1236
        return;
317✔
1237
    }
317✔
1238

1239
    auto waiter = is_download ? &sync::Session::async_wait_for_download_completion
2,306✔
1240
                              : &sync::Session::async_wait_for_upload_completion;
2,306✔
1241

1242
    (m_session.get()->*waiter)([weak_self = weak_from_this(), id = m_completion_request_counter](Status status) {
2,306✔
1243
        auto self = weak_self.lock();
2,300✔
1244
        if (!self)
2,300✔
1245
            return;
64✔
1246
        util::CheckedUniqueLock lock(self->m_state_mutex);
2,236✔
1247
        auto callback_node = self->m_completion_callbacks.extract(id);
2,236✔
1248
        lock.unlock();
2,236✔
1249
        if (callback_node) {
2,236✔
1250
            callback_node.mapped().second(std::move(status));
2,032✔
1251
        }
2,032✔
1252
    });
2,236✔
1253
}
2,306✔
1254

1255
void SyncSession::wait_for_upload_completion(util::UniqueFunction<void(Status)>&& callback)
1256
{
946✔
1257
    util::CheckedUniqueLock lock(m_state_mutex);
946✔
1258
    add_completion_callback(std::move(callback), ProgressDirection::upload);
946✔
1259
}
946✔
1260

1261
void SyncSession::wait_for_download_completion(util::UniqueFunction<void(Status)>&& callback)
1262
{
1,200✔
1263
    util::CheckedUniqueLock lock(m_state_mutex);
1,200✔
1264
    add_completion_callback(std::move(callback), ProgressDirection::download);
1,200✔
1265
}
1,200✔
1266

1267
uint64_t SyncSession::register_progress_notifier(std::function<ProgressNotifierCallback>&& notifier,
1268
                                                 ProgressDirection direction, bool is_streaming)
1269
{
36✔
1270
    int64_t pending_query_version = 0;
36✔
1271
    if (auto sub_store = get_flx_subscription_store()) {
36✔
1272
        pending_query_version = sub_store->get_version_info().latest;
16✔
1273
    }
16✔
1274
    return m_progress_notifier.register_callback(std::move(notifier), direction, is_streaming, pending_query_version);
36✔
1275
}
36✔
1276

1277
void SyncSession::unregister_progress_notifier(uint64_t token)
1278
{
12✔
1279
    m_progress_notifier.unregister_callback(token);
12✔
1280
}
12✔
1281

1282
uint64_t SyncSession::register_connection_change_callback(std::function<ConnectionStateChangeCallback>&& callback)
1283
{
6✔
1284
    return m_connection_change_notifier.add_callback(std::move(callback));
6✔
1285
}
6✔
1286

1287
void SyncSession::unregister_connection_change_callback(uint64_t token)
1288
{
2✔
1289
    m_connection_change_notifier.remove_callback(token);
2✔
1290
}
2✔
1291

1292
SyncSession::~SyncSession() {}
1,594✔
1293

1294
SyncSession::State SyncSession::state() const
1295
{
179,495✔
1296
    util::CheckedUniqueLock lock(m_state_mutex);
179,495✔
1297
    return m_state;
179,495✔
1298
}
179,495✔
1299

1300
SyncSession::ConnectionState SyncSession::connection_state() const
1301
{
5,194✔
1302
    util::CheckedUniqueLock lock(m_connection_state_mutex);
5,194✔
1303
    return m_connection_state;
5,194✔
1304
}
5,194✔
1305

1306
std::string const& SyncSession::path() const
1307
{
240✔
1308
    return m_db->get_path();
240✔
1309
}
240✔
1310

1311
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_flx_subscription_store()
1312
{
3,849,626✔
1313
    util::CheckedLockGuard lock(m_state_mutex);
3,849,626✔
1314
    return m_flx_subscription_store;
3,849,626✔
1315
}
3,849,626✔
1316

1317
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_subscription_store_base()
1318
{
2✔
1319
    util::CheckedLockGuard lock(m_state_mutex);
2✔
1320
    return m_subscription_store_base;
2✔
1321
}
2✔
1322

1323
sync::SaltedFileIdent SyncSession::get_file_ident() const
1324
{
164✔
1325
    auto repl = m_db->get_replication();
164✔
1326
    REALM_ASSERT(repl);
164✔
1327
    REALM_ASSERT(dynamic_cast<sync::ClientReplication*>(repl));
164✔
1328

1329
    sync::SaltedFileIdent ret;
164✔
1330
    sync::version_type unused_version;
164✔
1331
    sync::SyncProgress unused_progress;
164✔
1332
    static_cast<sync::ClientReplication*>(repl)->get_history().get_status(unused_version, ret, unused_progress);
164✔
1333
    return ret;
164✔
1334
}
164✔
1335

1336
std::string SyncSession::get_appservices_connection_id() const
1337
{
20✔
1338
    util::CheckedLockGuard lk(m_state_mutex);
20✔
1339
    if (!m_session) {
20✔
1340
        return {};
×
1341
    }
×
1342
    return m_session->get_appservices_connection_id();
20✔
1343
}
20✔
1344

1345
void SyncSession::update_configuration(SyncConfig new_config)
1346
{
8✔
1347
    while (true) {
18✔
1348
        util::CheckedUniqueLock state_lock(m_state_mutex);
18✔
1349
        if (m_state != State::Inactive && m_state != State::Paused) {
18✔
1350
            // Changing the state releases the lock, which means that by the
1351
            // time we reacquire the lock the state may have changed again
1352
            // (either due to one of the callbacks being invoked or another
1353
            // thread coincidentally doing something). We just attempt to keep
1354
            // switching it to inactive until it stays there.
1355
            become_inactive(std::move(state_lock));
10✔
1356
            continue;
10✔
1357
        }
10✔
1358

1359
        util::CheckedUniqueLock config_lock(m_config_mutex);
8✔
1360
        REALM_ASSERT(m_state == State::Inactive || m_state == State::Paused);
8!
1361
        REALM_ASSERT(!m_session);
8✔
1362
        REALM_ASSERT(m_config.sync_config->user == new_config.user);
8✔
1363
        // Since this is used for testing purposes only, just update the current sync_config
1364
        m_config.sync_config = std::make_shared<SyncConfig>(std::move(new_config));
8✔
1365
        break;
8✔
1366
    }
18✔
1367
    revive_if_needed();
8✔
1368
}
8✔
1369

1370
void SyncSession::apply_sync_config_after_migration_or_rollback()
1371
{
26✔
1372
    // Migration state changed - Update the configuration to
1373
    // match the new sync mode.
1374
    util::CheckedLockGuard cfg_lock(m_config_mutex);
26✔
1375
    if (!m_migrated_sync_config)
26✔
1376
        return;
2✔
1377

1378
    m_config.sync_config = m_migrated_sync_config;
24✔
1379
    m_migrated_sync_config.reset();
24✔
1380
}
24✔
1381

1382
void SyncSession::save_sync_config_after_migration_or_rollback()
1383
{
28✔
1384
    util::CheckedLockGuard cfg_lock(m_config_mutex);
28✔
1385
    m_migrated_sync_config = m_migration_store->convert_sync_config(m_original_sync_config);
28✔
1386
}
28✔
1387

1388
void SyncSession::update_subscription_store(bool flx_sync_requested, std::optional<sync::SubscriptionSet> new_subs)
1389
{
52✔
1390
    util::CheckedUniqueLock lock(m_state_mutex);
52✔
1391

1392
    // The session should be closed before updating the FLX subscription store
1393
    REALM_ASSERT(!m_session);
52✔
1394

1395
    // If the subscription store exists and switching to PBS, then clear the store
1396
    auto& history = static_cast<sync::ClientReplication&>(*m_db->get_replication());
52✔
1397
    if (!flx_sync_requested) {
52✔
1398
        if (m_flx_subscription_store) {
8✔
1399
            // Empty the subscription store and cancel any pending subscription notification
1400
            // waiters
1401
            auto subscription_store = std::move(m_flx_subscription_store);
8✔
1402
            lock.unlock();
8✔
1403
            auto tr = m_db->start_write();
8✔
1404
            subscription_store->reset(*tr);
8✔
1405
            history.set_write_validator_factory(nullptr);
8✔
1406
            tr->commit();
8✔
1407
        }
8✔
1408
        return;
8✔
1409
    }
8✔
1410

1411
    if (m_flx_subscription_store)
44✔
1412
        return; // Using FLX and subscription store already exists
2✔
1413

1414
    // Going from PBS -> FLX (or one doesn't exist yet), create a new subscription store
1415
    create_subscription_store();
42✔
1416

1417
    std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
42✔
1418

1419
    // If migrated to FLX, create subscriptions in the local realm to cover the existing data.
1420
    // This needs to be done before setting the write validator to avoid NoSubscriptionForWrite errors.
1421
    if (new_subs) {
42✔
1422
        auto active_mut_sub = m_flx_subscription_store->get_active().make_mutable_copy();
16✔
1423
        active_mut_sub.import(std::move(*new_subs));
16✔
1424
        active_mut_sub.set_state(sync::SubscriptionSet::State::Complete);
16✔
1425
        active_mut_sub.commit();
16✔
1426
    }
16✔
1427

1428
    auto tr = m_db->start_write();
42✔
1429
    set_write_validator_factory(weak_sub_mgr);
42✔
1430
    tr->rollback();
42✔
1431
}
42✔
1432

1433
void SyncSession::create_subscription_store()
1434
{
631✔
1435
    REALM_ASSERT(!m_flx_subscription_store);
631✔
1436

1437
    // Create the main subscription store instance when this is first called - this will
1438
    // remain valid afterwards for the life of the SyncSession, but m_flx_subscription_store
1439
    // will be reset when rolling back to PBS after a client FLX migration
1440
    if (!m_subscription_store_base) {
631✔
1441
        m_subscription_store_base = sync::SubscriptionStore::create(m_db);
629✔
1442
    }
629✔
1443

1444
    // m_subscription_store_base is always around for the life of SyncSession, but the
1445
    // m_flx_subscription_store is set when using FLX.
1446
    m_flx_subscription_store = m_subscription_store_base;
631✔
1447
}
631✔
1448

1449
void SyncSession::set_write_validator_factory(std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr)
1450
{
631✔
1451
    auto& history = static_cast<sync::ClientReplication&>(*m_db->get_replication());
631✔
1452
    history.set_write_validator_factory(
631✔
1453
        [weak_sub_mgr](Transaction& tr) -> util::UniqueFunction<sync::SyncReplication::WriteValidator> {
6,513✔
1454
            auto sub_mgr = weak_sub_mgr.lock();
6,513✔
1455
            REALM_ASSERT_RELEASE(sub_mgr);
6,513✔
1456
            auto latest_sub_tables = sub_mgr->get_tables_for_latest(tr);
6,513✔
1457
            return [tables = std::move(latest_sub_tables)](const Table& table) {
6,513✔
1458
                if (table.get_table_type() != Table::Type::TopLevel) {
869✔
1459
                    return;
430✔
1460
                }
430✔
1461
                auto object_class_name = Group::table_name_to_class_name(table.get_name());
439✔
1462
                if (tables.find(object_class_name) == tables.end()) {
439✔
1463
                    throw NoSubscriptionForWrite(
2✔
1464
                        util::format("Cannot write to class %1 when no flexible sync subscription has been created.",
2✔
1465
                                     object_class_name));
2✔
1466
                }
2✔
1467
            };
439✔
1468
        });
6,513✔
1469
}
631✔
1470

1471
// Represents a reference to the SyncSession from outside of the sync subsystem.
1472
// We attempt to keep the SyncSession in an active state as long as it has an external reference.
1473
class SyncSession::ExternalReference {
1474
public:
1475
    ExternalReference(std::shared_ptr<SyncSession> session)
1476
        : m_session(std::move(session))
715✔
1477
    {
1,601✔
1478
    }
1,601✔
1479

1480
    ~ExternalReference()
1481
    {
1,601✔
1482
        m_session->did_drop_external_reference();
1,601✔
1483
    }
1,601✔
1484

1485
private:
1486
    std::shared_ptr<SyncSession> m_session;
1487
};
1488

1489
std::shared_ptr<SyncSession> SyncSession::external_reference()
1490
{
1,837✔
1491
    util::CheckedLockGuard lock(m_external_reference_mutex);
1,837✔
1492

1493
    if (auto external_reference = m_external_reference.lock())
1,837✔
1494
        return std::shared_ptr<SyncSession>(external_reference, this);
236✔
1495

1496
    auto external_reference = std::make_shared<ExternalReference>(shared_from_this());
1,601✔
1497
    m_external_reference = external_reference;
1,601✔
1498
    return std::shared_ptr<SyncSession>(external_reference, this);
1,601✔
1499
}
1,837✔
1500

1501
std::shared_ptr<SyncSession> SyncSession::existing_external_reference()
1502
{
2,646✔
1503
    util::CheckedLockGuard lock(m_external_reference_mutex);
2,646✔
1504

1505
    if (auto external_reference = m_external_reference.lock())
2,646✔
1506
        return std::shared_ptr<SyncSession>(external_reference, this);
1,100✔
1507

1508
    return nullptr;
1,546✔
1509
}
2,646✔
1510

1511
void SyncSession::did_drop_external_reference()
1512
{
1,601✔
1513
    util::CheckedUniqueLock lock1(m_state_mutex);
1,601✔
1514
    {
1,601✔
1515
        util::CheckedLockGuard lock2(m_external_reference_mutex);
1,601✔
1516

1517
        // If the session is being resurrected we should not close the session.
1518
        if (!m_external_reference.expired())
1,601✔
1519
            return;
×
1520
    }
1,601✔
1521

1522
    close(std::move(lock1));
1,601✔
1523
}
1,601✔
1524

1525
uint64_t SyncProgressNotifier::register_callback(std::function<ProgressNotifierCallback> notifier,
1526
                                                 NotifierType direction, bool is_streaming,
1527
                                                 int64_t pending_query_version)
1528
{
90✔
1529
    util::UniqueFunction<void()> invocation;
90✔
1530
    uint64_t token_value = 0;
90✔
1531
    {
90✔
1532
        std::lock_guard<std::mutex> lock(m_mutex);
90✔
1533
        token_value = m_progress_notifier_token++;
90✔
1534
        NotifierPackage package{std::move(notifier), m_local_transaction_version, is_streaming,
90✔
1535
                                direction == NotifierType::download, pending_query_version};
90✔
1536
        if (!m_current_progress) {
90✔
1537
            // Simply register the package, since we have no data yet.
1538
            m_packages.emplace(token_value, std::move(package));
34✔
1539
            return token_value;
34✔
1540
        }
34✔
1541
        bool skip_registration = false;
56✔
1542
        invocation = package.create_invocation(*m_current_progress, skip_registration);
56✔
1543
        if (skip_registration) {
56✔
1544
            token_value = 0;
22✔
1545
        }
22✔
1546
        else {
34✔
1547
            m_packages.emplace(token_value, std::move(package));
34✔
1548
        }
34✔
1549
    }
56✔
1550
    invocation();
×
1551
    return token_value;
56✔
1552
}
90✔
1553

1554
void SyncProgressNotifier::unregister_callback(uint64_t token)
1555
{
16✔
1556
    std::lock_guard<std::mutex> lock(m_mutex);
16✔
1557
    m_packages.erase(token);
16✔
1558
}
16✔
1559

1560
void SyncProgressNotifier::update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded, uint64_t uploadable,
1561
                                  uint64_t snapshot_version, double download_estimate, double upload_estimate,
1562
                                  int64_t query_version)
1563
{
4,341✔
1564
    std::vector<util::UniqueFunction<void()>> invocations;
4,341✔
1565
    {
4,341✔
1566
        std::lock_guard<std::mutex> lock(m_mutex);
4,341✔
1567
        m_current_progress = Progress{uploadable,      downloadable,      uploaded,         downloaded,
4,341✔
1568
                                      upload_estimate, download_estimate, snapshot_version, query_version};
4,341✔
1569

1570
        for (auto it = m_packages.begin(); it != m_packages.end();) {
4,620✔
1571
            bool should_delete = false;
279✔
1572
            invocations.emplace_back(it->second.create_invocation(*m_current_progress, should_delete));
279✔
1573
            it = should_delete ? m_packages.erase(it) : std::next(it);
279✔
1574
        }
279✔
1575
    }
4,341✔
1576
    // Run the notifiers only after we've released the lock.
1577
    for (auto& invocation : invocations)
4,341✔
1578
        invocation();
279✔
1579
}
4,341✔
1580

1581
void SyncProgressNotifier::set_local_version(uint64_t snapshot_version)
1582
{
9,240✔
1583
    std::lock_guard<std::mutex> lock(m_mutex);
9,240✔
1584
    m_local_transaction_version = snapshot_version;
9,240✔
1585
}
9,240✔
1586

1587
util::UniqueFunction<void()>
1588
SyncProgressNotifier::NotifierPackage::create_invocation(Progress const& current_progress, bool& is_expired)
1589
{
335✔
1590
    uint64_t transfered = is_download ? current_progress.downloaded : current_progress.uploaded;
335✔
1591
    uint64_t transferable = is_download ? current_progress.downloadable : current_progress.uploadable;
335✔
1592
    double estimate = is_download ? current_progress.download_estimate : current_progress.upload_estimate;
335✔
1593

1594
    if (!is_streaming) {
335✔
1595
        // If the sync client has not yet processed all of the local
1596
        // transactions then the uploadable data is incorrect and we should
1597
        // not invoke the callback
1598
        if (!is_download && snapshot_version > current_progress.snapshot_version)
169✔
1599
            return [] {};
4✔
1600

1601
        // If this is a non-streaming download progress update and this notifier was
1602
        // created for a later query version (e.g. we're currently downloading
1603
        // subscription set version zero, but subscription set version 1 existed
1604
        // when the notifier was registered), then we want to skip this callback.
1605
        if (is_download && current_progress.query_version < pending_query_version) {
165✔
1606
            return [] {};
8✔
1607
        }
8✔
1608

1609
        // The initial download size we get from the server is the uncompacted
1610
        // size, and so the download may complete before we actually receive
1611
        // that much data. When that happens, transferrable will drop and we
1612
        // need to use the new value instead of the captured one.
1613
        if (!captured_transferable || *captured_transferable > transferable)
157✔
1614
            captured_transferable = transferable;
58✔
1615
        transferable = *captured_transferable;
157✔
1616

1617
        // Since we can adjust the transferrable downwards the estimate for uploads
1618
        // won't be correct since the sync client's view of the estimate is based on
1619
        // the total number of uploadable bytes available rather than the number of
1620
        // bytes this NotifierPackage was waiting to upload.
1621
        if (!is_download) {
157✔
1622
            estimate = transferable > 0 ? std::min(transfered / double(transferable), 1.0) : 0.0;
91✔
1623
        }
91✔
1624
    }
157✔
1625

1626
    // A notifier is expired if at least as many bytes have been transferred
1627
    // as were originally considered transferrable.
1628
    is_expired =
323✔
1629
        !is_streaming && (transfered >= transferable && (!is_download || !pending_query_version || estimate >= 1.0));
323✔
1630
    return [=, notifier = notifier] {
323✔
1631
        notifier(transfered, transferable, estimate);
323✔
1632
    };
323✔
1633
}
335✔
1634

1635
uint64_t SyncSession::ConnectionChangeNotifier::add_callback(std::function<ConnectionStateChangeCallback> callback)
1636
{
6✔
1637
    std::lock_guard<std::mutex> lock(m_callback_mutex);
6✔
1638
    auto token = m_next_token++;
6✔
1639
    m_callbacks.push_back({std::move(callback), token});
6✔
1640
    return token;
6✔
1641
}
6✔
1642

1643
void SyncSession::ConnectionChangeNotifier::remove_callback(uint64_t token)
1644
{
2✔
1645
    Callback old;
2✔
1646
    {
2✔
1647
        std::lock_guard<std::mutex> lock(m_callback_mutex);
2✔
1648
        auto it = std::find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) {
2✔
1649
            return c.token == token;
2✔
1650
        });
2✔
1651
        if (it == end(m_callbacks)) {
2✔
1652
            return;
×
1653
        }
×
1654

1655
        size_t idx = distance(begin(m_callbacks), it);
2✔
1656
        if (m_callback_index != npos) {
2✔
1657
            if (m_callback_index >= idx)
×
1658
                --m_callback_index;
×
1659
        }
×
1660
        --m_callback_count;
2✔
1661

1662
        old = std::move(*it);
2✔
1663
        m_callbacks.erase(it);
2✔
1664
    }
2✔
1665
}
2✔
1666

1667
void SyncSession::ConnectionChangeNotifier::invoke_callbacks(ConnectionState old_state, ConnectionState new_state)
1668
{
5,821✔
1669
    std::unique_lock lock(m_callback_mutex);
5,821✔
1670
    m_callback_count = m_callbacks.size();
5,821✔
1671
    for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) {
5,825✔
1672
        // acquire a local reference to the callback so that removing the
1673
        // callback from within it can't result in a dangling pointer
1674
        auto cb = m_callbacks[m_callback_index].fn;
4✔
1675
        lock.unlock();
4✔
1676
        cb(old_state, new_state);
4✔
1677
        lock.lock();
4✔
1678
    }
4✔
1679
    m_callback_index = npos;
5,821✔
1680
}
5,821✔
1681

1682
util::Future<std::string> SyncSession::send_test_command(std::string body)
1683
{
30✔
1684
    util::CheckedLockGuard lk(m_state_mutex);
30✔
1685
    if (!m_session) {
30✔
1686
        return Status{ErrorCodes::RuntimeError, "Session doesn't exist to send test command on"};
×
1687
    }
×
1688

1689
    return m_session->send_test_command(std::move(body));
30✔
1690
}
30✔
1691

1692
void SyncSession::migrate_schema(util::UniqueFunction<void(Status)>&& callback)
1693
{
28✔
1694
    util::CheckedUniqueLock lock(m_state_mutex);
28✔
1695
    // If the schema migration is already in progress, just wait to complete.
1696
    if (m_schema_migration_in_progress) {
28✔
1697
        add_completion_callback(std::move(callback), ProgressDirection::download);
2✔
1698
        return;
2✔
1699
    }
2✔
1700
    m_schema_migration_in_progress = true;
26✔
1701

1702
    // Perform the migration:
1703
    //  1. Pause the sync session
1704
    //  2. Once the sync client releases the realm file:
1705
    //      a. Delete all tables (private and public)
1706
    //      b. Reset the subscription store
1707
    //      d. Empty the sync history and adjust cursors
1708
    //      e. Reset file ident (the server flags the old ident as in the case of a client reset)
1709
    // 3. Resume the session (the client asks for a new file ident)
1710
    // See `sync_schema_migration::perform_schema_migration` for more details.
1711

1712
    CompletionCallbacks callbacks;
26✔
1713
    std::swap(m_completion_callbacks, callbacks);
26✔
1714
    auto guard = util::make_scope_exit([&]() noexcept {
26✔
1715
        util::CheckedUniqueLock lock(m_state_mutex);
26✔
1716
        if (m_completion_callbacks.empty())
26✔
1717
            std::swap(callbacks, m_completion_callbacks);
26✔
1718
        else
×
1719
            m_completion_callbacks.merge(std::move(callbacks));
×
1720
    });
26✔
1721
    m_state_mutex.unlock(lock);
26✔
1722

1723
    auto future = pause_async();
26✔
1724
    std::move(future).get_async(
26✔
1725
        [callback = std::move(callback), weak_session = weak_from_this()](Status status) mutable {
26✔
1726
            if (!status.is_ok())
26✔
1727
                return callback(status);
×
1728

1729
            auto session = weak_session.lock();
26✔
1730
            if (!session) {
26✔
1731
                status = Status(ErrorCodes::InvalidSession, "Sync session was destroyed during schema migration");
×
1732
                return callback(status);
×
1733
            }
×
1734
            sync_schema_migration::perform_schema_migration(*session->m_db);
26✔
1735
            {
26✔
1736
                util::CheckedUniqueLock lock(session->m_state_mutex);
26✔
1737
                session->m_previous_schema_version.reset();
26✔
1738
                session->m_schema_migration_in_progress = false;
26✔
1739
                session->m_subscription_store_base.reset();
26✔
1740
                session->m_flx_subscription_store.reset();
26✔
1741
            }
26✔
1742
            session->update_subscription_store(true, {});
26✔
1743
            session->wait_for_download_completion(std::move(callback));
26✔
1744
            session->resume();
26✔
1745
        });
26✔
1746
}
26✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc