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

realm / realm-core / 1892

05 Dec 2023 07:16PM UTC coverage: 91.692% (+0.02%) from 91.674%
1892

push

Evergreen

web-flow
Merge pull request #7161 from realm/tg/in-place-client-reset

Rewrite the local changesets in-place for client reset recovery

92346 of 169330 branches covered (0.0%)

835 of 865 new or added lines in 17 files covered. (96.53%)

103 existing lines in 16 files now uncovered.

231991 of 253012 relevant lines covered (91.69%)

6443355.21 hits per line

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

93.38
/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/sync_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/protocol.hpp>
40

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

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

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

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

86
void SyncSession::become_active()
87
{
1,711✔
88
    REALM_ASSERT(m_state != State::Active);
1,711✔
89
    m_state = State::Active;
1,711✔
90

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

768✔
109
    // when entering from the Dying state the session will still be bound
768✔
110
    if (!m_session) {
1,711✔
111
        create_sync_session();
1,709✔
112
        m_session->bind();
1,709✔
113
    }
1,709✔
114

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

768✔
121
    for (auto& [id, callback_tuple] : callbacks_to_register) {
945✔
122
        add_completion_callback(std::move(callback_tuple.second), callback_tuple.first);
339✔
123
    }
339✔
124
}
1,711✔
125

126
void SyncSession::restart_session()
127
{
8✔
128
    util::CheckedUniqueLock lock(m_state_mutex);
8✔
129
    do_restart_session(std::move(lock));
8✔
130
}
8✔
131

132
void SyncSession::become_dying(util::CheckedUniqueLock lock)
133
{
74✔
134
    REALM_ASSERT(m_state != State::Dying);
74✔
135
    m_state = State::Dying;
74✔
136

29✔
137
    // If we have no session, we cannot possibly upload anything.
29✔
138
    if (!m_session) {
74✔
139
        become_inactive(std::move(lock));
×
140
        return;
×
141
    }
×
142

29✔
143
    size_t current_death_count = ++m_death_count;
74✔
144
    m_session->async_wait_for_upload_completion([weak_session = weak_from_this(), current_death_count](Status) {
74✔
145
        if (auto session = weak_session.lock()) {
74✔
146
            util::CheckedUniqueLock lock(session->m_state_mutex);
37✔
147
            if (session->m_state == State::Dying && session->m_death_count == current_death_count) {
37✔
148
                session->become_inactive(std::move(lock));
37✔
149
            }
37✔
150
        }
37✔
151
    });
74✔
152
    m_state_mutex.unlock(lock);
74✔
153
}
74✔
154

155
void SyncSession::become_inactive(util::CheckedUniqueLock lock, Status status, bool cancel_subscription_notifications)
156
{
1,526✔
157
    REALM_ASSERT(m_state != State::Inactive);
1,526✔
158
    m_state = State::Inactive;
1,526✔
159

674✔
160
    do_become_inactive(std::move(lock), status, cancel_subscription_notifications);
1,526✔
161
}
1,526✔
162

163
void SyncSession::become_paused(util::CheckedUniqueLock lock)
164
{
152✔
165
    REALM_ASSERT(m_state != State::Paused);
152✔
166
    auto old_state = m_state;
152✔
167
    m_state = State::Paused;
152✔
168

76✔
169
    // Nothing to do if we're already inactive besides update the state.
76✔
170
    if (old_state == State::Inactive) {
152✔
171
        m_state_mutex.unlock(lock);
2✔
172
        return;
2✔
173
    }
2✔
174

75✔
175
    do_become_inactive(std::move(lock), Status::OK(), true);
150✔
176
}
150✔
177

178
void SyncSession::do_restart_session(util::CheckedUniqueLock)
179
{
8✔
180
    // Nothing to do if the sync session is currently paused
4✔
181
    // It will be resumed when resume() is called
4✔
182
    if (m_state == State::Paused)
8✔
183
        return;
×
184

4✔
185
    // Go straight to inactive so the progress completion waiters will
4✔
186
    // continue to wait until the session restarts and completes the
4✔
187
    // upload/download sync
4✔
188
    m_state = State::Inactive;
8✔
189

4✔
190
    if (m_session) {
8✔
191
        m_session.reset();
8✔
192
    }
8✔
193

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

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

749✔
212
    SyncSession::CompletionCallbacks waits;
1,676✔
213
    std::swap(waits, m_completion_callbacks);
1,676✔
214

749✔
215
    m_session = nullptr;
1,676✔
216
    if (m_sync_manager) {
1,676✔
217
        m_sync_manager->unregister_session(m_db->get_path());
1,676✔
218
    }
1,676✔
219

749✔
220
    auto subscription_store = m_flx_subscription_store;
1,676✔
221
    m_state_mutex.unlock(lock);
1,676✔
222

749✔
223
    // Send notifications after releasing the lock to prevent deadlocks in the callback.
749✔
224
    if (old_state != new_state) {
1,676✔
225
        m_connection_change_notifier.invoke_callbacks(old_state, connection_state());
1,343✔
226
    }
1,343✔
227

749✔
228
    if (status.is_ok())
1,676✔
229
        status = Status(ErrorCodes::OperationAborted, "Sync session became inactive");
1,604✔
230

749✔
231
    if (subscription_store && cancel_subscription_notifications) {
1,676✔
232
        subscription_store->notify_all_state_change_notifications(status);
464✔
233
    }
464✔
234

749✔
235
    // Inform any queued-up completion handlers that they were cancelled.
749✔
236
    for (auto& [id, callback] : waits)
1,676✔
237
        callback.second(status);
58✔
238
}
1,676✔
239

240
void SyncSession::become_waiting_for_access_token()
241
{
18✔
242
    REALM_ASSERT(m_state != State::WaitingForAccessToken);
18✔
243
    m_state = State::WaitingForAccessToken;
18✔
244
}
18✔
245

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

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

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

6✔
273
    return false;
12✔
274
}
12✔
275

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

6✔
286
    return false;
12✔
287
}
12✔
288

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

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

603✔
375
    // Adjust the sync_config if using PBS sync and already in the migrated or rollback state
603✔
376
    if (m_migration_store->is_migrated() || m_migration_store->is_rollback_in_progress()) {
1,379✔
377
        m_config.sync_config = sync::MigrationStore::convert_sync_config_to_flx(m_original_sync_config);
8✔
378
    }
8✔
379

603✔
380
    // If using FLX, set up m_flx_subscription_store and the history_write_validator
603✔
381
    if (m_config.sync_config->flx_sync_requested) {
1,379✔
382
        create_subscription_store();
418✔
383
        std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
418✔
384
        set_write_validator_factory(weak_sub_mgr);
418✔
385
    }
418✔
386

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

398
std::shared_ptr<SyncManager> SyncSession::sync_manager() const
399
{
×
400
    util::CheckedLockGuard lk(m_state_mutex);
×
401
    REALM_ASSERT(m_sync_manager);
×
402
    return m_sync_manager->shared_from_this();
×
403
}
×
404

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

412
void SyncSession::update_error_and_mark_file_for_deletion(SyncError& error, ShouldBackup should_backup)
413
{
70✔
414
    util::CheckedLockGuard config_lock(m_config_mutex);
70✔
415
    // Add a SyncFileActionMetadata marking the Realm as needing to be deleted.
35✔
416
    std::string recovery_path;
70✔
417
    auto original_path = path();
70✔
418
    error.user_info[SyncError::c_original_file_path_key] = original_path;
70✔
419
    if (should_backup == ShouldBackup::yes) {
70✔
420
        recovery_path = util::reserve_unique_file_name(
70✔
421
            m_sync_manager->recovery_directory_path(m_config.sync_config->recovery_directory),
70✔
422
            util::create_timestamped_template("recovered_realm"));
70✔
423
        error.user_info[SyncError::c_recovery_file_path_key] = recovery_path;
70✔
424
    }
70✔
425
    using Action = SyncFileActionMetadata::Action;
70✔
426
    auto action = should_backup == ShouldBackup::yes ? Action::BackUpThenDeleteRealm : Action::DeleteRealm;
70✔
427
    m_sync_manager->perform_metadata_update([action, original_path = std::move(original_path),
70✔
428
                                             recovery_path = std::move(recovery_path),
70✔
429
                                             partition_value = m_config.sync_config->partition_value,
70✔
430
                                             identity = m_config.sync_config->user->identity()](const auto& manager) {
70✔
431
        manager.make_file_action_metadata(original_path, partition_value, identity, action, recovery_path);
70✔
432
    });
70✔
433
}
70✔
434

