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

realm / realm-core / 2357

29 May 2024 11:05PM UTC coverage: 90.843% (+0.04%) from 90.801%
2357

push

Evergreen

web-flow
Merge pull request #7609 from realm/tg/session-lifecycle

RCORE-2092 Simplify the SessionWrapper lifecycle a bit

101578 of 179868 branches covered (56.47%)

506 of 544 new or added lines in 14 files covered. (93.01%)

42 existing lines in 13 files now uncovered.

214462 of 236080 relevant lines covered (90.84%)

5704793.94 hits per line

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

91.73
/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
    create_sync_session();
2,010✔
112

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

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

124
void SyncSession::become_dying(util::CheckedUniqueLock lock)
125
{
84✔
126
    REALM_ASSERT(m_state != State::Dying);
84✔
127
    m_state = State::Dying;
84✔
128

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

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

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

152
    do_become_inactive(std::move(lock), status, cancel_subscription_notifications);
1,782✔
153
}
1,782✔
154

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

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

167
    do_become_inactive(std::move(lock), Status::OK(), true);
210✔
168
}
210✔
169

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

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

192
    if (m_session) {
22✔
193
        m_session.reset();
22✔
194
    }
22✔
195

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

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

214
    SyncSession::CompletionCallbacks waits;
1,992✔
215
    std::swap(waits, m_completion_callbacks);
1,992✔
216

217
    m_session = nullptr;
1,992✔
218
    if (m_sync_manager) {
1,992✔
219
        m_sync_manager->unregister_session(m_db->get_path());
1,992✔
220
    }
1,992✔
221

222
    auto subscription_store = m_flx_subscription_store;
1,992✔
223
    m_state_mutex.unlock(lock);
1,992✔
224

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

230
    if (status.is_ok())
1,992✔
231
        status = Status(ErrorCodes::OperationAborted, "Sync session became inactive");
1,875✔
232

233
    if (subscription_store && cancel_subscription_notifications) {
1,992✔
234
        subscription_store->notify_all_state_change_notifications(status);
673✔
235
    }
673✔
236

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

242
void SyncSession::become_waiting_for_access_token()
243
{
20✔
244
    REALM_ASSERT(m_state != State::WaitingForAccessToken);
20✔
245
    m_state = State::WaitingForAccessToken;
20✔
246
}
20✔
247

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

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

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

275
    return false;
40✔
276
}
62✔
277

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

288
    return false;
40✔
289
}
40✔
290

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

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

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

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

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

403
void SyncSession::detach_from_sync_manager()
404
{
2✔
405
    shutdown_and_wait();
2✔
406
    util::CheckedLockGuard lk(m_state_mutex);
2✔
407
    m_sync_manager = nullptr;
2✔
408
}
2✔
409

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

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

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

446
    DBOptions options;
190✔
447
    options.allow_file_format_upgrade = false;
190✔
448
    options.enable_async_writes = false;
190✔
449
    if (!encryption_key.empty())
190✔
450
        options.encryption_key = encryption_key.data();
2✔
451

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

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

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

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

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

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

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

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

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

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

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

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

641
void SyncSession::OnlyForTesting::handle_error(SyncSession& session, sync::SessionErrorInfo&& error)
642
{
16✔
643
    session.handle_error(std::move(error));
16✔
644
}
16✔
645

646
util::Future<void> SyncSession::OnlyForTesting::pause_async(SyncSession& session)
647
{
2✔
648
    return session.pause_async();
2✔
649
}
2✔
650

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

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

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

759
    if (delete_file)
163✔
760
        update_error_and_mark_file_for_deletion(sync_error, *delete_file);
74✔
761

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

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

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

789
    if (log_out_user) {
161✔
790
        if (auto u = user())
×
791
            u->request_log_out();
×
792
    }
×
793

794
    if (auto error_handler = config(&SyncConfig::error_handler)) {
161✔
795
        error_handler(shared_from_this(), std::move(sync_error));
161✔
796
    }
161✔
797
}
161✔
798

