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

realm / realm-core / jonathan.reams_2947

01 Dec 2023 08:08PM UTC coverage: 91.739% (+0.04%) from 91.695%
jonathan.reams_2947

Pull #7160

Evergreen

jbreams
allow handle_error to decide resumability
Pull Request #7160: Prevent resuming a session that has not been fully shut down

92428 of 169414 branches covered (0.0%)

315 of 349 new or added lines in 14 files covered. (90.26%)

80 existing lines in 14 files now uncovered.

232137 of 253041 relevant lines covered (91.74%)

6882826.18 hits per line

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

94.45
/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,719✔
88
    REALM_ASSERT(m_state != State::Active);
1,719✔
89
    m_state = State::Active;
1,719✔
90

772✔
91
    // First time the session becomes active, register a notification on the sentinel subscription set to restart the
772✔
92
    // session and update to native FLX.
772✔
93
    if (m_migration_sentinel_query_version) {
1,719✔
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

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

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

772✔
121
    for (auto& [id, callback_tuple] : callbacks_to_register) {
948✔
122
        add_completion_callback(std::move(callback_tuple.second), callback_tuple.first);
337✔
123
    }
337✔
124
}
1,719✔
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
{
72✔
134
    REALM_ASSERT(m_state != State::Dying);
72✔
135
    m_state = State::Dying;
72✔
136

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

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

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

679✔
160
    do_become_inactive(std::move(lock), status, cancel_subscription_notifications);
1,537✔
161
}
1,537✔
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,687✔
204
    // Manually set the disconnected state. Sync would also do this, but
754✔
205
    // since the underlying SyncSession object already have been destroyed,
754✔
206
    // we are not able to get the callback.
754✔
207
    util::CheckedUniqueLock connection_state_lock(m_connection_state_mutex);
1,687✔
208
    auto old_state = m_connection_state;
1,687✔
209
    auto new_state = m_connection_state = SyncSession::ConnectionState::Disconnected;
1,687✔
210
    connection_state_lock.unlock();
1,687✔
211

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

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

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

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

754✔
228
    if (status.is_ok())
1,687✔
229
        status = Status(ErrorCodes::OperationAborted, "Sync session became inactive");
1,584✔
230

754✔
231
    if (subscription_store && cancel_subscription_notifications) {
1,687✔
232
        subscription_store->notify_all_state_change_notifications(status);
473✔
233
    }
473✔
234

754✔
235
    // Inform any queued-up completion handlers that they were cancelled.
754✔
236
    for (auto& [id, callback] : waits)
1,687✔
237
        callback.second(status);
62✔
238
}
1,687✔
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,387✔
370
    REALM_ASSERT(m_config.sync_config);
1,387✔
371
    // we don't want the following configs enabled during a client reset
607✔
372
    m_config.scheduler = nullptr;
1,387✔
373
    m_config.audit_config = nullptr;
1,387✔
374

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

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

607✔
387
    // After a migration to FLX, if the user opens the realm with a flexible sync configuration, we need to first
607✔
388
    // upload any unsynced changes before updating to native FLX.
607✔
389
    // A subscription set is used as sentinel so we know when to stop uploading.
607✔
390
    // Note: Currently, a sentinel subscription set is always created even if there is nothing to upload.
607✔
391
    if (m_migration_store->is_migrated() && m_original_sync_config->flx_sync_requested) {
1,387✔
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,387✔
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
{
4✔
407
    shutdown_and_wait();
4✔
408
    util::CheckedLockGuard lk(m_state_mutex);
4✔
409
    m_sync_manager = nullptr;
4✔
410
}
4✔
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
            sync::SubscriptionSet active = local_subs_store->get_active();
46✔
514
            auto fresh_mut_sub = fresh_sub.make_mutable_copy();
46✔
515
            fresh_mut_sub.import(active);
46✔
516
            fresh_sub = fresh_mut_sub.commit();
46✔
517
        }
46✔
518
        fresh_sub.get_state_change_notification(sync::SubscriptionSet::State::Complete)
64✔
519
            .then([=, weak_self = weak_from_this()](sync::SubscriptionSet::State state) {
63✔
520
                if (server_requests_action != sync::ProtocolErrorInfo::Action::MigrateToFLX) {
62✔
521
                    return util::Future<sync::SubscriptionSet::State>::make_ready(state);
44✔
522
                }
44✔
523
                auto strong_self = weak_self.lock();
18✔
524
                if (!strong_self || !strong_self->m_migration_store->is_migration_in_progress()) {
18✔
525
                    return util::Future<sync::SubscriptionSet::State>::make_ready(state);
×
526
                }
×
527

9✔
528
                // fresh_sync_session is using a new realm file that doesn't have the migration_store info
9✔
529
                // so the query string from the local migration store will need to be provided
9✔
530
                auto query_string = strong_self->m_migration_store->get_query_string();
18✔
531
                REALM_ASSERT(query_string);
18✔
532
                // Create subscriptions in the fresh realm based on the schema instructions received in the bootstrap
9✔
533
                // message.
9✔
534
                fresh_sync_session->m_migration_store->create_subscriptions(*fresh_sub_store, *query_string);
18✔
535
                auto latest_subs = fresh_sub_store->get_latest();
18✔
536
                {
18✔
537
                    util::CheckedLockGuard lock(strong_self->m_state_mutex);
18✔
538
                    // Save a copy of the subscriptions so we add them to the local realm once the
9✔
539
                    // subscription store is created.
9✔
540
                    strong_self->m_active_subscriptions_after_migration = latest_subs;
18✔
541
                }
18✔
542

9✔
543
                return latest_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete);
18✔
544
            })
