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

realm / realm-core / 2370

01 Jun 2024 12:06AM UTC coverage: 90.826% (-0.02%) from 90.849%
2370

push

Evergreen

web-flow
New changelog section to prepare for vNext (#7765)

Co-authored-by: ironage <2826060+ironage@users.noreply.github.com>

101700 of 180086 branches covered (56.47%)

214578 of 236251 relevant lines covered (90.83%)

5877101.98 hits per line

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

91.75
/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,011✔
89
    REALM_ASSERT(m_state != State::Active);
2,011✔
90
    m_state = State::Active;
2,011✔
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,011✔
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,011✔
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,011✔
117
    std::swap(m_completion_callbacks, callbacks_to_register);
2,011✔
118

119
    for (auto& [id, callback_tuple] : callbacks_to_register) {
2,011✔
120
        add_completion_callback(std::move(callback_tuple.second), callback_tuple.first);
475✔
121
    }
475✔
122
}
2,011✔
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,783✔
149
    REALM_ASSERT(m_state != State::Inactive);
1,783✔
150
    m_state = State::Inactive;
1,783✔
151

152
    do_become_inactive(std::move(lock), status, cancel_subscription_notifications);
1,783✔
153
}
1,783✔
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,993✔
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,993✔
210
    auto old_state = m_connection_state;
1,993✔
211
    auto new_state = m_connection_state = SyncSession::ConnectionState::Disconnected;
1,993✔
212
    connection_state_lock.unlock();
1,993✔
213

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

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

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

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

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

233
    if (subscription_store && cancel_subscription_notifications) {
1,993✔
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,993✔
239
        callback.second(status);
82✔
240
}
1,993✔
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,601✔
375
    REALM_ASSERT(m_config.sync_config);
1,601✔
376
    // we don't want the following configs enabled during a client reset
377
    m_config.scheduler = nullptr;
1,601✔
378
    m_config.audit_config = nullptr;
1,601✔
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,601✔
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,601✔
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,601✔
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,601✔
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(const sync::SessionErrorInfo& error_info)
426
{
192✔
427
    // first check that recovery will not be prevented
428
    if (error_info.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, {ErrorCodes::RuntimeError,
2✔
433
                          "A client reset is required but the server does not permit recovery for this client"});
2✔
434
            return;
2✔
435
        }
2✔
436
    }
4✔
437

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

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

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

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

474
    util::CheckedLockGuard state_lock(m_state_mutex);
182✔
475
    if (m_state != State::Active) {
182✔
476
        return;
×
477
    }
×
478

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

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

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

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

520
                // fresh_sync_session is using a new realm file that doesn't have the migration_store info
521
                // so the query string from the local migration store will need to be provided
522
                auto query_string = self->m_migration_store->get_query_string();
18✔
523
                REALM_ASSERT(query_string);
18✔
524
                // Create subscriptions in the fresh realm based on the schema instructions received in the bootstrap
525
                // message.
526
                fresh_sync_session->m_migration_store->create_subscriptions(*fresh_sub_store, *query_string);
18✔
527
                return fresh_sub_store->get_latest()
18✔
528
                    .get_state_change_notification(SubscriptionState::Complete)
18✔
529
                    .then([fresh_sub_store](SubscriptionState) {
18✔
530
                        return fresh_sub_store->get_latest();
18✔
531
                    });
18✔
532
            })
18✔
533
            .get_async([=](StatusWith<sync::SubscriptionSet>&& subs) {
72✔
534
                // Keep the sync session alive while it's downloading, but then close
535
                // it immediately
536
                fresh_sync_session->force_close();
72✔
537
                if (subs.is_ok()) {
72✔
538
                    self->handle_fresh_realm_downloaded(db, std::move(error_info), std::move(subs.get_value()));
70✔
539
                }
70✔
540
                else {
2✔
541
                    self->handle_fresh_realm_downloaded(nullptr, std::move(subs.get_status()));
2✔
542
                }
2✔
543
            });
72✔
544
    }
72✔
545
    else { // pbs
110✔
546
        fresh_sync_session->wait_for_download_completion([=, weak_self = weak_from_this()](Status status) {
110✔
547
            // Keep the sync session alive while it's downloading, but then close
548
            // it immediately
549
            fresh_sync_session->force_close();
110✔
550
            if (auto strong_self = weak_self.lock()) {
110✔
551
                if (status.is_ok()) {
110✔
552
                    strong_self->handle_fresh_realm_downloaded(db, std::move(error_info));
104✔
553
                }
104✔
554
                else {
6✔
555
                    strong_self->handle_fresh_realm_downloaded(nullptr, std::move(status));
6✔
556
                }
6✔
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, StatusWith<sync::SessionErrorInfo> error_info,
564
                                                std::optional<sync::SubscriptionSet> new_subs)
565
{
192✔
566
    util::CheckedUniqueLock lock(m_state_mutex);
192✔
567
    if (m_state != State::Active) {
192✔
568
        return;
×
569
    }
×
570
    // The download can fail for many reasons. For example:
571
    // - unable to write the fresh copy to the file system
572
    // - during download of the fresh copy, the fresh copy itself is reset
573
    // - in FLX mode there was a problem fulfilling the previously active subscription
574
    if (!error_info.is_ok()) {
192✔
575
        if (error_info.get_status() == ErrorCodes::OperationAborted) {
18✔
576
            return;
6✔
577
        }
6✔
578
        lock.unlock();
12✔
579

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

588
    // Performing a client reset requires tearing down our current
589
    // sync session and creating a new one with the relevant client reset config. This
590
    // will result in session completion handlers firing
591
    // when the old session is torn down, which we don't want as this
592
    // is supposed to be transparent to the user.
593
    //
594
    // To avoid this, we need to move the completion handlers aside temporarily so
595
    // that moving to the inactive state doesn't clear them - they will be
596
    // re-registered when the session becomes active again.
597
    {
174✔
598
        m_client_reset_fresh_copy = db;
174✔
599
        CompletionCallbacks callbacks;
174✔
600
        // Save the client reset error for when the original sync session is revived
601
        REALM_ASSERT(error_info.is_ok()); // required if we get here
174✔
602
        m_client_reset_error = std::move(error_info.get_value());
174✔
603

604
        std::swap(m_completion_callbacks, callbacks);
174✔
605
        // always swap back, even if advance_state throws
606
        auto guard = util::make_scope_exit([&]() noexcept {
174✔
607
            util::CheckedUniqueLock lock(m_state_mutex);
174✔
608
            if (m_completion_callbacks.empty())
174✔
609
                std::swap(callbacks, m_completion_callbacks);
174✔
610
            else
×
611
                m_completion_callbacks.merge(std::move(callbacks));
×
612
        });
174✔
613
        // Do not cancel the notifications on subscriptions.
614
        bool cancel_subscription_notifications = false;
174✔
615
        bool is_migration =
174✔
616
            m_client_reset_error->server_requests_action == sync::ProtocolErrorInfo::Action::MigrateToFLX ||
174✔
617
            m_client_reset_error->server_requests_action == sync::ProtocolErrorInfo::Action::RevertToPBS;
174✔
618
        become_inactive(std::move(lock), Status::OK(), cancel_subscription_notifications); // unlocks the lock
174✔
619

620
        // Once the session is inactive, update sync config and subscription store after migration.
621
        if (is_migration) {
174✔
622
            apply_sync_config_after_migration_or_rollback();
26✔
623
            auto flx_sync_requested = config(&SyncConfig::flx_sync_requested);
26✔
624
            update_subscription_store(flx_sync_requested, std::move(new_subs));
26✔
625
        }
26✔
626
    }
174✔
627
    revive_if_needed();
174✔
628
}
174✔
629

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

648
void SyncSession::OnlyForTesting::handle_error(SyncSession& session, sync::SessionErrorInfo&& error)
649
{
16✔
650
    session.handle_error(std::move(error));
16✔
651
}
16✔
652

653
util::Future<void> SyncSession::OnlyForTesting::pause_async(SyncSession& session)
654
{
2✔
655
    return session.pause_async();
2✔
656
}
2✔
657

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

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

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

766
    if (delete_file)
163✔
767
        update_error_and_mark_file_for_deletion(sync_error, *delete_file);
74✔
768

769
    if (m_state == State::Dying && error.is_fatal) {
163✔
770
        become_inactive(std::move(lock), error.status);
2✔
771
        return;
2✔
772
    }
2✔
773

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

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

796
    if (log_out_user) {
161✔
797
        if (auto u = user())
×
798
            u->request_log_out();
×
799
    }
×
800

801
    if (auto error_handler = config(&SyncConfig::error_handler)) {
161✔
802
        error_handler(shared_from_this(), std::move(sync_error));
161✔
803
    }
161✔
804
}
161✔
805

806
void SyncSession::cancel_pending_waits(util::CheckedUniqueLock lock, Status error)
807
{
38✔
808
    CompletionCallbacks callbacks;
38✔
809
    std::swap(callbacks, m_completion_callbacks);
38✔
810

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

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

826
void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded,
827
                                         uint64_t uploadable, uint64_t snapshot_version, double download_estimate,
828
                                         double upload_estimate, int64_t query_version)
829
{
4,184✔
830
    m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, snapshot_version, download_estimate,
4,184✔
831
                               upload_estimate, query_version);
4,184✔
832
}
4,184✔
833

834

835
static sync::Session::Config::ClientReset
836
make_client_reset_config(const RealmConfig& base_config, const std::shared_ptr<SyncConfig>& sync_config,
837
                         DBRef&& fresh_copy, sync::SessionErrorInfo&& error_info, bool schema_migration_detected)
838
{
174✔
839
    REALM_ASSERT(sync_config->client_resync_mode != ClientResyncMode::Manual);
174✔
840

841
    sync::Session::Config::ClientReset config{sync_config->client_resync_mode, std::move(fresh_copy),
174✔
842
                                              std::move(error_info.status), error_info.server_requests_action};
174✔
843

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

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

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

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

887
    return config;
142✔
888
}
146✔
889

890
void SyncSession::create_sync_session()
891
{
2,011✔
892
    if (m_session)
2,011✔
893
        return;
2✔
894

895
    util::CheckedLockGuard config_lock(m_config_mutex);
2,009✔
896

897
    REALM_ASSERT(m_config.sync_config);
2,009✔
898
    SyncConfig& sync_config = *m_config.sync_config;
2,009✔
899
    REALM_ASSERT(sync_config.user);
2,009✔
900

901
    std::weak_ptr<SyncSession> weak_self = weak_from_this();
2,009✔
902

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

917
    if (sync_config.on_sync_client_event_hook) {
2,009✔
918
        session_config.on_sync_client_event_hook = [hook = sync_config.on_sync_client_event_hook,
108✔
919
                                                    weak_self](const SyncClientHookData& data) {
1,065✔
920
            return hook(weak_self, data);
1,065✔
921
        };
1,065✔
922
    }
108✔
923

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

932
        if (!m_client.decompose_server_url(sync_route, session_config.protocol_envelope,
2,009✔
933
                                           session_config.server_address, session_config.server_port,
2,009✔
934
                                           session_config.service_identifier)) {
2,009✔
935
            throw sync::BadServerUrl(sync_route);
×
936
        }
×
937
        session_config.server_verified = verified;
2,009✔
938

939
        m_server_url = sync_route;
2,009✔
940
        m_server_url_verified = verified;
2,009✔
941
    }
2,009✔
942

943
    if (sync_config.authorization_header_name) {
2,009✔
944
        session_config.authorization_header_name = *sync_config.authorization_header_name;
×
945
    }
×
946
    session_config.custom_http_headers = sync_config.custom_http_headers;
2,009✔
947

948
    if (m_client_reset_error) {
2,009✔
949
        auto client_reset_error = std::exchange(m_client_reset_error, std::nullopt);
174✔
950
        if (client_reset_error->server_requests_action != sync::ProtocolErrorInfo::Action::NoAction) {
174✔
951
            // Use the original sync config, not the updated one from the migration store
952
            session_config.client_reset_config =
174✔
953
                make_client_reset_config(m_config, m_original_sync_config, std::move(m_client_reset_fresh_copy),
174✔
954
                                         std::move(*client_reset_error), m_previous_schema_version.has_value());
174✔
955
            session_config.schema_version = m_previous_schema_version.value_or(m_config.schema_version);
174✔
956
        }
174✔
957
    }
174✔
958

959
    session_config.progress_handler = [weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable,
2,009✔
960
                                                  uint_fast64_t uploaded, uint_fast64_t uploadable,
2,009✔
961
                                                  uint_fast64_t snapshot_version, double download_estimate,
2,009✔
962
                                                  double upload_estimate, int64_t query_version) {
4,224✔
963
        if (auto self = weak_self.lock()) {
4,224✔
964
            self->handle_progress_update(downloaded, downloadable, uploaded, uploadable, snapshot_version,
4,184✔
965
                                         download_estimate, upload_estimate, query_version);
4,184✔
966
        }
4,184✔
967
    };
4,224✔
968

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

993
    m_session = m_client.make_session(m_db, m_flx_subscription_store, m_migration_store, std::move(session_config));
2,009✔
994
}
2,009✔
995

996
void SyncSession::update_connection_state(ConnectionState new_state)
997
{
4,328✔
998
    if (new_state == ConnectionState::Connected) {
4,328✔
999
        util::CheckedLockGuard lock(m_config_mutex);
1,910✔
1000
        m_server_url_verified = true;
1,910✔
1001
    }
1,910✔
1002

1003
    ConnectionState old_state;
4,328✔
1004
    {
4,328✔
1005
        util::CheckedLockGuard lock(m_connection_state_mutex);
4,328✔
1006
        old_state = m_connection_state;
4,328✔
1007
        m_connection_state = new_state;
4,328✔
1008
    }
4,328✔
1009

1010
    // Notify any registered connection callbacks of the state transition
1011
    if (old_state != new_state) {
4,328✔
1012
        m_connection_change_notifier.invoke_callbacks(old_state, new_state);
4,259✔
1013
    }
4,259✔
1014
}
4,328✔
1015

1016
void SyncSession::nonsync_transact_notify(sync::version_type version)
1017
{
9,230✔
1018
    m_progress_notifier.set_local_version(version);
9,230✔
1019

1020
    util::CheckedUniqueLock lock(m_state_mutex);
9,230✔
1021
    switch (m_state) {
9,230✔
1022
        case State::Active:
8,859✔
1023
        case State::WaitingForAccessToken:
8,861✔
1024
            if (m_session) {
8,861✔
1025
                m_session->nonsync_transact_notify(version);
8,859✔
1026
            }
8,859✔
1027
            break;
8,861✔
1028
        case State::Dying:
✔
1029
        case State::Inactive:
21✔
1030
        case State::Paused:
369✔
1031
            break;
369✔
1032
    }
9,230✔
1033
}
9,230✔
1034

1035
void SyncSession::revive_if_needed()
1036
{
2,367✔
1037
    util::CheckedUniqueLock lock(m_state_mutex);
2,367✔
1038
    switch (m_state) {
2,367✔
1039
        case State::Active:
572✔
1040
        case State::WaitingForAccessToken:
572✔
1041
        case State::Paused:
578✔
1042
            return;
578✔
1043
        case State::Dying:
2✔
1044
        case State::Inactive:
1,789✔
1045
            do_revive(std::move(lock));
1,789✔
1046
            break;
1,789✔
1047
    }
2,367✔
1048
}
2,367✔
1049

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

1065
void SyncSession::force_close()
1066
{
309✔
1067
    util::CheckedUniqueLock lock(m_state_mutex);
309✔
1068
    switch (m_state) {
309✔
1069
        case State::Active:
239✔
1070
        case State::Dying:
289✔
1071
        case State::WaitingForAccessToken:
293✔
1072
            become_inactive(std::move(lock));
293✔
1073
            break;
293✔
1074
        case State::Inactive:
14✔
1075
        case State::Paused:
16✔
1076
            break;
16✔
1077
    }
309✔
1078
}
309✔
1079

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

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

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

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

1133
void SyncSession::close()
1134
{
100✔
1135
    util::CheckedUniqueLock lock(m_state_mutex);
100✔
1136
    close(std::move(lock));
100✔
1137
}
100✔
1138

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

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

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

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

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

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

1236
    auto waiter = is_download ? &sync::Session::async_wait_for_download_completion
2,306✔
1237
                              : &sync::Session::async_wait_for_upload_completion;
2,306✔
1238

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

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

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

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

1274
void SyncSession::unregister_progress_notifier(uint64_t token)
1275
{
12✔
1276
    m_progress_notifier.unregister_callback(token);
12✔
1277
}
12✔
1278

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

1284
void SyncSession::unregister_connection_change_callback(uint64_t token)
1285
{
2✔
1286
    m_connection_change_notifier.remove_callback(token);
2✔
1287
}
2✔
1288

1289
SyncSession::~SyncSession() {}
1,595✔
1290

1291
SyncSession::State SyncSession::state() const
1292
{
190,253✔
1293
    util::CheckedUniqueLock lock(m_state_mutex);
190,253✔
1294
    return m_state;
190,253✔
1295
}
190,253✔
1296

1297
SyncSession::ConnectionState SyncSession::connection_state() const
1298
{
5,796✔
1299
    util::CheckedUniqueLock lock(m_connection_state_mutex);
5,796✔
1300
    return m_connection_state;
5,796✔
1301
}
5,796✔
1302

1303
std::string const& SyncSession::path() const
1304
{
240✔
1305
    return m_db->get_path();
240✔
1306
}
240✔
1307

1308
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_flx_subscription_store()
1309
{
3,527,468✔
1310
    util::CheckedLockGuard lock(m_state_mutex);
3,527,468✔
1311
    return m_flx_subscription_store;
3,527,468✔
1312
}
3,527,468✔
1313

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

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

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

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

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

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

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

1375
    m_config.sync_config = m_migrated_sync_config;
24✔
1376
    m_migrated_sync_config.reset();
24✔
1377
}
24✔
1378

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

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

1389
    // The session should be closed before updating the FLX subscription store
1390
    REALM_ASSERT(!m_session);
52✔
1391

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

1408
    if (m_flx_subscription_store)
44✔
1409
        return; // Using FLX and subscription store already exists
2✔
1410

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

1414
    std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
42✔
1415

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

1425
    auto tr = m_db->start_write();
42✔
1426
    set_write_validator_factory(weak_sub_mgr);
42✔
1427
    tr->rollback();
42✔
1428
}
42✔
1429

1430
void SyncSession::create_subscription_store()
1431
{
631✔
1432
    REALM_ASSERT(!m_flx_subscription_store);
631✔
1433

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

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

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

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

1477
    ~ExternalReference()
1478
    {
1,601✔
1479
        m_session->did_drop_external_reference();
1,601✔
1480
    }
1,601✔
1481

1482
private:
1483
    std::shared_ptr<SyncSession> m_session;
1484
};
1485

1486
std::shared_ptr<SyncSession> SyncSession::external_reference()
1487
{
1,837✔
1488
    util::CheckedLockGuard lock(m_external_reference_mutex);
1,837✔
1489

1490
    if (auto external_reference = m_external_reference.lock())
1,837✔
1491
        return std::shared_ptr<SyncSession>(external_reference, this);
236✔
1492

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

1498
std::shared_ptr<SyncSession> SyncSession::existing_external_reference()
1499
{
2,646✔
1500
    util::CheckedLockGuard lock(m_external_reference_mutex);
2,646✔
1501

1502
    if (auto external_reference = m_external_reference.lock())
2,646✔
1503
        return std::shared_ptr<SyncSession>(external_reference, this);
1,099✔
1504

1505
    return nullptr;
1,547✔
1506
}
2,646✔
1507

1508
void SyncSession::did_drop_external_reference()
1509
{
1,601✔
1510
    util::CheckedUniqueLock lock1(m_state_mutex);
1,601✔
1511
    {
1,601✔
1512
        util::CheckedLockGuard lock2(m_external_reference_mutex);
1,601✔
1513

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

1519
    close(std::move(lock1));
1,601✔
1520
}
1,601✔
1521

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

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

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

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

1578
void SyncProgressNotifier::set_local_version(uint64_t snapshot_version)
1579
{
9,238✔
1580
    std::lock_guard<std::mutex> lock(m_mutex);
9,238✔
1581
    m_local_transaction_version = snapshot_version;
9,238✔
1582
}
9,238✔
1583

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

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

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

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

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

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

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

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

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

1659
        old = std::move(*it);
2✔
1660
        m_callbacks.erase(it);
2✔
1661
    }
2✔
1662
}
2✔
1663

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

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

1686
    return m_session->send_test_command(std::move(body));
30✔
1687
}
30✔
1688

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

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

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

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

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