799
void SyncSession::cancel_pending_waits(util::CheckedUniqueLock lock, Status error)
800
{
38✔
801
    CompletionCallbacks callbacks;
38✔
802
    std::swap(callbacks, m_completion_callbacks);
38✔
803

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

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

819
void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded,
820
                                         uint64_t uploadable, uint64_t snapshot_version, double download_estimate,
821
                                         double upload_estimate, int64_t query_version)
822
{
4,185✔
823
    m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, snapshot_version, download_estimate,
4,185✔
824
                               upload_estimate, query_version);
4,185✔
825
}
4,185✔
826

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

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

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

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

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

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

882
    return config;
142✔
883
}
146✔
884

885
void SyncSession::create_sync_session()
886
{
2,010✔
887
    if (m_session)
2,010✔
888
        return;
2✔
889

890
    util::CheckedLockGuard config_lock(m_config_mutex);
2,008✔
891

892
    REALM_ASSERT(m_config.sync_config);
2,008✔
893
    SyncConfig& sync_config = *m_config.sync_config;
2,008✔
894
    REALM_ASSERT(sync_config.user);
2,008✔
895

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

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

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

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

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

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

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

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

956
    session_config.progress_handler = [weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable,
2,008✔
957
                                                  uint_fast64_t uploaded, uint_fast64_t uploadable,
2,008✔
958
                                                  uint_fast64_t snapshot_version, double download_estimate,
2,008✔
959
                                                  double upload_estimate, int64_t query_version) {
4,215✔
960
        if (auto self = weak_self.lock()) {
4,215✔
961
            self->handle_progress_update(downloaded, downloadable, uploaded, uploadable, snapshot_version,
4,185✔
962
                                         download_estimate, upload_estimate, query_version);
4,185✔
963
        }
4,185✔
964
    };
4,215✔
965

966
    session_config.connection_state_change_listener = [weak_self](sync::ConnectionState state,
2,008✔
967
                                                                  std::optional<sync::SessionErrorInfo> error) {
4,352✔
968
        using cs = sync::ConnectionState;
4,352✔
969
        ConnectionState new_state = [&] {
4,352✔
970
            switch (state) {
4,352✔
971
                case cs::disconnected:
431✔
972
                    return ConnectionState::Disconnected;
431✔
973
                case cs::connecting:
1,999✔
974
                    return ConnectionState::Connecting;
1,999✔
975
                case cs::connected:
1,922✔
976
                    return ConnectionState::Connected;
1,922✔
977
            }
4,352✔
978
            REALM_UNREACHABLE();
NEW
979
        }();
×
980
        // If the OS SyncSession object is destroyed, we ignore any events from the underlying Session as there is
981
        // nothing useful we can do with them.
982
        if (auto self = weak_self.lock()) {
4,352✔
983
            self->update_connection_state(new_state);
4,318✔
984
            if (error) {
4,318✔
985
                self->handle_error(std::move(*error));
492✔
986
            }
492✔
987
        }
4,318✔
988
    };
4,352✔
989

990
    m_session = m_client.make_session(m_db, m_flx_subscription_store, m_migration_store, std::move(session_config));
2,008✔
991
}
2,008✔
992

993
void SyncSession::update_connection_state(ConnectionState new_state)
994
{
4,318✔
995
    if (new_state == ConnectionState::Connected) {
4,318✔
996
        util::CheckedLockGuard lock(m_config_mutex);
1,904✔
997
        m_server_url_verified = true;
1,904✔
998
    }
1,904✔
999

1000
    ConnectionState old_state;
4,318✔
1001
    {
4,318✔
1002
        util::CheckedLockGuard lock(m_connection_state_mutex);
4,318✔
1003
        old_state = m_connection_state;
4,318✔
1004
        m_connection_state = new_state;
4,318✔
1005
    }
4,318✔
1006

1007
    // Notify any registered connection callbacks of the state transition
1008
    if (old_state != new_state) {
4,318✔
1009
        m_connection_change_notifier.invoke_callbacks(old_state, new_state);
4,249✔
1010
    }
4,249✔
1011
}
4,318✔
1012