435
void SyncSession::download_fresh_realm(sync::ProtocolErrorInfo::Action server_requests_action)
436
{
176✔
437
    // first check that recovery will not be prevented
88✔
438
    if (server_requests_action == sync::ProtocolErrorInfo::Action::ClientResetNoRecovery) {
176✔
439
        auto mode = config(&SyncConfig::client_resync_mode);
4✔
440
        if (mode == ClientResyncMode::Recover) {
4✔
441
            handle_fresh_realm_downloaded(
2✔
442
                nullptr,
2✔
443
                {ErrorCodes::RuntimeError,
2✔
444
                 "A client reset is required but the server does not permit recovery for this client"},
2✔
445
                server_requests_action);
2✔
446
            return;
2✔
447
        }
2✔
448
    }
174✔
449

87✔
450
    std::vector<char> encryption_key;
174✔
451
    {
174✔
452
        util::CheckedLockGuard lock(m_config_mutex);
174✔
453
        encryption_key = m_config.encryption_key;
174✔
454
    }
174✔
455

87✔
456
    DBOptions options;
174✔
457
    options.allow_file_format_upgrade = false;
174✔
458
    options.enable_async_writes = false;
174✔
459
    if (!encryption_key.empty())
174✔
460
        options.encryption_key = encryption_key.data();
2✔
461

87✔
462
    DBRef db;
174✔
463
    auto fresh_path = client_reset::get_fresh_path_for(m_db->get_path());
174✔
464
    try {
174✔
465
        // We want to attempt to use a pre-existing file to reduce the chance of
87✔
466
        // downloading the first part of the file only to then delete it over
87✔
467
        // and over, but if we fail to open it then we should just start over.
87✔
468
        try {
174✔
469
            db = DB::create(sync::make_client_replication(), fresh_path, options);
174✔
470
        }
174✔
471
        catch (...) {
92✔
472
            util::File::try_remove(fresh_path);
10✔
473
        }
10✔
474

87✔
475
        if (!db) {
170✔
476
            db = DB::create(sync::make_client_replication(), fresh_path, options);
2✔
477
        }
2✔
478
    }
166✔
479
    catch (...) {
91✔
480
        // Failed to open the fresh path after attempting to delete it, so we
4✔
481
        // just can't do automatic recovery.
4✔
482
        handle_fresh_realm_downloaded(nullptr, exception_to_status(), server_requests_action);
8✔
483
        return;
8✔
484
    }
8✔
485

83✔
486
    util::CheckedLockGuard state_lock(m_state_mutex);
166✔
487
    if (m_state != State::Active) {
166✔
488
        return;
×
489
    }
×
490
    std::shared_ptr<SyncSession> fresh_sync_session;
166✔
491
    {
166✔
492
        util::CheckedLockGuard config_lock(m_config_mutex);
166✔
493
        RealmConfig config = m_config;
166✔
494
        config.path = fresh_path;
166✔
495
        // in case of migrations use the migrated config
83✔
496
        auto fresh_config = m_migrated_sync_config ? *m_migrated_sync_config : *m_config.sync_config;
152✔
497
        // deep copy the sync config so we don't modify the live session's config
83✔
498
        config.sync_config = std::make_shared<SyncConfig>(fresh_config);
166✔
499
        config.sync_config->client_resync_mode = ClientResyncMode::Manual;
166✔
500
        fresh_sync_session = m_sync_manager->get_session(db, config);
166✔
501
        auto& history = static_cast<sync::ClientReplication&>(*db->get_replication());
166✔
502
        // the fresh Realm may apply writes to this db after it has outlived its sync session
83✔
503
        // the writes are used to generate a changeset for recovery, but are never committed
83✔
504
        history.set_write_validator_factory({});
166✔
505
    }
166✔
506

83✔
507
    fresh_sync_session->assert_mutex_unlocked();
166✔
508
    // The fresh realm uses flexible sync.
83✔
509
    if (auto fresh_sub_store = fresh_sync_session->get_flx_subscription_store()) {
166✔
510
        auto fresh_sub = fresh_sub_store->get_latest();
64✔
511
        // The local realm uses flexible sync as well so copy the active subscription set to the fresh realm.
32✔
512
        if (auto local_subs_store = m_flx_subscription_store) {
64✔
513
            auto fresh_mut_sub = fresh_sub.make_mutable_copy();
46✔
514
            fresh_mut_sub.import(local_subs_store->get_active());
46✔
515
            fresh_sub = fresh_mut_sub.commit();
46✔
516
        }
46✔
517

32✔
518
        auto self = shared_from_this();
64✔
519
        using SubscriptionState = sync::SubscriptionSet::State;
64✔
520
        fresh_sub.get_state_change_notification(SubscriptionState::Complete)
64✔
521
            .then([=](SubscriptionState) -> util::Future<sync::SubscriptionSet> {
63✔
522
                if (server_requests_action != sync::ProtocolErrorInfo::Action::MigrateToFLX) {
62✔
523
                    return fresh_sub;
44✔
524
                }
44✔
525
                if (!self->m_migration_store->is_migration_in_progress()) {
18✔
NEW
526
                    return fresh_sub;
×
UNCOV
527
                }
×
528

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

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

6✔
586
        sync::SessionErrorInfo synthetic(
12✔
587
            Status{ErrorCodes::AutoClientResetFailed,
12✔
588
                   util::format("A fatal error occurred during client reset: '%1'", status.reason())},
12✔
589
            sync::IsFatal{true});
12✔
590
        handle_error(synthetic);
12✔
591
        return;
12✔
592
    }
12✔
593

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

79✔
620
        // Once the session is inactive, update sync config and subscription store after migration.
79✔
621
        if (server_requests_action == sync::ProtocolErrorInfo::Action::MigrateToFLX ||
158✔
622
            server_requests_action == sync::ProtocolErrorInfo::Action::RevertToPBS) {
149✔
623
            apply_sync_config_after_migration_or_rollback();
26✔
624
            auto flx_sync_requested = config(&SyncConfig::flx_sync_requested);
26✔
625
            update_subscription_store(flx_sync_requested, std::move(new_subs));
26✔
626
        }
26✔
627
    }
158✔
628
    revive_if_needed();
158✔
629
}
158✔
630

631
void SyncSession::OnlyForTesting::handle_error(SyncSession& session, sync::SessionErrorInfo&& error)
632
{
16✔
633
    session.handle_error(std::move(error));
16✔
634
}
16✔
635

636
// This method should only be called from within the error handler callback registered upon the underlying
637
// `m_session`.
638
void SyncSession::handle_error(sync::SessionErrorInfo error)
639
{
387✔
640
    enum class NextStateAfterError { none, inactive, error };
387✔
641
    auto next_state = error.is_fatal ? NextStateAfterError::error : NextStateAfterError::none;
331✔
642
    util::Optional<ShouldBackup> delete_file;
387✔
643
    bool log_out_user = false;
387✔
644
    bool unrecognized_by_client = false;
387✔
645

192✔
646
    if (error.status == ErrorCodes::AutoClientResetFailed) {
387✔
647
        // At this point, automatic recovery has been attempted but it failed.
23✔
648
        // Fallback to a manual reset and let the user try to handle it.
23✔
649
        next_state = NextStateAfterError::inactive;
46✔
650
        delete_file = ShouldBackup::yes;
46✔
651
    }
46✔
652
    else if (error.server_requests_action != sync::ProtocolErrorInfo::Action::NoAction) {
341✔
653
        switch (error.server_requests_action) {
331✔
654
            case sync::ProtocolErrorInfo::Action::NoAction:
✔
655
                REALM_UNREACHABLE(); // This is not sent by the MongoDB server
656
            case sync::ProtocolErrorInfo::Action::ApplicationBug:
21✔
657
                [[fallthrough]];
21✔
658
            case sync::ProtocolErrorInfo::Action::ProtocolViolation:
27✔
659
                break;
27✔
660
            case sync::ProtocolErrorInfo::Action::Warning:
22✔
661
                break; // not fatal, but should be bubbled up to the user below.
22✔
662
            case sync::ProtocolErrorInfo::Action::Transient:
58✔
663
                // Not real errors, don't need to be reported to the binding.
29✔
664
                return;
58✔
665
            case sync::ProtocolErrorInfo::Action::DeleteRealm:
9✔
666
                next_state = NextStateAfterError::inactive;
×
667
                delete_file = ShouldBackup::no;
×
668
                break;
×
669
            case sync::ProtocolErrorInfo::Action::ClientReset:
168✔
670
                [[fallthrough]];
168✔
671
            case sync::ProtocolErrorInfo::Action::ClientResetNoRecovery:
172✔
672
                switch (config(&SyncConfig::client_resync_mode)) {
172✔
673
                    case ClientResyncMode::Manual:
24✔
674
                        next_state = NextStateAfterError::inactive;
24✔
675
                        delete_file = ShouldBackup::yes;
24✔
676
                        break;
24✔
677
                    case ClientResyncMode::DiscardLocal:
78✔
678
                        [[fallthrough]];
78✔
679
                    case ClientResyncMode::RecoverOrDiscard:
90✔
680
                        [[fallthrough]];
90✔
681
                    case ClientResyncMode::Recover:
148✔
682
                        download_fresh_realm(error.server_requests_action);
148✔
683
                        return; // do not propgate the error to the user at this point
148✔
684
                }
24✔
685
                break;
24✔
686
            case sync::ProtocolErrorInfo::Action::MigrateToFLX:
21✔
687
                // Should not receive this error if original sync config is FLX
9✔
688
                REALM_ASSERT(!m_original_sync_config->flx_sync_requested);
18✔
689
                REALM_ASSERT(error.migration_query_string && !error.migration_query_string->empty());
18✔
690
                // Original config was PBS, migrating to FLX
9✔
691
                m_migration_store->migrate_to_flx(*error.migration_query_string,
18✔
692
                                                  m_original_sync_config->partition_value);
18✔
693
                save_sync_config_after_migration_or_rollback();
18✔
694
                download_fresh_realm(error.server_requests_action);
18✔
695
                return;
18✔
696
            case sync::ProtocolErrorInfo::Action::RevertToPBS:
17✔
697
                // If the client was updated to use FLX natively, but the server was rolled back to PBS,
5✔
698
                // the server should be sending switch_to_flx_sync; throw exception if this error is not
5✔
699
                // received.
5✔
700
                if (m_original_sync_config->flx_sync_requested) {
10✔
701
                    throw LogicError(ErrorCodes::InvalidServerResponse,
×
702
                                     "Received 'RevertToPBS' from server after rollback while client is natively "
×
703
                                     "using FLX - expected 'SwitchToPBS'");
×
704
                }
×
705
                // Original config was PBS, rollback the migration
5✔
706
                m_migration_store->rollback_to_pbs();
10✔
707
                save_sync_config_after_migration_or_rollback();
10✔
708
                download_fresh_realm(error.server_requests_action);
10✔
709
                return;
10✔
710
            case sync::ProtocolErrorInfo::Action::RefreshUser:
18✔
711
                if (auto u = user()) {
18✔
712
                    u->refresh_custom_data(false, handle_refresh(shared_from_this(), false));
18✔
713
                    return;
18✔
714
                }
18✔
715
                break;
×
716
            case sync::ProtocolErrorInfo::Action::RefreshLocation:
6✔
717
                if (auto u = user()) {
6✔
718
                    u->refresh_custom_data(true, handle_refresh(shared_from_this(), true));
6✔
719
                    return;
6✔
720
                }
6✔
721
                break;
×
722
            case sync::ProtocolErrorInfo::Action::LogOutUser:
✔
723
                next_state = NextStateAfterError::inactive;
×
724
                log_out_user = true;
×
725
                break;
×
726
        }
10✔
727
    }
10✔
728
    else {
10✔
729
        // Unrecognized error code.
5✔
730
        unrecognized_by_client = true;
10✔
731
    }
10✔
732

192✔
733
    util::CheckedUniqueLock lock(m_state_mutex);
258✔
734
    SyncError sync_error{error.status, error.is_fatal, error.log_url, std::move(error.compensating_writes)};
129✔
735
    // `action` is used over `shouldClientReset` and `isRecoveryModeDisabled`.
63✔
736
    sync_error.server_requests_action = error.server_requests_action;
129✔
737
    sync_error.is_unrecognized_by_client = unrecognized_by_client;
129✔
738

63✔
739
    if (delete_file)
129✔
740
        update_error_and_mark_file_for_deletion(sync_error, *delete_file);
70✔
741

63✔
742
    if (m_state == State::Dying && error.is_fatal) {
129✔
743
        become_inactive(std::move(lock), error.status);
2✔
744
        return;
2✔
745
    }
2✔
746

62✔
747
    // Don't bother invoking m_config.error_handler if the sync is inactive.
62✔
748
    // It does not make sense to call the handler when the session is closed.
62✔
749
    if (m_state == State::Inactive || m_state == State::Paused) {
127✔
750
        return;
×
751
    }
×
752

62✔
753
    switch (next_state) {
127✔
754
        case NextStateAfterError::none:
30✔
755
            if (config(&SyncConfig::cancel_waits_on_nonfatal_error)) {
30✔
756
                cancel_pending_waits(std::move(lock), sync_error.status); // unlocks the mutex
×
757
            }
×
758
            break;
30✔
759
        case NextStateAfterError::inactive: {
70✔
760
            become_inactive(std::move(lock), sync_error.status);
70✔
761
            break;
70✔
762
        }
×
763
        case NextStateAfterError::error: {
27✔
764
            cancel_pending_waits(std::move(lock), sync_error.status);
27✔
765
            break;
27✔
766
        }
127✔
767
    }
127✔
768

62✔
769
    if (log_out_user) {
127✔
770
        if (auto u = user())
×
771
            u->log_out();
×
772
    }
×
773

62✔
774
    if (auto error_handler = config(&SyncConfig::error_handler)) {
127✔
775
        error_handler(shared_from_this(), std::move(sync_error));
127✔
776
    }
127✔
777
}
127✔
778

779
void SyncSession::cancel_pending_waits(util::CheckedUniqueLock lock, Status error)
780
{
43✔
781
    CompletionCallbacks callbacks;
43✔
782
    std::swap(callbacks, m_completion_callbacks);
43✔
783

20✔
784
    // Inform any waiters on pending subscription states that they were cancelled
20✔
785
    if (m_flx_subscription_store) {
43✔
786
        auto subscription_store = m_flx_subscription_store;
18✔
787
        m_state_mutex.unlock(lock);
18✔
788
        subscription_store->notify_all_state_change_notifications(error);
18✔
789
    }
18✔
790
    else {
25✔
791
        m_state_mutex.unlock(lock);
25✔
792
    }
25✔
793

20✔
794
    // Inform any queued-up completion handlers that they were cancelled.
20✔
795
    for (auto& [id, callback] : callbacks)
43✔
796
        callback.second(error);
18✔
797
}
43✔
798

799
void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded,
800
                                         uint64_t uploadable, uint64_t download_version, uint64_t snapshot_version)