18✔
545
            .get_async([=, weak_self = weak_from_this()](StatusWith<sync::SubscriptionSet::State> s) {
64✔
546
                // Keep the sync session alive while it's downloading, but then close
32✔
547
                // it immediately
32✔
548
                fresh_sync_session->force_close();
64✔
549
                if (auto strong_self = weak_self.lock()) {
64✔
550
                    if (s.is_ok()) {
64✔
551
                        strong_self->handle_fresh_realm_downloaded(db, Status::OK(), server_requests_action);
62✔
552
                    }
62✔
553
                    else {
2✔
554
                        strong_self->handle_fresh_realm_downloaded(nullptr, s.get_status(), server_requests_action);
2✔
555
                    }
2✔
556
                }
64✔
557
            });
64✔
558
    }
64✔
559
    else { // pbs
102✔
560
        fresh_sync_session->wait_for_download_completion([=, weak_self = weak_from_this()](Status s) {
102✔
561
            // Keep the sync session alive while it's downloading, but then close
51✔
562
            // it immediately
51✔
563
            fresh_sync_session->force_close();
102✔
564
            if (auto strong_self = weak_self.lock()) {
102✔
565
                strong_self->handle_fresh_realm_downloaded(db, s, server_requests_action);
102✔
566
            }
102✔
567
        });
102✔
568
    }
102✔
569
    fresh_sync_session->revive_if_needed();
166✔
570
}
166✔
571

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

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

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

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

634
void SyncSession::OnlyForTesting::handle_error(SyncSession& session, sync::SessionErrorInfo&& error)
635
{
16✔
636
    session.handle_error(std::move(error));
16✔
637
}
16✔
638

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

295✔
649
    switch (error.server_requests_action) {
568✔
NEW
650
        case sync::ProtocolErrorInfo::Action::NoAction:
✔
651
            REALM_UNREACHABLE();
652
        case sync::ProtocolErrorInfo::Action::ApplicationBug:
25✔
653
            [[fallthrough]];
25✔
654
        case sync::ProtocolErrorInfo::Action::ProtocolViolation:
31✔
655
            next_state = NextStateAfterError::inactive;
31✔
656
            break;
31✔
657
        case sync::ProtocolErrorInfo::Action::Warning:
32✔
658
            break; // not fatal, but should be bubbled up to the user below.
32✔
659
        case sync::ProtocolErrorInfo::Action::Transient:
233✔
660
            // Not real errors, don't need to be reported to the binding.
129✔
661
            return;
233✔
662
        case sync::ProtocolErrorInfo::Action::BackupThenDeleteRealm:
46✔
663
            next_state = NextStateAfterError::inactive;
46✔
664
            delete_file = ShouldBackup::yes;
46✔
665
            break;
46✔
666
        case sync::ProtocolErrorInfo::Action::DeleteRealm:
11✔
NEW
667
            next_state = NextStateAfterError::inactive;
×
NEW
668
            delete_file = ShouldBackup::no;
×
NEW
669
            break;
×
670
        case sync::ProtocolErrorInfo::Action::ClientReset:
168✔
671
            [[fallthrough]];
168✔
672
        case sync::ProtocolErrorInfo::Action::ClientResetNoRecovery:
172✔
673
            switch (config(&SyncConfig::client_resync_mode)) {
172✔
674
                case ClientResyncMode::Manual:
24✔
675
                    next_state = NextStateAfterError::inactive;
24✔
676
                    delete_file = ShouldBackup::yes;
24✔
677
                    break;
24✔
678
                case ClientResyncMode::DiscardLocal:
78✔
679
                    [[fallthrough]];
78✔
680
                case ClientResyncMode::RecoverOrDiscard:
90✔
681
                    [[fallthrough]];
90✔
682
                case ClientResyncMode::Recover:
148✔
683
                    download_fresh_realm(error.server_requests_action);
148✔
684
                    return; // do not propgate the error to the user at this point
148✔
685
            }
24✔
686
            break;
24✔
687
        case sync::ProtocolErrorInfo::Action::MigrateToFLX:
21✔
688
            // Should not receive this error if original sync config is FLX
9✔
689
            REALM_ASSERT(!m_original_sync_config->flx_sync_requested);
18✔
690
            REALM_ASSERT(error.migration_query_string && !error.migration_query_string->empty());
18✔
691
            // Original config was PBS, migrating to FLX
9✔
692
            m_migration_store->migrate_to_flx(*error.migration_query_string, 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✔
NEW
701
                throw LogicError(ErrorCodes::InvalidServerResponse,
×
NEW
702
                                 "Received 'RevertToPBS' from server after rollback while client is natively "
×
NEW
703
                                 "using FLX - expected 'SwitchToPBS'");
×
NEW
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✔
NEW
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✔
NEW
721
            break;
×
722
        case sync::ProtocolErrorInfo::Action::LogOutUser:
2✔
723
            next_state = NextStateAfterError::inactive;
2✔
724
            log_out_user = true;
2✔
725
            break;
2✔
726
    }
135✔
727

66✔
728
    util::CheckedUniqueLock lock(m_state_mutex);
135✔
729
    SyncError sync_error{error.status, error.is_fatal, error.log_url, std::move(error.compensating_writes)};
135✔
730
    // `action` is used over `shouldClientReset` and `isRecoveryModeDisabled`.
66✔
731
    sync_error.server_requests_action = error.server_requests_action;
135✔
732
    sync_error.is_unrecognized_by_client = unrecognized_by_client;
135✔
733

66✔
734
    if (delete_file)
135✔
735
        update_error_and_mark_file_for_deletion(sync_error, *delete_file);
70✔
736

66✔
737
    if (m_state == State::Dying && error.is_fatal) {
135✔
738
        become_inactive(std::move(lock), sync_error.status);
2✔
739
        return;
2✔
740
    }
2✔
741

65✔
742
    // Don't bother invoking m_config.error_handler if the sync is inactive.
65✔
743
    // It does not make sense to call the handler when the session is closed.
65✔
744
    if (m_state == State::Inactive || m_state == State::Paused) {
133✔
745
        return;
×
746
    }
×
747

65✔
748
    switch (next_state) {
133✔
749
        case NextStateAfterError::none:
30✔
750
            if (config(&SyncConfig::cancel_waits_on_nonfatal_error)) {
30✔
751
                cancel_pending_waits(std::move(lock), sync_error.status); // unlocks the mutex
×
752
            }
×
753
            break;
30✔
754
        case NextStateAfterError::inactive: {
101✔
755
            m_session->mark_unresumable();
101✔
756
            become_inactive(std::move(lock), sync_error.status);
101✔
757
            break;
101✔
758
        }
×
759
        case NextStateAfterError::error: {
2✔
760
            cancel_pending_waits(std::move(lock), sync_error.status);
2✔
761
            break;
2✔
762
        }
133✔
763
    }
133✔
764

65✔
765
    if (log_out_user) {
133✔
766
        if (auto u = user())
2✔
767
            u->log_out();
2✔
768
    }
2✔
769

65✔
770
    if (auto error_handler = config(&SyncConfig::error_handler)) {
133✔
771
        error_handler(shared_from_this(), std::move(sync_error));
133✔
772
    }
133✔
773
}
133✔
774