1013
void SyncSession::nonsync_transact_notify(sync::version_type version)
1014
{
9,218✔
1015
    m_progress_notifier.set_local_version(version);
9,218✔
1016

1017
    util::CheckedUniqueLock lock(m_state_mutex);
9,218✔
1018
    switch (m_state) {
9,218✔
1019
        case State::Active:
8,854✔
1020
        case State::WaitingForAccessToken:
8,856✔
1021
            if (m_session) {
8,856✔
1022
                m_session->nonsync_transact_notify(version);
8,854✔
1023
            }
8,854✔
1024
            break;
8,856✔
1025
        case State::Dying:
✔
1026
        case State::Inactive:
19✔
1027
        case State::Paused:
362✔
1028
            break;
362✔
1029
    }
9,218✔
1030
}
9,218✔
1031

1032
void SyncSession::revive_if_needed()
1033
{
2,367✔
1034
    util::CheckedUniqueLock lock(m_state_mutex);
2,367✔
1035
    switch (m_state) {
2,367✔
1036
        case State::Active:
573✔
1037
        case State::WaitingForAccessToken:
573✔
1038
        case State::Paused:
579✔
1039
            return;
579✔
1040
        case State::Dying:
2✔
1041
        case State::Inactive:
1,788✔
1042
            do_revive(std::move(lock));
1,788✔
1043
            break;
1,788✔
1044
    }
2,367✔
1045
}
2,367✔
1046

1047
void SyncSession::handle_reconnect()
1048
{
4✔
1049
    util::CheckedUniqueLock lock(m_state_mutex);
4✔
1050
    switch (m_state) {
4✔
1051
        case State::Active:
4✔
1052
            m_session->cancel_reconnect_delay();
4✔
1053
            break;
4✔
1054
        case State::Dying:
✔
1055
        case State::Inactive:
✔
1056
        case State::WaitingForAccessToken:
✔
1057
        case State::Paused:
✔
1058
            break;
×
1059
    }
4✔
1060
}
4✔
1061

1062
void SyncSession::force_close()
1063
{
306✔
1064
    util::CheckedUniqueLock lock(m_state_mutex);
306✔
1065
    switch (m_state) {
306✔
1066
        case State::Active:
239✔
1067
        case State::Dying:
289✔
1068
        case State::WaitingForAccessToken:
293✔
1069
            become_inactive(std::move(lock));
293✔
1070
            break;
293✔
1071
        case State::Inactive:
11✔
1072
        case State::Paused:
13✔
1073
            break;
13✔
1074
    }
306✔
1075
}
306✔
1076

1077
void SyncSession::pause()
1078
{
214✔
1079
    util::CheckedUniqueLock lock(m_state_mutex);
214✔
1080
    switch (m_state) {
214✔
1081
        case State::Active:
210✔
1082
        case State::Dying:
210✔
1083
        case State::WaitingForAccessToken:
210✔
1084
        case State::Inactive:
212✔
1085
            become_paused(std::move(lock));
212✔
1086
            break;
212✔
1087
        case State::Paused:
2✔
1088
            break;
2✔
1089
    }
214✔
1090
}
214✔
1091

1092
void SyncSession::resume()
1093
{
194✔
1094
    util::CheckedUniqueLock lock(m_state_mutex);
194✔
1095
    switch (m_state) {
194✔
1096
        case State::Active:
✔
1097
        case State::WaitingForAccessToken:
✔
1098
            return;
×
1099
        case State::Paused:
194✔
1100
        case State::Dying:
194✔
1101
        case State::Inactive:
194✔
1102
            do_revive(std::move(lock));
194✔
1103
            break;
194✔
1104
    }
194✔
1105
}
194✔
1106

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

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

1130
void SyncSession::close()
1131
{
100✔
1132
    util::CheckedUniqueLock lock(m_state_mutex);
100✔
1133
    close(std::move(lock));
100✔
1134
}
100✔
1135

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

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

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