801
{
6,478✔
802
    m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, download_version, snapshot_version);
6,478✔
803
}
6,478✔
804

805
static sync::Session::Config::ClientReset make_client_reset_config(const RealmConfig& base_config,
806
                                                                   const std::shared_ptr<SyncConfig>& sync_config,
807
                                                                   DBRef&& fresh_copy, bool recovery_is_allowed)
808
{
158✔
809
    REALM_ASSERT(sync_config->client_resync_mode != ClientResyncMode::Manual);
158✔
810

79✔
811
    sync::Session::Config::ClientReset config;
158✔
812
    config.mode = sync_config->client_resync_mode;
158✔
813
    config.fresh_copy = std::move(fresh_copy);
158✔
814
    config.recovery_is_allowed = recovery_is_allowed;
158✔
815

79✔
816
    // The conditions here are asymmetric because if we have *either* a before
79✔
817
    // or after callback we need to make sure to initialize the local schema
79✔
818
    // before the client reset happens.
79✔
819
    if (!sync_config->notify_before_client_reset && !sync_config->notify_after_client_reset)
158✔
820
        return config;
26✔
821

66✔
822
    RealmConfig realm_config = base_config;
132✔
823
    realm_config.sync_config = std::make_shared<SyncConfig>(*sync_config); // deep copy
132✔
824
    realm_config.scheduler = util::Scheduler::make_dummy();
132✔
825

66✔
826
    if (sync_config->notify_after_client_reset) {
132✔
827
        config.notify_after_client_reset = [realm_config](VersionID previous_version, bool did_recover) {
113✔
828
            auto coordinator = _impl::RealmCoordinator::get_coordinator(realm_config);
96✔
829
            ThreadSafeReference active_after = coordinator->get_unbound_realm();
96✔
830
            SharedRealm frozen_before = coordinator->get_realm(realm_config, previous_version);
96✔
831
            REALM_ASSERT(frozen_before);
96✔
832
            REALM_ASSERT(frozen_before->is_frozen());
96✔
833
            realm_config.sync_config->notify_after_client_reset(std::move(frozen_before), std::move(active_after),
96✔
834
                                                                did_recover);
96✔
835
        };
96✔
836
    }
130✔
837
    config.notify_before_client_reset = [config = std::move(realm_config)]() -> VersionID {
132✔
838
        // Opening the Realm live here may make a write if the schema is different
66✔
839
        // than what exists on disk. It is necessary to pass a fully usable Realm
66✔
840
        // to the user here. Note that the schema changes made here will be considered
66✔
841
        // an "offline write" to be recovered if this is recovery mode.
66✔
842
        auto before = Realm::get_shared_realm(config);
132✔
843
        if (auto& notify_before = config.sync_config->notify_before_client_reset) {
132✔
844
            notify_before(config.sync_config->freeze_before_reset_realm ? before->freeze() : before);
128✔
845
        }
130✔
846
        // Note that if the SDK wrote to the Realm (hopefully by requesting a
66✔
847
        // live instance and not opening a secondary one), this may be a
66✔
848
        // different version than what we had before calling the callback.
66✔
849
        before->refresh();
132✔
850
        return before->read_transaction_version();
132✔
851
    };
132✔
852

66✔
853
    return config;
132✔
854
}
132✔
855