775
void SyncSession::cancel_pending_waits(util::CheckedUniqueLock lock, Status error)
776
{
18✔
777
    CompletionCallbacks callbacks;
18✔
778
    std::swap(callbacks, m_completion_callbacks);
18✔
779

9✔
780
    // Inform any waiters on pending subscription states that they were cancelled
9✔
781
    if (m_flx_subscription_store) {
18✔
782
        auto subscription_store = m_flx_subscription_store;
2✔
783
        m_state_mutex.unlock(lock);
2✔
784
        subscription_store->notify_all_state_change_notifications(error);
2✔
785
    }
2✔
786
    else {
16✔
787
        m_state_mutex.unlock(lock);
16✔
788
    }
16✔
789

9✔
790
    // Inform any queued-up completion handlers that they were cancelled.
9✔
791
    for (auto& [id, callback] : callbacks)
18✔
792
        callback.second(error);
14✔
793
}
18✔
794

795
void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded,
796
                                         uint64_t uploadable, uint64_t download_version, uint64_t snapshot_version)
797
{
6,502✔
798
    m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, download_version, snapshot_version);
6,502✔
799
}
6,502✔
800

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

79✔
807
    sync::Session::Config::ClientReset config;
158✔
808
    config.mode = sync_config->client_resync_mode;
158✔
809
    config.fresh_copy = std::move(fresh_copy);
158✔
810
    config.recovery_is_allowed = recovery_is_allowed;
158✔
811

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

66✔
818
    RealmConfig realm_config = base_config;
132✔
819
    realm_config.sync_config = std::make_shared<SyncConfig>(*sync_config); // deep copy
132✔
820
    realm_config.scheduler = util::Scheduler::make_dummy();
132✔
821

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

66✔
848
    return config;
132✔
849
}
132✔
850