1213
void SyncSession::initiate_access_token_refresh()
1214
{
20✔
1215
    if (auto session_user = user()) {
20✔
1216
        session_user->request_access_token(handle_refresh(shared_from_this(), false));
20✔
1217
    }
20✔
1218
}
20✔
1219

1220
void SyncSession::add_completion_callback(util::UniqueFunction<void(Status)> callback, ProgressDirection direction)
1221
{
2,623✔
1222
    bool is_download = (direction == ProgressDirection::download);
2,623✔
1223

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

1233
    auto waiter = is_download ? &sync::Session::async_wait_for_download_completion
2,306✔
1234
                              : &sync::Session::async_wait_for_upload_completion;
2,306✔
1235

1236
    (m_session.get()->*waiter)([weak_self = weak_from_this(), id = m_completion_request_counter](Status status) {
2,306✔
1237
        auto self = weak_self.lock();
2,300✔
1238
        if (!self)
2,300✔
1239
            return;
65✔
1240
        util::CheckedUniqueLock lock(self->m_state_mutex);
2,235✔
1241
        auto callback_node = self->m_completion_callbacks.extract(id);
2,235✔
1242
        lock.unlock();
2,235✔
1243
        if (callback_node) {
2,235✔
1244
            callback_node.mapped().second(std::move(status));
2,032✔
1245
        }
2,032✔
1246
    });
2,235✔
1247
}
2,306✔
1248

1249
void SyncSession::wait_for_upload_completion(util::UniqueFunction<void(Status)>&& callback)
1250
{
946✔
1251
    util::CheckedUniqueLock lock(m_state_mutex);
946✔
1252
    add_completion_callback(std::move(callback), ProgressDirection::upload);
946✔
1253
}
946✔
1254

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

1261
uint64_t SyncSession::register_progress_notifier(std::function<ProgressNotifierCallback>&& notifier,
1262
                                                 ProgressDirection direction, bool is_streaming)
1263
{
36✔
1264
    int64_t pending_query_version = 0;
36✔
1265
    if (auto sub_store = get_flx_subscription_store()) {
36✔
1266
        pending_query_version = sub_store->get_version_info().latest;
16✔
1267
    }
16✔
1268
    return m_progress_notifier.register_callback(std::move(notifier), direction, is_streaming, pending_query_version);
36✔
1269
}
36✔
1270

1271
void SyncSession::unregister_progress_notifier(uint64_t token)
1272
{
12✔
1273
    m_progress_notifier.unregister_callback(token);
12✔
1274
}
12✔
1275

1276
uint64_t SyncSession::register_connection_change_callback(std::function<ConnectionStateChangeCallback>&& callback)
1277
{
6✔
1278
    return m_connection_change_notifier.add_callback(std::move(callback));
6✔
1279
}
6✔
1280

1281
void SyncSession::unregister_connection_change_callback(uint64_t token)
1282
{
2✔
1283
    m_connection_change_notifier.remove_callback(token);
2✔
1284
}
2✔
1285

1286
SyncSession::~SyncSession() {}
1,594✔
1287

1288
SyncSession::State SyncSession::state() const
1289
{
167,554✔
1290
    util::CheckedUniqueLock lock(m_state_mutex);
167,554✔
1291
    return m_state;
167,554✔
1292
}
167,554✔
1293

1294
SyncSession::ConnectionState SyncSession::connection_state() const
1295
{
6,165✔
1296
    util::CheckedUniqueLock lock(m_connection_state_mutex);
6,165✔
1297
    return m_connection_state;
6,165✔
1298
}
6,165✔
1299

1300
std::string const& SyncSession::path() const
1301
{
240✔
1302
    return m_db->get_path();
240✔
1303
}
240✔
1304

1305
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_flx_subscription_store()
1306
{
4,089,499✔
1307
    util::CheckedLockGuard lock(m_state_mutex);
4,089,499✔
1308
    return m_flx_subscription_store;
4,089,499✔
1309
}
4,089,499✔
1310