856
void SyncSession::create_sync_session()
857
{
1,709✔
858
    if (m_session)
1,709✔
859
        return;
×
860

767✔
861
    util::CheckedLockGuard config_lock(m_config_mutex);
1,709✔
862

767✔
863
    REALM_ASSERT(m_config.sync_config);
1,709✔
864
    SyncConfig& sync_config = *m_config.sync_config;
1,709✔
865
    REALM_ASSERT(sync_config.user);
1,709✔
866

767✔
867
    sync::Session::Config session_config;
1,709✔
868
    session_config.signed_user_token = sync_config.user->access_token();
1,709✔
869
    session_config.user_id = sync_config.user->identity();
1,709✔
870
    session_config.realm_identifier = sync_config.partition_value;
1,709✔
871
    session_config.verify_servers_ssl_certificate = sync_config.client_validate_ssl;
1,709✔
872
    session_config.ssl_trust_certificate_path = sync_config.ssl_trust_certificate_path;
1,709✔
873
    session_config.ssl_verify_callback = sync_config.ssl_verify_callback;
1,709✔
874
    session_config.proxy_config = sync_config.proxy_config;
1,709✔
875
    session_config.simulate_integration_error = sync_config.simulate_integration_error;
1,709✔
876
    session_config.flx_bootstrap_batch_size_bytes = sync_config.flx_bootstrap_batch_size_bytes;
1,709✔
877
    session_config.session_reason =
1,709✔
878
        client_reset::is_fresh_path(m_config.path) ? sync::SessionReason::ClientReset : sync::SessionReason::Sync;
1,630✔
879

767✔
880
    if (sync_config.on_sync_client_event_hook) {
1,709✔
881
        session_config.on_sync_client_event_hook = [hook = sync_config.on_sync_client_event_hook,
58✔
882
                                                    anchor = weak_from_this()](const SyncClientHookData& data) {
418✔
883
            return hook(anchor, data);
418✔
884
        };
418✔
885
    }
58✔
886

767✔
887
    {
1,709✔
888
        std::string sync_route = m_sync_manager->sync_route();
1,709✔
889

767✔
890
        if (!m_client.decompose_server_url(sync_route, session_config.protocol_envelope,
1,709✔
891
                                           session_config.server_address, session_config.server_port,
1,709✔
892
                                           session_config.service_identifier)) {
767✔
893
            throw sync::BadServerUrl(sync_route);
×
894
        }
×
895
        // FIXME: Java needs the fully resolved URL for proxy support, but we also need it before
767✔
896
        // the session is created. How to resolve this?
767✔
897
        m_server_url = sync_route;
1,709✔
898
    }
1,709✔
899

767✔
900
    if (sync_config.authorization_header_name) {
1,709✔
901
        session_config.authorization_header_name = *sync_config.authorization_header_name;
×
902
    }
×
903
    session_config.custom_http_headers = sync_config.custom_http_headers;
1,709✔
904

767✔
905
    if (m_server_requests_action != sync::ProtocolErrorInfo::Action::NoAction) {
1,709✔
906
        // Migrations are allowed to recover local data.
79✔
907
        const bool allowed_to_recover = m_server_requests_action == sync::ProtocolErrorInfo::Action::ClientReset ||
158✔
908
                                        m_server_requests_action == sync::ProtocolErrorInfo::Action::MigrateToFLX ||
93✔
909
                                        m_server_requests_action == sync::ProtocolErrorInfo::Action::RevertToPBS;
84✔
910
        // Use the original sync config, not the updated one from the migration store
79✔
911
        session_config.client_reset_config = make_client_reset_config(
158✔
912
            m_config, m_original_sync_config, std::move(m_client_reset_fresh_copy), allowed_to_recover);
158✔
913
        m_server_requests_action = sync::ProtocolErrorInfo::Action::NoAction;
158✔
914
    }
158✔
915

767✔
916
    m_session = m_client.make_session(m_db, m_flx_subscription_store, m_migration_store, std::move(session_config));
1,709✔
917

767✔
918
    std::weak_ptr<SyncSession> weak_self = weak_from_this();
1,709✔
919

767✔
920
    // Set up the wrapped progress handler callback
767✔
921
    m_session->set_progress_handler([weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable,
1,709✔
922
                                                uint_fast64_t uploaded, uint_fast64_t uploadable,
1,709✔
923
                                                uint_fast64_t progress_version, uint_fast64_t snapshot_version) {
6,673✔
924
        if (auto self = weak_self.lock()) {
6,673✔
925
            self->handle_progress_update(downloaded, downloadable, uploaded, uploadable, progress_version,
6,478✔
926
                                         snapshot_version);
6,478✔
927
        }
6,478✔
928
    });
6,673✔
929

767✔
930
    // Sets up the connection state listener. This callback is used for both reporting errors as well as changes to
767✔
931
    // the connection state.
767✔
932
    m_session->set_connection_state_change_listener(
1,709✔
933
        [weak_self](sync::ConnectionState state, util::Optional<sync::SessionErrorInfo> error) {
3,646✔
934
            // If the OS SyncSession object is destroyed, we ignore any events from the underlying Session as there is
1,672✔
935
            // nothing useful we can do with them.
1,672✔
936
            auto self = weak_self.lock();
3,646✔
937
            if (!self) {
3,646✔
938
                return;
20✔
939
            }
20✔
940
            using cs = sync::ConnectionState;
3,626✔
941
            ConnectionState new_state = [&] {
3,626✔
942
                switch (state) {
3,626✔
943
                    case cs::disconnected:
333✔
944
                        return ConnectionState::Disconnected;
333✔
945
                    case cs::connecting:
1,686✔
946
                        return ConnectionState::Connecting;
1,686✔
947
                    case cs::connected:
1,607✔
948
                        return ConnectionState::Connected;
1,607✔
949
                }
×
950
                REALM_UNREACHABLE();
951
            }();
×
952
            util::CheckedUniqueLock lock(self->m_connection_state_mutex);
3,626✔
953
            auto old_state = self->m_connection_state;
3,626✔
954
            self->m_connection_state = new_state;
3,626✔
955
            lock.unlock();
3,626✔
956

1,666✔
957
            if (old_state != new_state) {
3,626✔
958
                self->m_connection_change_notifier.invoke_callbacks(old_state, new_state);
3,588✔
959
            }
3,588✔
960

1,666✔
961
            if (error) {
3,626✔
962
                self->handle_error(std::move(*error));
359✔
963
            }
359✔
964
        });
3,626✔
965
}
1,709✔
966