851
void SyncSession::create_sync_session()
852
{
1,717✔
853
    if (m_session)
1,717✔
854
        return;
×
855

771✔
856
    util::CheckedLockGuard config_lock(m_config_mutex);
1,717✔
857

771✔
858
    REALM_ASSERT(m_config.sync_config);
1,717✔
859
    SyncConfig& sync_config = *m_config.sync_config;
1,717✔
860
    REALM_ASSERT(sync_config.user);
1,717✔
861

771✔
862
    sync::Session::Config session_config;
1,717✔
863
    session_config.signed_user_token = sync_config.user->access_token();
1,717✔
864
    session_config.user_id = sync_config.user->identity();
1,717✔
865
    session_config.realm_identifier = sync_config.partition_value;
1,717✔
866
    session_config.verify_servers_ssl_certificate = sync_config.client_validate_ssl;
1,717✔
867
    session_config.ssl_trust_certificate_path = sync_config.ssl_trust_certificate_path;
1,717✔
868
    session_config.ssl_verify_callback = sync_config.ssl_verify_callback;
1,717✔
869
    session_config.proxy_config = sync_config.proxy_config;
1,717✔
870
    session_config.simulate_integration_error = sync_config.simulate_integration_error;
1,717✔
871
    session_config.flx_bootstrap_batch_size_bytes = sync_config.flx_bootstrap_batch_size_bytes;
1,717✔
872
    session_config.session_reason =
1,717✔
873
        client_reset::is_fresh_path(m_config.path) ? sync::SessionReason::ClientReset : sync::SessionReason::Sync;
1,638✔
874

771✔
875
    if (sync_config.on_sync_client_event_hook) {
1,717✔
876
        session_config.on_sync_client_event_hook = [hook = sync_config.on_sync_client_event_hook,
62✔
877
                                                    anchor = weak_from_this()](const SyncClientHookData& data) {
478✔
878
            return hook(anchor, data);
478✔
879
        };
478✔
880
    }
62✔
881

771✔
882
    {
1,717✔
883
        std::string sync_route = m_sync_manager->sync_route();
1,717✔
884

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

771✔
895
    if (sync_config.authorization_header_name) {
1,717✔
896
        session_config.authorization_header_name = *sync_config.authorization_header_name;
×
897
    }
×
898
    session_config.custom_http_headers = sync_config.custom_http_headers;
1,717✔
899

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

771✔
911
    m_session = m_client.make_session(m_db, m_flx_subscription_store, m_migration_store, std::move(session_config));
1,717✔
912

771✔
913
    std::weak_ptr<SyncSession> weak_self = weak_from_this();
1,717✔
914

771✔
915
    // Set up the wrapped progress handler callback
771✔
916
    m_session->set_progress_handler([weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable,
1,717✔
917
                                                uint_fast64_t uploaded, uint_fast64_t uploadable,
1,717✔
918
                                                uint_fast64_t progress_version, uint_fast64_t snapshot_version) {
6,698✔
919
        if (auto self = weak_self.lock()) {
6,698✔
920
            self->handle_progress_update(downloaded, downloadable, uploaded, uploadable, progress_version,
6,502✔
921
                                         snapshot_version);
6,502✔
922
        }
6,502✔
923
    });
6,698✔
924

771✔
925
    // Sets up the connection state listener. This callback is used for both reporting errors as well as changes to
771✔
926
    // the connection state.
771✔
927
    m_session->set_connection_state_change_listener(
1,717✔
928
        [weak_self](sync::ConnectionState state, util::Optional<sync::SessionErrorInfo> error) {
4,194✔
929
            // If the OS SyncSession object is destroyed, we ignore any events from the underlying Session as there is
1,984✔
930
            // nothing useful we can do with them.
1,984✔
931
            auto self = weak_self.lock();
4,194✔
932
            if (!self) {
4,194✔
933
                return;
23✔
934
            }
23✔
935
            using cs = sync::ConnectionState;
4,171✔
936
            ConnectionState new_state = [&] {
4,171✔
937
                switch (state) {
4,171✔
938
                    case cs::disconnected:
514✔
939
                        return ConnectionState::Disconnected;
514✔
940
                    case cs::connecting:
1,866✔
941
                        return ConnectionState::Connecting;
1,866✔
942
                    case cs::connected:
1,791✔
943
                        return ConnectionState::Connected;
1,791✔
944
                }
×
945
                REALM_UNREACHABLE();
946
            }();
×
947
            util::CheckedUniqueLock lock(self->m_connection_state_mutex);
4,171✔
948
            auto old_state = self->m_connection_state;
4,171✔
949
            self->m_connection_state = new_state;
4,171✔
950
            lock.unlock();
4,171✔
951

1,979✔
952
            if (old_state != new_state) {
4,171✔
953
                self->m_connection_change_notifier.invoke_callbacks(old_state, new_state);
4,133✔
954
            }
4,133✔
955

1,979✔
956
            if (error) {
4,171✔
957
                self->handle_error(std::move(*error));
540✔
958
            }
540✔
959
        });
4,171✔
960
}
1,717✔
961

962
void SyncSession::nonsync_transact_notify(sync::version_type version)
963
{
8,030✔
964
    m_progress_notifier.set_local_version(version);
8,030✔
965

3,913✔
966
    util::CheckedUniqueLock lock(m_state_mutex);
8,030✔
967
    switch (m_state) {
8,030✔
968
        case State::Active:
7,672✔
969
        case State::WaitingForAccessToken:
7,673✔
970
            if (m_session) {
7,673✔
971
                m_session->nonsync_transact_notify(version);
7,671✔
972
            }
7,671✔
973
            break;
7,673✔
974
        case State::Dying:
3,766✔
975
        case State::Inactive:
234✔
976
        case State::Paused:
357✔
977
            break;
357✔
978
    }
8,030✔
979
}
8,030✔
980

981
void SyncSession::revive_if_needed()
982
{
2,048✔
983
    util::CheckedUniqueLock lock(m_state_mutex);
2,048✔
984
    switch (m_state) {
2,048✔
985
        case State::Active:
474✔
986
        case State::WaitingForAccessToken:
474✔
987
        case State::Paused:
477✔
988
            return;
477✔
989
        case State::Dying:
699✔
990
        case State::Inactive:
1,571✔
991
            do_revive(std::move(lock));
1,571✔
992
            break;
1,571✔
993
    }
2,048✔
994
}
2,048✔
995

996
void SyncSession::handle_reconnect()
997
{
2✔
998
    util::CheckedUniqueLock lock(m_state_mutex);
2✔
999
    switch (m_state) {
2✔
1000
        case State::Active:
2✔
1001
            m_session->cancel_reconnect_delay();
2✔
1002
            break;
2✔
1003
        case State::Dying:
✔
1004
        case State::Inactive:
✔
1005
        case State::WaitingForAccessToken:
✔
1006
        case State::Paused:
✔
1007
            break;
×
1008
    }
2✔
1009
}
2✔
1010

1011
void SyncSession::force_close()
1012
{
239✔
1013
    util::CheckedUniqueLock lock(m_state_mutex);
239✔
1014
    switch (m_state) {
239✔
1015
        case State::Active:
222✔
1016
        case State::Dying:
222✔
1017
        case State::WaitingForAccessToken:
225✔
1018
            become_inactive(std::move(lock));
225✔
1019
            break;
225✔
1020
        case State::Inactive:
107✔
1021
        case State::Paused:
14✔
1022
            break;
14✔
1023
    }
239✔
1024
}
239✔
1025

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

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

1056
void SyncSession::do_revive(util::CheckedUniqueLock&& lock)
1057
{
1,719✔
1058
    auto u = user();
1,719✔
1059
    if (!u || !u->access_token_refresh_required()) {
1,719✔
1060
        become_active();
1,701✔
1061
        m_state_mutex.unlock(lock);
1,701✔
1062
        return;
1,701✔
1063
    }
1,701✔
1064

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

1074
void SyncSession::close()
1075
{
100✔
1076
    util::CheckedUniqueLock lock(m_state_mutex);
100✔
1077
    close(std::move(lock));
100✔
1078
}
100✔
1079

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

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

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

1150
void SyncSession::initiate_access_token_refresh()
1151
{
20✔
1152
    if (auto session_user = user()) {
20✔
1153
        session_user->refresh_custom_data(handle_refresh(shared_from_this(), false));
20✔
1154
    }
20✔
1155
}
20✔
1156

1157
void SyncSession::add_completion_callback(util::UniqueFunction<void(Status)> callback,
1158
                                          _impl::SyncProgressNotifier::NotifierType direction)
1159
{
2,146✔
1160
    bool is_download = (direction == _impl::SyncProgressNotifier::NotifierType::download);
2,146✔
1161

1,030✔
1162
    m_completion_request_counter++;
2,146✔
1163
    m_completion_callbacks.emplace_hint(m_completion_callbacks.end(), m_completion_request_counter,
2,146✔
1164
                                        std::make_pair(direction, std::move(callback)));
2,146✔
1165
    // If the state is inactive then just store the callback and return. The callback will get
1,030✔
1166
    // re-registered with the underlying session if/when the session ever becomes active again.
1,030✔
1167
    if (!m_session) {
2,146✔
1168
        return;
199✔
1169
    }
199✔
1170

938✔
1171
    auto waiter = is_download ? &sync::Session::async_wait_for_download_completion
1,947✔
1172
                              : &sync::Session::async_wait_for_upload_completion;
1,445✔
1173

938✔
1174
    (m_session.get()->*waiter)([weak_self = weak_from_this(), id = m_completion_request_counter](Status status) {
1,947✔
1175
        auto self = weak_self.lock();
1,947✔
1176
        if (!self)
1,947✔
1177
            return;
36✔
1178
        util::CheckedUniqueLock lock(self->m_state_mutex);
1,911✔
1179
        auto callback_node = self->m_completion_callbacks.extract(id);
1,911✔
1180
        lock.unlock();
1,911✔
1181
        if (callback_node) {
1,911✔
1182
            callback_node.mapped().second(std::move(status));
1,733✔
1183
        }
1,733✔
1184
    });
1,911✔
1185
}
1,947✔
1186

1187
void SyncSession::wait_for_upload_completion(util::UniqueFunction<void(Status)>&& callback)
1188
{
823✔
1189
    util::CheckedUniqueLock lock(m_state_mutex);
823✔
1190
    add_completion_callback(std::move(callback), ProgressDirection::upload);
823✔
1191
}
823✔
1192

1193
void SyncSession::wait_for_download_completion(util::UniqueFunction<void(Status)>&& callback)
1194
{
986✔
1195
    util::CheckedUniqueLock lock(m_state_mutex);
986✔
1196
    add_completion_callback(std::move(callback), ProgressDirection::download);
986✔
1197
}
986✔
1198

1199
uint64_t SyncSession::register_progress_notifier(std::function<ProgressNotifierCallback>&& notifier,
1200
                                                 ProgressDirection direction, bool is_streaming)
1201
{
4✔
1202
    return m_progress_notifier.register_callback(std::move(notifier), direction, is_streaming);
4✔
1203
}
4✔
1204

1205
void SyncSession::unregister_progress_notifier(uint64_t token)
1206
{
4✔
1207
    m_progress_notifier.unregister_callback(token);
4✔
1208
}
4✔
1209

1210
uint64_t SyncSession::register_connection_change_callback(std::function<ConnectionStateChangeCallback>&& callback)
1211
{
6✔
1212
    return m_connection_change_notifier.add_callback(std::move(callback));
6✔
1213
}
6✔
1214

1215
void SyncSession::unregister_connection_change_callback(uint64_t token)
1216
{
2✔
1217
    m_connection_change_notifier.remove_callback(token);
2✔
1218
}
2✔
1219

1220
SyncSession::~SyncSession() {}
1,387✔
1221

1222
SyncSession::State SyncSession::state() const
1223
{
14,843✔
1224
    util::CheckedUniqueLock lock(m_state_mutex);
14,843✔
1225
    return m_state;
14,843✔
1226
}
14,843✔
1227

1228
SyncSession::ConnectionState SyncSession::connection_state() const
1229
{
2,594✔
1230
    util::CheckedUniqueLock lock(m_connection_state_mutex);
2,594✔
1231
    return m_connection_state;
2,594✔
1232
}
2,594✔
1233

1234
std::string const& SyncSession::path() const
1235
{
1,563✔
1236
    return m_db->get_path();
1,563✔
1237
}
1,563✔
1238

1239
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_flx_subscription_store()
1240
{
12,161,480✔
1241
    util::CheckedLockGuard lock(m_state_mutex);
12,161,480✔
1242
    return m_flx_subscription_store;
12,161,480✔
1243
}
12,161,480✔
1244

1245
std::shared_ptr<sync::SubscriptionStore> SyncSession::get_subscription_store_base()
1246
{
2✔
1247
    util::CheckedLockGuard lock(m_state_mutex);
2✔
1248
    return m_subscription_store_base;
2✔
1249
}
2✔
1250

1251
sync::SaltedFileIdent SyncSession::get_file_ident() const
1252
{
138✔
1253
    auto repl = m_db->get_replication();
138✔
1254
    REALM_ASSERT(repl);
138✔
1255
    REALM_ASSERT(dynamic_cast<sync::ClientReplication*>(repl));
138✔
1256

69✔
1257
    sync::SaltedFileIdent ret;
138✔
1258
    sync::version_type unused_version;
138✔
1259
    sync::SyncProgress unused_progress;
138✔
1260
    static_cast<sync::ClientReplication*>(repl)->get_history().get_status(unused_version, ret, unused_progress);
138✔
1261
    return ret;
138✔
1262
}
138✔
1263

1264
std::string SyncSession::get_appservices_connection_id() const
1265
{
20✔
1266
    util::CheckedLockGuard lk(m_state_mutex);
20✔
1267
    if (!m_session) {
20✔
1268
        return {};
×
1269
    }
×
1270
    return m_session->get_appservices_connection_id();
20✔
1271
}
20✔
1272

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

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

1298
void SyncSession::apply_sync_config_after_migration_or_rollback()
1299
{
26✔
1300
    // Migration state changed - Update the configuration to
13✔
1301
    // match the new sync mode.
13✔
1302
    util::CheckedLockGuard cfg_lock(m_config_mutex);
26✔
1303
    if (!m_migrated_sync_config)
26✔
1304
        return;
2✔
1305

12✔
1306
    m_config.sync_config = m_migrated_sync_config;
24✔
1307
    m_migrated_sync_config.reset();
24✔
1308
}
24✔
1309

1310
void SyncSession::save_sync_config_after_migration_or_rollback()
1311
{
28✔
1312
    util::CheckedLockGuard cfg_lock(m_config_mutex);
28✔
1313
    m_migrated_sync_config = m_migration_store->convert_sync_config(m_original_sync_config);
28✔
1314
}
28✔
1315

1316
void SyncSession::update_subscription_store(bool flx_sync_requested)
1317
{
26✔
1318
    util::CheckedUniqueLock lock(m_state_mutex);
26✔
1319

13✔
1320
    // The session should be closed before updating the FLX subscription store
13✔
1321
    REALM_ASSERT(!m_session);
26✔
1322

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

9✔
1339
    if (m_flx_subscription_store)
18✔
1340
        return; // Using FLX and subscription store already exists
2✔
1341

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

8✔
1345
    std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr(m_flx_subscription_store);
16✔
1346
    lock.unlock();
16✔
1347

8✔
1348
    // If migrated to FLX, create subscriptions in the local realm to cover the existing data.
8✔
1349
    // This needs to be done before setting the write validator to avoid NoSubscriptionForWrite errors.
8✔
1350
    make_active_subscription_set();
16✔
1351

8✔
1352
    auto tr = m_db->start_write();
16✔
1353
    set_write_validator_factory(weak_sub_mgr);
16✔
1354
    tr->rollback();
16✔
1355
}
16✔
1356

1357
void SyncSession::create_subscription_store()
1358
{
442✔
1359
    REALM_ASSERT(!m_flx_subscription_store);
442✔
1360

221✔
1361
    // Create the main subscription store instance when this is first called - this will
221✔
1362
    // remain valid afterwards for the life of the SyncSession, but m_flx_subscription_store
221✔
1363
    // will be reset when rolling back to PBS after a client FLX migration
221✔
1364
    if (!m_subscription_store_base) {
442✔
1365
        m_subscription_store_base = sync::SubscriptionStore::create(m_db);
440✔
1366
    }
440✔
1367

221✔
1368
    // m_subscription_store_base is always around for the life of SyncSession, but the
221✔
1369
    // m_flx_subscription_store is set when using FLX.
221✔
1370
    m_flx_subscription_store = m_subscription_store_base;
442✔
1371
}
442✔
1372

1373
void SyncSession::set_write_validator_factory(std::weak_ptr<sync::SubscriptionStore> weak_sub_mgr)
1374
{
442✔
1375
    auto& history = static_cast<sync::ClientReplication&>(*m_db->get_replication());
442✔
1376
    history.set_write_validator_factory(
442✔
1377
        [weak_sub_mgr](Transaction& tr) -> util::UniqueFunction<sync::SyncReplication::WriteValidator> {
5,094✔
1378
            auto sub_mgr = weak_sub_mgr.lock();
5,094✔
1379
            REALM_ASSERT_RELEASE(sub_mgr);
5,094✔
1380
            auto latest_sub_tables = sub_mgr->get_tables_for_latest(tr);
5,094✔
1381
            return [tables = std::move(latest_sub_tables)](const Table& table) {
2,954✔
1382
                if (table.get_table_type() != Table::Type::TopLevel) {
819✔
1383
                    return;
430✔
1384
                }
430✔
1385
                auto object_class_name = Group::table_name_to_class_name(table.get_name());
389✔
1386
                if (tables.find(object_class_name) == tables.end()) {
389✔
1387
                    throw NoSubscriptionForWrite(
2✔
1388
                        util::format("Cannot write to class %1 when no flexible sync subscription has been created.",
2✔
1389
                                     object_class_name));
2✔
1390
                }
2✔
1391
            };
389✔
1392
        });
5,094✔
1393
}
442✔
1394

1395
// Represents a reference to the SyncSession from outside of the sync subsystem.
1396
// We attempt to keep the SyncSession in an active state as long as it has an external reference.
1397
class SyncSession::ExternalReference {
1398
public:
1399
    ExternalReference(std::shared_ptr<SyncSession> session)
1400
        : m_session(std::move(session))
1401
    {
1,388✔
1402
    }
1,388✔
1403

1404
    ~ExternalReference()
1405
    {
1,388✔
1406
        m_session->did_drop_external_reference();
1,388✔
1407
    }
1,388✔
1408

1409
private:
1410
    std::shared_ptr<SyncSession> m_session;
1411
};
1412

1413
std::shared_ptr<SyncSession> SyncSession::external_reference()
1414
{
1,607✔
1415
    util::CheckedLockGuard lock(m_external_reference_mutex);
1,607✔
1416

717✔
1417
    if (auto external_reference = m_external_reference.lock())
1,607✔
1418
        return std::shared_ptr<SyncSession>(external_reference, this);
219✔
1419

608✔
1420
    auto external_reference = std::make_shared<ExternalReference>(shared_from_this());
1,388✔
1421
    m_external_reference = external_reference;
1,388✔
1422
    return std::shared_ptr<SyncSession>(external_reference, this);
1,388✔
1423
}
1,388✔
1424

1425
std::shared_ptr<SyncSession> SyncSession::existing_external_reference()
1426
{
2,276✔
1427
    util::CheckedLockGuard lock(m_external_reference_mutex);
2,276✔
1428

933✔
1429
    if (auto external_reference = m_external_reference.lock())
2,276✔
1430
        return std::shared_ptr<SyncSession>(external_reference, this);
889✔
1431

606✔
1432
    return nullptr;
1,387✔
1433
}
1,387✔
1434

1435
void SyncSession::did_drop_external_reference()
1436
{
1,388✔
1437
    util::CheckedUniqueLock lock1(m_state_mutex);
1,388✔
1438
    {
1,388✔
1439
        util::CheckedLockGuard lock2(m_external_reference_mutex);
1,388✔
1440

608✔
1441
        // If the session is being resurrected we should not close the session.
608✔
1442
        if (!m_external_reference.expired())
1,388✔
1443
            return;
×
1444
    }
1,388✔
1445

608✔
1446
    close(std::move(lock1));
1,388✔
1447
}
1,388✔
1448

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

1477
void SyncProgressNotifier::unregister_callback(uint64_t token)
1478
{
8✔
1479
    std::lock_guard<std::mutex> lock(m_mutex);
8✔
1480
    m_packages.erase(token);
8✔
1481
}
8✔
1482

1483
void SyncProgressNotifier::update(uint64_t downloaded, uint64_t downloadable, uint64_t uploaded, uint64_t uploadable,
1484
                                  uint64_t download_version, uint64_t snapshot_version)
1485
{
6,598✔
1486
    // Ignore progress messages from before we first receive a DOWNLOAD message
2,759✔
1487
    if (download_version == 0)
6,598✔
1488
        return;
2,849✔
1489

1,649✔
1490
    std::vector<util::UniqueFunction<void()>> invocations;
3,749✔
1491
    {
3,749✔
1492
        std::lock_guard<std::mutex> lock(m_mutex);
3,749✔
1493
        m_current_progress = Progress{uploadable, downloadable, uploaded, downloaded, snapshot_version};
3,749✔
1494

1,649✔
1495
        for (auto it = m_packages.begin(); it != m_packages.end();) {
3,815✔
1496
            bool should_delete = false;
66✔
1497
            invocations.emplace_back(it->second.create_invocation(*m_current_progress, should_delete));
66✔
1498
            it = should_delete ? m_packages.erase(it) : std::next(it);
57✔
1499
        }
66✔
1500
    }
3,749✔
1501
    // Run the notifiers only after we've released the lock.
1,649✔
1502
    for (auto& invocation : invocations)
3,749✔
1503
        invocation();
66✔
1504
}
3,749✔
1505

1506
void SyncProgressNotifier::set_local_version(uint64_t snapshot_version)
1507
{
8,038✔
1508
    std::lock_guard<std::mutex> lock(m_mutex);
8,038✔
1509
    m_local_transaction_version = snapshot_version;
8,038✔
1510
}
8,038✔
1511

1512
util::UniqueFunction<void()>
1513
SyncProgressNotifier::NotifierPackage::create_invocation(Progress const& current_progress, bool& is_expired)
1514
{
102✔
1515
    uint64_t transferred = is_download ? current_progress.downloaded : current_progress.uploaded;
83✔
1516
    uint64_t transferrable = is_download ? current_progress.downloadable : current_progress.uploadable;
83✔
1517
    if (!is_streaming) {
102✔
1518
        // If the sync client has not yet processed all of the local
35✔
1519
        // transactions then the uploadable data is incorrect and we should
35✔
1520
        // not invoke the callback
35✔
1521
        if (!is_download && snapshot_version > current_progress.snapshot_version)
70✔
1522
            return [] {};
2✔
1523

34✔
1524
        // The initial download size we get from the server is the uncompacted
34✔
1525
        // size, and so the download may complete before we actually receive
34✔
1526
        // that much data. When that happens, transferrable will drop and we
34✔
1527
        // need to use the new value instead of the captured one.
34✔
1528
        if (!captured_transferrable || *captured_transferrable > transferrable)
68✔
1529
            captured_transferrable = transferrable;
36✔
1530
        transferrable = *captured_transferrable;
68✔
1531
    }
68✔
1532

51✔
1533
    // A notifier is expired if at least as many bytes have been transferred
51✔
1534
    // as were originally considered transferrable.
51✔
1535
    is_expired = !is_streaming && transferred >= transferrable;
101✔
1536
    return [=, notifier = notifier] {
100✔
1537
        notifier(transferred, transferrable);
100✔
1538
    };
100✔
1539
}
102✔
1540

1541
uint64_t SyncSession::ConnectionChangeNotifier::add_callback(std::function<ConnectionStateChangeCallback> callback)
1542
{
6✔
1543
    std::lock_guard<std::mutex> lock(m_callback_mutex);
6✔
1544
    auto token = m_next_token++;
6✔
1545
    m_callbacks.push_back({std::move(callback), token});
6✔
1546
    return token;
6✔
1547
}
6✔
1548

1549
void SyncSession::ConnectionChangeNotifier::remove_callback(uint64_t token)
1550
{
2✔
1551
    Callback old;
2✔
1552
    {
2✔
1553
        std::lock_guard<std::mutex> lock(m_callback_mutex);
2✔
1554
        auto it = std::find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) {
2✔
1555
            return c.token == token;
2✔
1556
        });
2✔
1557
        if (it == end(m_callbacks)) {
2✔
1558
            return;
×
1559
        }
×
1560

1✔
1561
        size_t idx = distance(begin(m_callbacks), it);
2✔
1562
        if (m_callback_index != npos) {
2✔
1563
            if (m_callback_index >= idx)
×
1564
                --m_callback_index;
×
1565
        }
×
1566
        --m_callback_count;
2✔
1567

1✔
1568
        old = std::move(*it);
2✔
1569
        m_callbacks.erase(it);
2✔
1570
    }
2✔
1571
}
2✔
1572