1311
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_subscription_store_base()
1312
{
2✔
1313
    util::CheckedLockGuard lock(m_state_mutex);
2✔
1314
    return m_subscription_store_base;
2✔
1315
}
2✔
1316

1317
sync::SaltedFileIdent SyncSession::get_file_ident() const
1318
{
164✔
1319
    auto repl = m_db->get_replication();
164✔
1320
    REALM_ASSERT(repl);
164✔
1321
    REALM_ASSERT(dynamic_cast<sync::ClientReplication*>(repl));
164✔
1322

1323
    sync::SaltedFileIdent ret;
164✔
1324
    sync::version_type unused_version;
164✔
1325
    sync::SyncProgress unused_progress;
164✔
1326
    static_cast<sync::ClientReplication*>(repl)->get_history().get_status(unused_version, ret, unused_progress);
164✔
1327
    return ret;
164✔
1328
}
164✔
1329

1330
std::string SyncSession::get_appservices_connection_id() const
1331
{
20✔
1332
    util::CheckedLockGuard lk(m_state_mutex);
20✔
1333
    if (!m_session) {
20✔
1334
        return {};
×
1335
    }
×
1336
    return m_session->get_appservices_connection_id();
20✔
1337
}
20✔
1338

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

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

1364
void SyncSession::apply_sync_config_after_migration_or_rollback()
1365
{
26✔
1366
    // Migration state changed - Update the configuration to
1367
    // match the new sync mode.
1368
    util::CheckedLockGuard cfg_lock(m_config_mutex);
26✔
1369
    if (!m_migrated_sync_config)
26✔
1370
        return;
2✔
1371

1372
    m_config.sync_config = m_migrated_sync_config;
24✔
1373
    m_migrated_sync_config.reset();
24✔
1374
}
24✔
1375

1376
void SyncSession::save_sync_config_after_migration_or_rollback()
1377
{
28✔
1378
    util::CheckedLockGuard cfg_lock(m_config_mutex);
28✔
1379
    m_migrated_sync_config = m_migration_store->convert_sync_config(m_original_sync_config);
28✔
1380
}
28✔
1381

1382
void SyncSession::update_subscription_store(bool flx_sync_requested, std::optional<sync::SubscriptionSet> new_subs)
1383
{
52✔
1384
    util::CheckedUniqueLock lock(m_state_mutex);
52✔
1385

1386
    // The session should be closed before updating the FLX subscription store
1387
    REALM_ASSERT(!m_session);
52✔
1388

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

1405
    if (m_flx_subscription_store)
44✔
1406
        return; // Using FLX and subscription store already exists
2✔
1407

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

1411
    std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
42✔
1412

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

1422
    auto tr = m_db->start_write();
42✔
1423
    set_write_validator_factory(weak_sub_mgr);
42✔
1424
    tr->rollback();
42✔
1425
}
42✔
1426

1427
void SyncSession::create_subscription_store()
1428
{
631✔
1429
    REALM_ASSERT(!m_flx_subscription_store);
631✔
1430

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

1438
    // m_subscription_store_base is always around for the life of SyncSession, but the
1439
    // m_flx_subscription_store is set when using FLX.
1440
    m_flx_subscription_store = m_subscription_store_base;
631✔
1441
}
631✔
1442

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

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

1474
    ~ExternalReference()
1475
    {
1,601✔
1476
        m_session->did_drop_external_reference();
1,601✔
1477
    }
1,601✔
1478

1479
private:
1480
    std::shared_ptr<SyncSession> m_session;
1481
};
1482

1483
std::shared_ptr<SyncSession> SyncSession::external_reference()
1484
{
1,837✔
1485
    util::CheckedLockGuard lock(m_external_reference_mutex);
1,837✔
1486

1487
    if (auto external_reference = m_external_reference.lock())
1,837✔
1488
        return std::shared_ptr<SyncSession>(external_reference, this);
236✔
1489

1490
    auto external_reference = std::make_shared<ExternalReference>(shared_from_this());
1,601✔
1491
    m_external_reference = external_reference;
1,601✔
1492
    return std::shared_ptr<SyncSession>(external_reference, this);
1,601✔
1493
}
1,837✔
1494

1495
std::shared_ptr<SyncSession> SyncSession::existing_external_reference()
1496
{
2,649✔
1497
    util::CheckedLockGuard lock(m_external_reference_mutex);
2,649✔
1498

1499
    if (auto external_reference = m_external_reference.lock())
2,649✔
1500
        return std::shared_ptr<SyncSession>(external_reference, this);
1,100✔
1501

1502
    return nullptr;
1,549✔
1503
}
2,649✔
1504

1505
void SyncSession::did_drop_external_reference()
1506
{
1,601✔
1507
    util::CheckedUniqueLock lock1(m_state_mutex);
1,601✔
1508
    {
1,601✔
1509
        util::CheckedLockGuard lock2(m_external_reference_mutex);
1,601✔
1510

1511
        // If the session is being resurrected we should not close the session.
1512
        if (!m_external_reference.expired())
1,601✔
1513
            return;
×
1514
    }
1,601✔
1515

1516
    close(std::move(lock1));
1,601✔
1517
}
1,601✔
1518

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

1548
void SyncProgressNotifier::unregister_callback(uint64_t token)
1549
{
16✔
1550
    std::lock_guard<std::mutex> lock(m_mutex);
16✔
1551
    m_packages.erase(token);
16✔
1552
}
16✔
1553

1554
void SyncProgressNotifier::update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded, uint64_t uploadable,
1555
                                  uint64_t snapshot_version, double download_estimate, double upload_estimate,
1556
                                  int64_t query_version)
1557
{
4,347✔
1558
    std::vector<util::UniqueFunction<void()>> invocations;
4,347✔
1559
    {
4,347✔
1560
        std::lock_guard<std::mutex> lock(m_mutex);
4,347✔
1561
        m_current_progress = Progress{uploadable,      downloadable,      uploaded,         downloaded,
4,347✔
1562
                                      upload_estimate, download_estimate, snapshot_version, query_version};
4,347✔
1563

1564
        for (auto it = m_packages.begin(); it != m_packages.end();) {
4,625✔
1565
            bool should_delete = false;
278✔
1566
            invocations.emplace_back(it->second.create_invocation(*m_current_progress, should_delete));
278✔
1567
            it = should_delete ? m_packages.erase(it) : std::next(it);
278✔
1568
        }
278✔
1569
    }
4,347✔
1570
    // Run the notifiers only after we've released the lock.
1571
    for (auto& invocation : invocations)
4,347✔
1572
        invocation();
278✔
1573
}
4,347✔
1574

1575
void SyncProgressNotifier::set_local_version(uint64_t snapshot_version)
1576
{
9,226✔
1577
    std::lock_guard<std::mutex> lock(m_mutex);
9,226✔
1578
    m_local_transaction_version = snapshot_version;
9,226✔
1579
}
9,226✔
1580

1581
util::UniqueFunction<void()>
1582
SyncProgressNotifier::NotifierPackage::create_invocation(Progress const& current_progress, bool& is_expired)
1583
{
334✔
1584
    uint64_t transfered = is_download ? current_progress.downloaded : current_progress.uploaded;
334✔
1585
    uint64_t transferable = is_download ? current_progress.downloadable : current_progress.uploadable;
334✔
1586
    double estimate = is_download ? current_progress.download_estimate : current_progress.upload_estimate;
334✔
1587

1588
    if (!is_streaming) {
334✔
1589
        // If the sync client has not yet processed all of the local
1590
        // transactions then the uploadable data is incorrect and we should
1591
        // not invoke the callback
1592
        if (!is_download && snapshot_version > current_progress.snapshot_version)
168✔
1593
            return [] {};
3✔
1594

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

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

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

1620
    // A notifier is expired if at least as many bytes have been transferred
1621
    // as were originally considered transferrable.
1622
    is_expired =
323✔
1623
        !is_streaming && (transfered >= transferable && (!is_download || !pending_query_version || estimate >= 1.0));
323✔
1624
    return [=, notifier = notifier] {
323✔
1625
        notifier(transfered, transferable, estimate);
323✔
1626
    };
323✔
1627
}
334✔
1628

1629
uint64_t SyncSession::ConnectionChangeNotifier::add_callback(std::function<ConnectionStateChangeCallback> callback)
1630
{
6✔
1631
    std::lock_guard<std::mutex> lock(m_callback_mutex);
6✔
1632
    auto token = m_next_token++;
6✔
1633
    m_callbacks.push_back({std::move(callback), token});
6✔
1634
    return token;
6✔
1635
}
6✔
1636

1637
void SyncSession::ConnectionChangeNotifier::remove_callback(uint64_t token)
1638
{
2✔
1639
    Callback old;
2✔
1640
    {
2✔
1641
        std::lock_guard<std::mutex> lock(m_callback_mutex);
2✔
1642
        auto it = std::find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) {
2✔
1643
            return c.token == token;
2✔
1644
        });
2✔
1645
        if (it == end(m_callbacks)) {
2✔
1646
            return;
×
1647
        }
×
1648

1649
        size_t idx = distance(begin(m_callbacks), it);
2✔
1650
        if (m_callback_index != npos) {
2✔
1651
            if (m_callback_index >= idx)
×
1652
                --m_callback_index;
×
1653
        }
×
1654
        --m_callback_count;
2✔
1655

1656
        old = std::move(*it);
2✔
1657
        m_callbacks.erase(it);
2✔
1658
    }
2✔
1659
}
2✔
1660

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

1676
util::Future<std::string> SyncSession::send_test_command(std::string body)
1677
{
30✔
1678
    util::CheckedLockGuard lk(m_state_mutex);
30✔
1679
    if (!m_session) {
30✔
1680
        return Status{ErrorCodes::RuntimeError, "Session doesn't exist to send test command on"};
×
1681
    }
×
1682

1683
    return m_session->send_test_command(std::move(body));
30✔
1684
}
30✔
1685

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

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

1706
    CompletionCallbacks callbacks;
26✔
1707
    std::swap(m_completion_callbacks, callbacks);
26✔
1708
    auto guard = util::make_scope_exit([&]() noexcept {
26✔
1709
        util::CheckedUniqueLock lock(m_state_mutex);
26✔
1710
        if (m_completion_callbacks.empty())
26✔
1711
            std::swap(callbacks, m_completion_callbacks);
26✔
1712
        else
×
1713
            m_completion_callbacks.merge(std::move(callbacks));
×
1714
    });
26✔
1715
    m_state_mutex.unlock(lock);
26✔
1716

1717
    auto future = pause_async();
26✔
1718
    std::move(future).get_async(
26✔
1719
        [callback = std::move(callback), weak_session = weak_from_this()](Status status) mutable {
26✔
1720
            if (!status.is_ok())
26✔
1721
                return callback(status);
×
1722

1723
            auto session = weak_session.lock();
26✔
1724
            if (!session) {
26✔
1725
                status = Status(ErrorCodes::InvalidSession, "Sync session was destroyed during schema migration");
×
1726
                return callback(status);
×
1727
            }
×
1728
            sync_schema_migration::perform_schema_migration(*session->m_db);
26✔
1729
            {
26✔
1730
                util::CheckedUniqueLock lock(session->m_state_mutex);
26✔
1731
                session->m_previous_schema_version.reset();
26✔
1732
                session->m_schema_migration_in_progress = false;
26✔
1733
                session->m_subscription_store_base.reset();
26✔
1734
                session->m_flx_subscription_store.reset();
26✔
1735
            }
26✔
1736
            session->update_subscription_store(true, {});
26✔
1737
            session->wait_for_download_completion(std::move(callback));
26✔
1738
            session->resume();
26✔
1739
        });
26✔
1740
}
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

© 2025 Coveralls, Inc