967
void SyncSession::nonsync_transact_notify(sync::version_type version)
968
{
7,823✔
969
    m_progress_notifier.set_local_version(version);
7,823✔
970

3,807✔
971
    util::CheckedUniqueLock lock(m_state_mutex);
7,823✔
972
    switch (m_state) {
7,823✔
973
        case State::Active:
7,493✔
974
        case State::WaitingForAccessToken:
7,494✔
975
            if (m_session) {
7,494✔
976
                m_session->nonsync_transact_notify(version);
7,492✔
977
            }
7,492✔
978
            break;
7,494✔
979
        case State::Dying:
3,675✔
980
        case State::Inactive:
207✔
981
        case State::Paused:
329✔
982
            break;
329✔
983
    }
7,823✔
984
}
7,823✔
985

986
void SyncSession::revive_if_needed()
987
{
2,040✔
988
    util::CheckedUniqueLock lock(m_state_mutex);
2,040✔
989
    switch (m_state) {
2,040✔
990
        case State::Active:
474✔
991
        case State::WaitingForAccessToken:
474✔
992
        case State::Paused:
477✔
993
            return;
477✔
994
        case State::Dying:
695✔
995
        case State::Inactive:
1,563✔
996
            do_revive(std::move(lock));
1,563✔
997
            break;
1,563✔
998
    }
2,040✔
999
}
2,040✔
1000

1001
void SyncSession::handle_reconnect()
1002
{
×
1003
    util::CheckedUniqueLock lock(m_state_mutex);
×
1004
    switch (m_state) {
×
1005
        case State::Active:
×
1006
            m_session->cancel_reconnect_delay();
×
1007
            break;
×
1008
        case State::Dying:
×
1009
        case State::Inactive:
×
1010
        case State::WaitingForAccessToken:
×
1011
        case State::Paused:
×
1012
            break;
×
1013
    }
×
1014
}
×
1015

1016
void SyncSession::force_close()
1017
{
237✔
1018
    util::CheckedUniqueLock lock(m_state_mutex);
237✔
1019
    switch (m_state) {
237✔
1020
        case State::Active:
222✔
1021
        case State::Dying:
222✔
1022
        case State::WaitingForAccessToken:
225✔
1023
            become_inactive(std::move(lock));
225✔
1024
            break;
225✔
1025
        case State::Inactive:
106✔
1026
        case State::Paused:
12✔
1027
            break;
12✔
1028
    }
237✔
1029
}
237✔
1030

1031
void SyncSession::pause()
1032
{
154✔
1033
    util::CheckedUniqueLock lock(m_state_mutex);
154✔
1034
    switch (m_state) {
154✔
1035
        case State::Active:
151✔
1036
        case State::Dying:
151✔
1037
        case State::WaitingForAccessToken:
151✔
1038
        case State::Inactive:
152✔
1039
            become_paused(std::move(lock));
152✔
1040
            break;
152✔
1041
        case State::Paused:
77✔
1042
            break;
2✔
1043
    }
154✔
1044
}
154✔
1045

1046
void SyncSession::resume()
1047
{
148✔
1048
    util::CheckedUniqueLock lock(m_state_mutex);
148✔
1049
    switch (m_state) {
148✔
1050
        case State::Active:
✔
1051
        case State::WaitingForAccessToken:
✔
1052
            return;
×
1053
        case State::Paused:
148✔
1054
        case State::Dying:
148✔
1055
        case State::Inactive:
148✔
1056
            do_revive(std::move(lock));
148✔
1057
            break;
148✔
1058
    }
148✔
1059
}
148✔
1060

1061
void SyncSession::do_revive(util::CheckedUniqueLock&& lock)
1062
{
1,711✔
1063
    auto u = user();
1,711✔
1064
    if (!u || !u->access_token_refresh_required()) {
1,711✔
1065
        become_active();
1,693✔
1066
        m_state_mutex.unlock(lock);
1,693✔
1067
        return;
1,693✔
1068
    }
1,693✔
1069

9✔
1070
    become_waiting_for_access_token();
18✔
1071
    // Release the lock for SDKs with a single threaded
9✔
1072
    // networking implementation such as our test suite
9✔
1073
    // so that the update can trigger a state change from
9✔
1074
    // the completion handler.
9✔
1075
    m_state_mutex.unlock(lock);
18✔
1076
    initiate_access_token_refresh();
18✔
1077
}
18✔
1078

1079
void SyncSession::close()
1080
{
100✔
1081
    util::CheckedUniqueLock lock(m_state_mutex);
100✔
1082
    close(std::move(lock));
100✔
1083
}
100✔
1084

1085
void SyncSession::close(util::CheckedUniqueLock lock)
1086
{
1,479✔
1087
    switch (m_state) {
1,479✔
1088
        case State::Active: {
1,032✔
1089
            switch (config(&SyncConfig::stop_policy)) {
1,032✔
1090
                case SyncSessionStopPolicy::Immediately:
958✔
1091
                    become_inactive(std::move(lock));
958✔
1092
                    break;
958✔
1093
                case SyncSessionStopPolicy::LiveIndefinitely:
✔
1094
                    // Don't do anything; session lives forever.
1095
                    m_state_mutex.unlock(lock);
×
1096
                    break;
×
1097
                case SyncSessionStopPolicy::AfterChangesUploaded:
74✔
1098
                    // Wait for all pending changes to upload.
29✔
1099
                    become_dying(std::move(lock));
74✔
1100
                    break;
74✔
1101
            }
1,032✔
1102
            break;
1,032✔
1103
        }
1,032✔
1104
        case State::Dying:
484✔
1105
            m_state_mutex.unlock(lock);
18✔
1106
            break;
18✔
1107
        case State::Paused:
469✔
1108
        case State::Inactive: {
427✔
1109
            // We need to register from the sync manager if it still exists so that we don't end up
148✔
1110
            // holding the DBRef open after the session is closed. Otherwise we can end up preventing
148✔
1111
            // the user from deleting the realm when it's in the paused/inactive state.
148✔
1112
            if (m_sync_manager) {
427✔
1113
                m_sync_manager->unregister_session(m_db->get_path());
423✔
1114
            }
423✔
1115
            m_state_mutex.unlock(lock);
427✔
1116
            break;
427✔
1117
        }
150✔
1118
        case State::WaitingForAccessToken:
149✔
1119
            // Immediately kill the session.
1✔
1120
            become_inactive(std::move(lock));
2✔
1121
            break;
2✔
1122
    }
1,479✔
1123
}
1,479✔
1124

1125
void SyncSession::shutdown_and_wait()
1126
{
120✔
1127
    {
120✔
1128
        // Transition immediately to `inactive` state. Calling this function must gurantee that any
10✔
1129
        // sync::Session object in SyncSession::m_session that existed prior to the time of invocation
10✔
1130
        // must have been destroyed upon return. This allows the caller to follow up with a call to
10✔
1131
        // sync::Client::wait_for_session_terminations_or_client_stopped() in order to wait for the
10✔
1132
        // Realm file to be closed. This works so long as this SyncSession object remains in the
10✔
1133
        // `inactive` state after the invocation of shutdown_and_wait().
10✔
1134
        util::CheckedUniqueLock lock(m_state_mutex);
120✔
1135
        if (m_state != State::Inactive && m_state != State::Paused) {
120✔
1136
            become_inactive(std::move(lock));
64✔
1137
        }
64✔
1138
    }
120✔
1139
    m_client.wait_for_session_terminations();
120✔
1140
}
120✔
1141

1142
void SyncSession::update_access_token(const std::string& signed_token)
1143
{
14✔
1144
    util::CheckedUniqueLock lock(m_state_mutex);
14✔
1145
    // We don't expect there to be a session when waiting for access token, but if there is, refresh its token.
7✔
1146
    // If not, the latest token will be seeded from SyncUser::access_token() on session creation.
7✔
1147
    if (m_session) {
14✔
1148
        m_session->refresh(signed_token);
2✔
1149
    }
2✔
1150
    if (m_state == State::WaitingForAccessToken) {
14✔
1151
        become_active();
8✔
1152
    }
8✔
1153
}
14✔
1154

1155
void SyncSession::initiate_access_token_refresh()
1156
{
20✔
1157
    if (auto session_user = user()) {
20✔
1158
        session_user->refresh_custom_data(handle_refresh(shared_from_this(), false));
20✔
1159
    }
20✔
1160
}
20✔
1161

1162
void SyncSession::add_completion_callback(util::UniqueFunction<void(Status)> callback,
1163
                                          _impl::SyncProgressNotifier::NotifierType direction)
1164
{
2,138✔
1165
    bool is_download = (direction == _impl::SyncProgressNotifier::NotifierType::download);
2,138✔
1166

1,026✔
1167
    m_completion_request_counter++;
2,138✔
1168
    m_completion_callbacks.emplace_hint(m_completion_callbacks.end(), m_completion_request_counter,
2,138✔
1169
                                        std::make_pair(direction, std::move(callback)));
2,138✔
1170
    // If the state is inactive then just store the callback and return. The callback will get
1,026✔
1171
    // re-registered with the underlying session if/when the session ever becomes active again.
1,026✔
1172
    if (!m_session) {
2,138✔
1173
        return;
199✔
1174
    }
199✔
1175

934✔
1176
    auto waiter = is_download ? &sync::Session::async_wait_for_download_completion
1,939✔
1177
                              : &sync::Session::async_wait_for_upload_completion;
1,438✔
1178

934✔
1179
    (m_session.get()->*waiter)([weak_self = weak_from_this(), id = m_completion_request_counter](Status status) {
1,939✔
1180
        auto self = weak_self.lock();
1,939✔
1181
        if (!self)
1,939✔
1182
            return;
39✔
1183
        util::CheckedUniqueLock lock(self->m_state_mutex);
1,900✔
1184
        auto callback_node = self->m_completion_callbacks.extract(id);
1,900✔
1185
        lock.unlock();
1,900✔
1186
        if (callback_node) {
1,900✔
1187
            callback_node.mapped().second(std::move(status));
1,723✔
1188
        }
1,723✔
1189
    });
1,900✔
1190
}
1,939✔
1191

1192
void SyncSession::wait_for_upload_completion(util::UniqueFunction<void(Status)>&& callback)
1193
{
819✔
1194
    util::CheckedUniqueLock lock(m_state_mutex);
819✔
1195
    add_completion_callback(std::move(callback), ProgressDirection::upload);
819✔
1196
}
819✔
1197

1198
void SyncSession::wait_for_download_completion(util::UniqueFunction<void(Status)>&& callback)
1199
{
980✔
1200
    util::CheckedUniqueLock lock(m_state_mutex);
980✔
1201
    add_completion_callback(std::move(callback), ProgressDirection::download);
980✔
1202
}
980✔
1203

1204
uint64_t SyncSession::register_progress_notifier(std::function<ProgressNotifierCallback>&& notifier,
1205
                                                 ProgressDirection direction, bool is_streaming)
1206
{
4✔
1207
    return m_progress_notifier.register_callback(std::move(notifier), direction, is_streaming);
4✔
1208
}
4✔
1209

1210
void SyncSession::unregister_progress_notifier(uint64_t token)
1211
{
4✔
1212
    m_progress_notifier.unregister_callback(token);
4✔
1213
}
4✔
1214

1215
uint64_t SyncSession::register_connection_change_callback(std::function<ConnectionStateChangeCallback>&& callback)
1216
{
6✔
1217
    return m_connection_change_notifier.add_callback(std::move(callback));
6✔
1218
}
6✔
1219

1220
void SyncSession::unregister_connection_change_callback(uint64_t token)
1221
{
2✔
1222
    m_connection_change_notifier.remove_callback(token);
2✔
1223
}
2✔
1224

1225
SyncSession::~SyncSession() {}
1,379✔
1226

1227
SyncSession::State SyncSession::state() const
1228
{
13,232✔
1229
    util::CheckedUniqueLock lock(m_state_mutex);
13,232✔
1230
    return m_state;
13,232✔
1231
}
13,232✔
1232

1233
SyncSession::ConnectionState SyncSession::connection_state() const
1234
{
2,565✔
1235
    util::CheckedUniqueLock lock(m_connection_state_mutex);
2,565✔
1236
    return m_connection_state;
2,565✔
1237
}
2,565✔
1238

1239
std::string const& SyncSession::path() const
1240
{
1,561✔
1241
    return m_db->get_path();
1,561✔
1242
}
1,561✔
1243

1244
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_flx_subscription_store()
1245
{
11,174,933✔
1246
    util::CheckedLockGuard lock(m_state_mutex);
11,174,933✔
1247
    return m_flx_subscription_store;
11,174,933✔
1248
}
11,174,933✔
1249

1250
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_subscription_store_base()
1251
{
2✔
1252
    util::CheckedLockGuard lock(m_state_mutex);
2✔
1253
    return m_subscription_store_base;
2✔
1254
}
2✔
1255

1256
sync::SaltedFileIdent SyncSession::get_file_ident() const
1257
{
142✔
1258
    auto repl = m_db->get_replication();
142✔
1259
    REALM_ASSERT(repl);
142✔
1260
    REALM_ASSERT(dynamic_cast<sync::ClientReplication*>(repl));
142✔
1261

71✔
1262
    sync::SaltedFileIdent ret;
142✔
1263
    sync::version_type unused_version;
142✔
1264
    sync::SyncProgress unused_progress;
142✔
1265
    static_cast<sync::ClientReplication*>(repl)->get_history().get_status(unused_version, ret, unused_progress);
142✔
1266
    return ret;
142✔
1267
}
142✔
1268

1269
std::string SyncSession::get_appservices_connection_id() const
1270
{
20✔
1271
    util::CheckedLockGuard lk(m_state_mutex);
20✔
1272
    if (!m_session) {
20✔
1273
        return {};
×
1274
    }
×
1275
    return m_session->get_appservices_connection_id();
20✔
1276
}
20✔
1277

1278
void SyncSession::update_configuration(SyncConfig new_config)
1279
{
8✔
1280
    while (true) {
18✔
1281
        util::CheckedUniqueLock state_lock(m_state_mutex);
18✔
1282
        if (m_state != State::Inactive && m_state != State::Paused) {
18✔
1283
            // Changing the state releases the lock, which means that by the
5✔
1284
            // time we reacquire the lock the state may have changed again
5✔
1285
            // (either due to one of the callbacks being invoked or another
5✔
1286
            // thread coincidentally doing something). We just attempt to keep
5✔
1287
            // switching it to inactive until it stays there.
5✔
1288
            become_inactive(std::move(state_lock));
10✔
1289
            continue;
10✔
1290
        }
10✔
1291

4✔
1292
        util::CheckedUniqueLock config_lock(m_config_mutex);
8✔
1293
        REALM_ASSERT(m_state == State::Inactive || m_state == State::Paused);
8!
1294
        REALM_ASSERT(!m_session);
8✔
1295
        REALM_ASSERT(m_config.sync_config->user == new_config.user);
8✔
1296
        // Since this is used for testing purposes only, just update the current sync_config
4✔
1297
        m_config.sync_config = std::make_shared<SyncConfig>(std::move(new_config));
8✔
1298
        break;
8✔
1299
    }
8✔
1300
    revive_if_needed();
8✔
1301
}
8✔
1302

1303
void SyncSession::apply_sync_config_after_migration_or_rollback()
1304
{
26✔
1305
    // Migration state changed - Update the configuration to
13✔
1306
    // match the new sync mode.
13✔
1307
    util::CheckedLockGuard cfg_lock(m_config_mutex);
26✔
1308
    if (!m_migrated_sync_config)
26✔
1309
        return;
2✔
1310

12✔
1311
    m_config.sync_config = m_migrated_sync_config;
24✔
1312
    m_migrated_sync_config.reset();
24✔
1313
}
24✔
1314

1315
void SyncSession::save_sync_config_after_migration_or_rollback()
1316
{
28✔
1317
    util::CheckedLockGuard cfg_lock(m_config_mutex);
28✔
1318
    m_migrated_sync_config = m_migration_store->convert_sync_config(m_original_sync_config);
28✔
1319
}
28✔
1320

1321
void SyncSession::update_subscription_store(bool flx_sync_requested, std::optional<sync::SubscriptionSet> new_subs)
1322
{
26✔
1323
    util::CheckedUniqueLock lock(m_state_mutex);
26✔
1324

13✔
1325
    // The session should be closed before updating the FLX subscription store
13✔
1326
    REALM_ASSERT(!m_session);
26✔
1327

13✔
1328
    // If the subscription store exists and switching to PBS, then clear the store
13✔
1329
    auto& history = static_cast<sync::ClientReplication&>(*m_db->get_replication());
26✔
1330
    if (!flx_sync_requested) {
26✔
1331
        if (m_flx_subscription_store) {
8✔
1332
            // Empty the subscription store and cancel any pending subscription notification
4✔
1333
            // waiters
4✔
1334
            auto subscription_store = std::move(m_flx_subscription_store);
8✔
1335
            lock.unlock();
8✔
1336
            subscription_store->terminate();
8✔
1337
            auto tr = m_db->start_write();
8✔
1338
            history.set_write_validator_factory(nullptr);
8✔
1339
            tr->rollback();
8✔
1340
        }
8✔
1341
        return;
8✔
1342
    }
8✔
1343

9✔
1344
    if (m_flx_subscription_store)
18✔
1345
        return; // Using FLX and subscription store already exists
2✔
1346

8✔
1347
    // Going from PBS -> FLX (or one doesn't exist yet), create a new subscription store
8✔
1348
    create_subscription_store();
16✔
1349

8✔
1350
    std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
16✔
1351

8✔
1352
    // If migrated to FLX, create subscriptions in the local realm to cover the existing data.
8✔
1353
    // This needs to be done before setting the write validator to avoid NoSubscriptionForWrite errors.
8✔
1354
    if (new_subs) {
16✔
1355
        auto active_mut_sub = m_flx_subscription_store->get_active().make_mutable_copy();
16✔
1356
        active_mut_sub.import(std::move(*new_subs));
16✔
1357
        active_mut_sub.set_state(sync::SubscriptionSet::State::Complete);
16✔
1358
        active_mut_sub.commit();
16✔
1359
    }
16✔
1360

8✔
1361
    auto tr = m_db->start_write();
16✔
1362
    set_write_validator_factory(weak_sub_mgr);
16✔
1363
    tr->rollback();
16✔
1364
}
16✔
1365

1366
void SyncSession::create_subscription_store()
1367
{
434✔
1368
    REALM_ASSERT(!m_flx_subscription_store);
434✔
1369

217✔
1370
    // Create the main subscription store instance when this is first called - this will
217✔
1371
    // remain valid afterwards for the life of the SyncSession, but m_flx_subscription_store
217✔
1372
    // will be reset when rolling back to PBS after a client FLX migration
217✔
1373
    if (!m_subscription_store_base) {
434✔
1374
        m_subscription_store_base = sync::SubscriptionStore::create(m_db);
432✔
1375
    }
432✔
1376

217✔
1377
    // m_subscription_store_base is always around for the life of SyncSession, but the
217✔
1378
    // m_flx_subscription_store is set when using FLX.
217✔
1379
    m_flx_subscription_store = m_subscription_store_base;
434✔
1380
}
434✔
1381

1382
void SyncSession::set_write_validator_factory(std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr)
1383
{
434✔
1384
    auto& history = static_cast<sync::ClientReplication&>(*m_db->get_replication());
434✔
1385
    history.set_write_validator_factory(
434✔
1386
        [weak_sub_mgr](Transaction& tr) -> util::UniqueFunction<sync::SyncReplication::WriteValidator> {
4,878✔
1387
            auto sub_mgr = weak_sub_mgr.lock();
4,878✔
1388
            REALM_ASSERT_RELEASE(sub_mgr);
4,878✔
1389
            auto latest_sub_tables = sub_mgr->get_tables_for_latest(tr);
4,878✔
1390
            return [tables = std::move(latest_sub_tables)](const Table& table) {
2,817✔
1391
                if (table.get_table_type() != Table::Type::TopLevel) {
763✔
1392
                    return;
430✔
1393
                }
430✔
1394
                auto object_class_name = Group::table_name_to_class_name(table.get_name());
333✔
1395
                if (tables.find(object_class_name) == tables.end()) {
333✔
1396
                    throw NoSubscriptionForWrite(
2✔
1397
                        util::format("Cannot write to class %1 when no flexible sync subscription has been created.",
2✔
1398
                                     object_class_name));
2✔
1399
                }
2✔
1400
            };
333✔
1401
        });
4,878✔
1402
}
434✔
1403

1404
// Represents a reference to the SyncSession from outside of the sync subsystem.
1405
// We attempt to keep the SyncSession in an active state as long as it has an external reference.
1406
class SyncSession::ExternalReference {
1407
public:
1408
    ExternalReference(std::shared_ptr<SyncSession> session)
1409
        : m_session(std::move(session))
1410
    {
1,379✔
1411
    }
1,379✔
1412

1413
    ~ExternalReference()
1414
    {
1,379✔
1415
        m_session->did_drop_external_reference();
1,379✔
1416
    }
1,379✔
1417

1418
private:
1419
    std::shared_ptr<SyncSession> m_session;
1420
};
1421

1422
std::shared_ptr<SyncSession> SyncSession::external_reference()
1423
{
1,600✔
1424
    util::CheckedLockGuard lock(m_external_reference_mutex);
1,600✔
1425

713✔
1426
    if (auto external_reference = m_external_reference.lock())
1,600✔
1427
        return std::shared_ptr<SyncSession>(external_reference, this);
221✔
1428

603✔
1429
    auto external_reference = std::make_shared<ExternalReference>(shared_from_this());
1,379✔
1430
    m_external_reference = external_reference;
1,379✔
1431
    return std::shared_ptr<SyncSession>(external_reference, this);
1,379✔
1432
}
1,379✔
1433

1434
std::shared_ptr<SyncSession> SyncSession::existing_external_reference()
1435
{
2,238✔
1436
    util::CheckedLockGuard lock(m_external_reference_mutex);
2,238✔
1437

915✔
1438
    if (auto external_reference = m_external_reference.lock())
2,238✔
1439
        return std::shared_ptr<SyncSession>(external_reference, this);
857✔
1440

603✔
1441
    return nullptr;
1,381✔
1442
}
1,381✔
1443

1444
void SyncSession::did_drop_external_reference()
1445
{
1,379✔
1446
    util::CheckedUniqueLock lock1(m_state_mutex);
1,379✔
1447
    {
1,379✔
1448
        util::CheckedLockGuard lock2(m_external_reference_mutex);
1,379✔
1449

603✔
1450
        // If the session is being resurrected we should not close the session.
603✔
1451
        if (!m_external_reference.expired())
1,379✔
1452
            return;
×
1453
    }
1,379✔
1454

603✔
1455
    close(std::move(lock1));
1,379✔
1456
}
1,379✔
1457

1458
uint64_t SyncProgressNotifier::register_callback(std::function<ProgressNotifierCallback> notifier,
1459
                                                 NotifierType direction, bool is_streaming)
1460
{
48✔
1461
    util::UniqueFunction<void()> invocation;
48✔
1462
    uint64_t token_value = 0;
48✔
1463
    {
48✔
1464
        std::lock_guard<std::mutex> lock(m_mutex);
48✔
1465
        token_value = m_progress_notifier_token++;
48✔
1466
        NotifierPackage package{std::move(notifier), util::none, m_local_transaction_version, is_streaming,
48✔
1467
                                direction == NotifierType::download};
48✔
1468
        if (!m_current_progress) {
48✔
1469
            // Simply register the package, since we have no data yet.
6✔
1470
            m_packages.emplace(token_value, std::move(package));
12✔
1471
            return token_value;
12✔
1472
        }
12✔
1473
        bool skip_registration = false;
36✔
1474
        invocation = package.create_invocation(*m_current_progress, skip_registration);
36✔
1475
        if (skip_registration) {
36✔
1476
            token_value = 0;
10✔
1477
        }
10✔
1478
        else {
26✔
1479
            m_packages.emplace(token_value, std::move(package));
26✔
1480
        }
26✔
1481
    }
36✔
1482
    invocation();
36✔
1483
    return token_value;
36✔
1484
}
36✔
1485

1486
void SyncProgressNotifier::unregister_callback(uint64_t token)
1487
{
8✔
1488
    std::lock_guard<std::mutex> lock(m_mutex);
8✔
1489
    m_packages.erase(token);
8✔
1490
}
8✔
1491

1492
void SyncProgressNotifier::update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded, uint64_t uploadable,
1493
                                  uint64_t download_version, uint64_t snapshot_version)
1494
{
6,574✔
1495
    // Ignore progress messages from before we first receive a DOWNLOAD message
2,745✔
1496
    if (download_version == 0)
6,574✔
1497
        return;
2,839✔
1498

1,637✔
1499
    std::vector<util::UniqueFunction<void()>> invocations;
3,735✔
1500
    {
3,735✔
1501
        std::lock_guard<std::mutex> lock(m_mutex);
3,735✔
1502
        m_current_progress = Progress{uploadable, downloadable, uploaded, downloaded, snapshot_version};
3,735✔
1503

1,637✔
1504
        for (auto it = m_packages.begin(); it != m_packages.end();) {
3,801✔
1505
            bool should_delete = false;
66✔
1506
            invocations.emplace_back(it->second.create_invocation(*m_current_progress, should_delete));
66✔
1507
            it = should_delete ? m_packages.erase(it) : std::next(it);
57✔
1508
        }
66✔
1509
    }
3,735✔
1510
    // Run the notifiers only after we've released the lock.
1,637✔
1511
    for (auto& invocation : invocations)
3,735✔
1512
        invocation();
66✔
1513
}
3,735✔
1514

1515
void SyncProgressNotifier::set_local_version(uint64_t snapshot_version)
1516
{
7,831✔
1517
    std::lock_guard<std::mutex> lock(m_mutex);
7,831✔
1518
    m_local_transaction_version = snapshot_version;
7,831✔
1519
}
7,831✔
1520

1521
util::UniqueFunction<void()>
1522
SyncProgressNotifier::NotifierPackage::create_invocation(Progress const& current_progress, bool& is_expired)
1523
{
102✔
1524
    uint64_t transferred = is_download ? current_progress.downloaded : current_progress.uploaded;
83✔
1525
    uint64_t transferrable = is_download ? current_progress.downloadable : current_progress.uploadable;
83✔
1526
    if (!is_streaming) {
102✔
1527
        // If the sync client has not yet processed all of the local
35✔
1528
        // transactions then the uploadable data is incorrect and we should
35✔
1529
        // not invoke the callback
35✔
1530
        if (!is_download && snapshot_version > current_progress.snapshot_version)
70✔
1531
            return [] {};
2✔
1532

34✔
1533
        // The initial download size we get from the server is the uncompacted
34✔
1534
        // size, and so the download may complete before we actually receive
34✔
1535
        // that much data. When that happens, transferrable will drop and we
34✔
1536
        // need to use the new value instead of the captured one.
34✔
1537
        if (!captured_transferrable || *captured_transferrable > transferrable)
68✔
1538
            captured_transferrable = transferrable;
36✔
1539
        transferrable = *captured_transferrable;
68✔
1540
    }
68✔
1541

51✔
1542
    // A notifier is expired if at least as many bytes have been transferred
51✔
1543
    // as were originally considered transferrable.
51✔
1544
    is_expired = !is_streaming && transferred >= transferrable;
101✔
1545
    return [=, notifier = notifier] {
100✔
1546
        notifier(transferred, transferrable);
100✔
1547
    };
100✔
1548
}
102✔
1549

1550
uint64_t SyncSession::ConnectionChangeNotifier::add_callback(std::function<ConnectionStateChangeCallback> callback)
1551
{
6✔
1552
    std::lock_guard<std::mutex> lock(m_callback_mutex);
6✔
1553
    auto token = m_next_token++;
6✔
1554
    m_callbacks.push_back({std::move(callback), token});
6✔
1555
    return token;
6✔
1556
}
6✔
1557

1558
void SyncSession::ConnectionChangeNotifier::remove_callback(uint64_t token)
1559
{
2✔
1560
    Callback old;
2✔
1561
    {
2✔
1562
        std::lock_guard<std::mutex> lock(m_callback_mutex);
2✔
1563
        auto it = std::find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) {
2✔
1564
            return c.token == token;
2✔
1565
        });
2✔
1566
        if (it == end(m_callbacks)) {
2✔
1567
            return;
×
1568
        }
×
1569

1✔
1570
        size_t idx = distance(begin(m_callbacks), it);
2✔
1571
        if (m_callback_index != npos) {
2✔
1572
            if (m_callback_index >= idx)
×
1573
                --m_callback_index;
×
1574
        }
×
1575
        --m_callback_count;
2✔
1576

1✔
1577
        old = std::move(*it);
2✔
1578
        m_callbacks.erase(it);
2✔
1579
    }
2✔
1580
}
2✔
1581

1582
void SyncSession::ConnectionChangeNotifier::invoke_callbacks(ConnectionState old_state, ConnectionState new_state)
1583
{
4,931✔
1584
    std::unique_lock lock(m_callback_mutex);
4,931✔
1585
    m_callback_count = m_callbacks.size();
4,931✔
1586
    for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) {
4,935✔
1587
        // acquire a local reference to the callback so that removing the
2✔
1588
        // callback from within it can't result in a dangling pointer
2✔
1589
        auto cb = m_callbacks[m_callback_index].fn;
4✔
1590
        lock.unlock();
4✔
1591
        cb(old_state, new_state);
4✔
1592
        lock.lock();
4✔
1593
    }
4✔
1594
    m_callback_index = npos;
4,931✔
1595
}
4,931✔
1596

1597
util::Future<std::string> SyncSession::send_test_command(std::string body)
1598
{
26✔
1599
    util::CheckedLockGuard lk(m_state_mutex);
26✔
1600
    if (!m_session) {
26✔
1601
        return Status{ErrorCodes::RuntimeError, "Session doesn't exist to send test command on"};
×
1602
    }
×
1603

13✔
1604
    return m_session->send_test_command(std::move(body));
26✔
1605
}
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