1573
void SyncSession::ConnectionChangeNotifier::invoke_callbacks(ConnectionState old_state, ConnectionState new_state)
1574
{
5,478✔
1575
    std::unique_lock lock(m_callback_mutex);
5,478✔
1576
    m_callback_count = m_callbacks.size();
5,478✔
1577
    for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) {
5,482✔
1578
        // acquire a local reference to the callback so that removing the
2✔
1579
        // callback from within it can't result in a dangling pointer
2✔
1580
        auto cb = m_callbacks[m_callback_index].fn;
4✔
1581
        lock.unlock();
4✔
1582
        cb(old_state, new_state);
4✔
1583
        lock.lock();
4✔
1584
    }
4✔
1585
    m_callback_index = npos;
5,478✔
1586
}
5,478✔
1587

1588
util::Future<std::string> SyncSession::send_test_command(std::string body)
1589
{
34✔
1590
    util::CheckedLockGuard lk(m_state_mutex);
34✔
1591
    if (!m_session) {
34✔
1592
        return Status{ErrorCodes::RuntimeError, "Session doesn't exist to send test command on"};
×
1593
    }
×
1594

17✔
1595
    return m_session->send_test_command(std::move(body));
34✔
1596
}
34✔
1597

1598
void SyncSession::make_active_subscription_set()
1599
{
16✔
1600
    util::CheckedUniqueLock lock(m_state_mutex);
16✔
1601

8✔
1602
    if (!m_active_subscriptions_after_migration)
16✔
1603
        return;
×
1604

8✔
1605
    REALM_ASSERT(m_flx_subscription_store);
16✔
1606

8✔
1607
    // Create subscription set from the subscriptions used to download the fresh realm after migration.
8✔
1608
    auto active_mut_sub = m_flx_subscription_store->get_active().make_mutable_copy();
16✔
1609
    active_mut_sub.import(*m_active_subscriptions_after_migration);
16✔
1610
    active_mut_sub.update_state(sync::SubscriptionSet::State::Complete);
16✔
1611
    active_mut_sub.commit();
16✔
1612

8✔
1613
    m_active_subscriptions_after_migration.reset();
16✔
1614
}
16✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc