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

realm / realm-core / thomas.goyne_315

27 Apr 2024 02:45AM UTC coverage: 90.896% (+0.1%) from 90.756%
thomas.goyne_315

push

Evergreen

web-flow
Merge pull request #7639 from realm/release/14.6.0-again

merge release 14.6.0

103074 of 182252 branches covered (56.56%)

285 of 285 new or added lines in 5 files covered. (100.0%)

80 existing lines in 10 files now uncovered.

213807 of 235222 relevant lines covered (90.9%)

5800736.68 hits per line

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

91.6
/test/object-store/util/test_file.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 "util/test_file.hpp"
20

21
#include "util/test_utils.hpp"
22
#include "util/sync/baas_admin_api.hpp"
23
#include "util/sync/sync_test_utils.hpp"
24
#include "../util/crypt_key.hpp"
25
#include "../util/test_path.hpp"
26
#include "util/sync/sync_test_utils.hpp"
27

28
#include <realm/db.hpp>
29
#include <realm/disable_sync_to_disk.hpp>
30
#include <realm/history.hpp>
31
#include <realm/string_data.hpp>
32
#include <realm/object-store/impl/realm_coordinator.hpp>
33
#include <realm/util/base64.hpp>
34
#include <realm/util/file.hpp>
35

36
#if REALM_ENABLE_SYNC
37
#include <realm/object-store/sync/mongo_client.hpp>
38
#include <realm/object-store/sync/mongo_database.hpp>
39
#include <realm/object-store/sync/mongo_collection.hpp>
40
#include <realm/object-store/sync/sync_manager.hpp>
41
#include <realm/object-store/sync/sync_session.hpp>
42
#include <realm/object-store/sync/sync_user.hpp>
43
#include <realm/object-store/schema.hpp>
44
#endif
45

46
#include <cstdlib>
47
#include <iostream>
48

49
#ifdef _WIN32
50
#include <io.h>
51
#include <fcntl.h>
52

53
inline static int mkstemp(char* _template)
54
{
55
    return _open(_mktemp(_template), _O_CREAT | _O_TEMPORARY, _S_IREAD | _S_IWRITE);
56
}
57
#else
58
#include <unistd.h>
59
#endif
60

61
#if REALM_HAVE_CLANG_FEATURE(thread_sanitizer)
62
#include <condition_variable>
63
#include <functional>
64
#include <thread>
65
#include <map>
66
#endif
67

68
using namespace realm;
69

70
TestFile::TestFile()
71
{
9,740✔
72
    disable_sync_to_disk();
9,740✔
73
    m_temp_dir = util::make_temp_dir();
9,740✔
74
    path = (fs::path(m_temp_dir) / "realm.XXXXXX").string();
9,740✔
75
    if (const char* crypt_key = test_util::crypt_key()) {
9,740✔
76
        encryption_key = std::vector<char>(crypt_key, crypt_key + 64);
×
77
    }
×
78
    int fd = mkstemp(path.data());
9,740✔
79
    if (fd < 0) {
9,740✔
80
        int err = errno;
×
81
        throw std::system_error(err, std::system_category());
×
82
    }
×
83
#ifdef _WIN32
84
    _close(fd);
85
    _unlink(path.c_str());
86
#else // POSIX
87
    close(fd);
9,740✔
88
    unlink(path.c_str());
9,740✔
89
#endif
9,740✔
90

91
    schema_version = 0;
9,740✔
92
}
9,740✔
93

94
TestFile::~TestFile()
95
{
9,740✔
96
    if (!m_persist) {
9,740✔
97
        try {
9,654✔
98
            util::Logger::get_default_logger()->debug("~TestFile() removing '%1' and '%2'", path, m_temp_dir);
9,654✔
99
            util::File::try_remove(path);
9,654✔
100
            util::try_remove_dir_recursive(m_temp_dir);
9,654✔
101
        }
9,654✔
102
        catch (const std::exception& e) {
9,654✔
UNCOV
103
            util::Logger::get_default_logger()->warn("~TestFile() cleanup failed for '%1': %2", path, e.what());
×
104
            // clean up is best effort, ignored.
UNCOV
105
        }
×
106
    }
9,654✔
107
}
9,740✔
108

109
DBOptions TestFile::options() const
110
{
26✔
111
    DBOptions options;
26✔
112
    options.durability = in_memory ? DBOptions::Durability::MemOnly : DBOptions::Durability::Full;
26✔
113
    return options;
26✔
114
}
26✔
115

116
InMemoryTestFile::InMemoryTestFile()
117
{
8,614✔
118
    in_memory = true;
8,614✔
119
    schema_version = 0;
8,614✔
120
    encryption_key = std::vector<char>();
8,614✔
121
}
8,614✔
122

123
DBOptions InMemoryTestFile::options() const
124
{
×
125
    DBOptions options;
×
126
    options.durability = DBOptions::Durability::MemOnly;
×
127
    return options;
×
128
}
×
129

130
#if REALM_ENABLE_SYNC
131

132
static const std::string fake_refresh_token = ENCODE_FAKE_JWT("not_a_real_token");
133
static const std::string fake_access_token = ENCODE_FAKE_JWT("also_not_real");
134
static const std::string fake_device_id = "123400000000000000000000";
135

136
SyncTestFile::SyncTestFile(TestSyncManager& tsm, std::string name, std::string user_name)
137
    : SyncTestFile(tsm.fake_user(user_name), bson::Bson(name))
69✔
138
{
214✔
139
}
214✔
140

141
#if REALM_APP_SERVICES
142
SyncTestFile::SyncTestFile(OfflineAppSession& oas, std::string name)
143
    : SyncTestFile(oas.make_user(), bson::Bson(name))
1,781✔
144
{
3,562✔
145
}
3,562✔
146
#endif // REALM_APP_SERVICES
147

148
SyncTestFile::SyncTestFile(std::shared_ptr<SyncUser> user, bson::Bson partition, util::Optional<Schema> schema)
149
{
7,830✔
150
    REALM_ASSERT(user);
7,830✔
151
    sync_config = std::make_shared<realm::SyncConfig>(user, partition);
7,830✔
152
    sync_config->stop_policy = SyncSessionStopPolicy::Immediately;
7,830✔
153
    sync_config->error_handler = [](std::shared_ptr<SyncSession>, SyncError error) {
7,830✔
154
        util::format(std::cerr, "An unexpected sync error was caught by the default SyncTestFile handler: '%1'\n",
×
155
                     error.status);
×
156
        abort();
×
157
    };
×
158
    schema_version = 1;
7,830✔
159
    this->schema = std::move(schema);
7,830✔
160
    schema_mode = SchemaMode::AdditiveExplicit;
7,830✔
161
}
7,830✔
162

163
SyncTestFile::SyncTestFile(std::shared_ptr<SyncUser> user, bson::Bson partition,
164
                           realm::util::Optional<realm::Schema> schema,
165
                           std::function<SyncSessionErrorHandler>&& error_handler)
166
{
2✔
167
    REALM_ASSERT(user);
2✔
168
    sync_config = std::make_shared<realm::SyncConfig>(user, partition);
2✔
169
    sync_config->stop_policy = SyncSessionStopPolicy::Immediately;
2✔
170
    sync_config->error_handler = std::move(error_handler);
2✔
171
    schema_version = 1;
2✔
172
    this->schema = std::move(schema);
2✔
173
    schema_mode = SchemaMode::AdditiveExplicit;
2✔
174
}
2✔
175

176
SyncTestFile::SyncTestFile(std::shared_ptr<realm::SyncUser> user, realm::Schema _schema, SyncConfig::FLXSyncEnabled)
177
{
403✔
178
    REALM_ASSERT(user);
403✔
179
    sync_config = std::make_shared<realm::SyncConfig>(user, SyncConfig::FLXSyncEnabled{});
403✔
180
    sync_config->stop_policy = SyncSessionStopPolicy::Immediately;
403✔
181
    sync_config->error_handler = [](std::shared_ptr<SyncSession> session, SyncError error) {
403✔
182
        util::format(std::cerr,
×
183
                     "An unexpected sync error was caught by the default SyncTestFile handler: '%1' for '%2'",
×
184
                     error.status, session->path());
×
185
        abort();
×
186
    };
×
187
    schema_version = 0;
403✔
188
    schema = _schema;
403✔
189
    schema_mode = SchemaMode::AdditiveExplicit;
403✔
190
}
403✔
191

192
SyncTestFile::SyncTestFile(TestSyncManager& tsm, bson::Bson partition, Schema schema)
193
    : SyncTestFile(tsm.fake_user("test"), std::move(partition), std::move(schema))
194
{
×
195
}
×
196

197
// MARK: - SyncServer
198
SyncServer::SyncServer(const SyncServer::Config& config)
199
    : m_local_root_dir(config.local_dir.empty() ? util::make_temp_dir() : config.local_dir)
86✔
200
    , m_server(m_local_root_dir, util::none, ([&] {
235✔
201
                   using namespace std::literals::chrono_literals;
235✔
202

203
                   m_logger = util::Logger::get_default_logger();
235✔
204

205
                   sync::Server::Config c;
235✔
206
                   c.logger = m_logger;
235✔
207
                   c.token_expiration_clock = this;
235✔
208
                   c.listen_address = "127.0.0.1";
235✔
209
                   c.disable_sync_to_disk = true;
235✔
210
                   c.ssl = config.ssl;
235✔
211
                   if (c.ssl) {
235✔
212
                       c.ssl_certificate_path = test_util::get_test_resource_path() + "test_util_network_ssl_ca.pem";
2✔
213
                       c.ssl_certificate_key_path =
2✔
214
                           test_util::get_test_resource_path() + "test_util_network_ssl_key.pem";
2✔
215
                   }
2✔
216

217
                   return c;
235✔
218
               })())
235✔
219
{
235✔
220
    m_server.start();
235✔
221
    m_url = util::format("%1://127.0.0.1:%2", config.ssl ? "wss" : "ws", m_server.listen_endpoint().port());
235✔
222
    if (config.start_immediately)
235✔
223
        start();
174✔
224
}
235✔
225

226
SyncServer::~SyncServer()
227
{
235✔
228
    stop();
235✔
229
}
235✔
230

231
void SyncServer::start()
232
{
207✔
233
    REALM_ASSERT(!m_thread.joinable());
207✔
234
    m_thread = std::thread([this] {
207✔
235
        m_server.run();
207✔
236
    });
207✔
237
}
207✔
238

239
void SyncServer::stop()
240
{
285✔
241
    m_server.stop();
285✔
242
    if (m_thread.joinable())
285✔
243
        m_thread.join();
207✔
244
}
285✔
245

246
std::string SyncServer::url_for_realm(StringData realm_name) const
247
{
×
248
    return util::format("%1/%2", m_url, realm_name);
×
249
}
×
250

251
int SyncServer::port() const
252
{
14✔
253
    return m_server.listen_endpoint().port();
14✔
254
}
14✔
255

256
struct WaitForSessionState {
257
    std::condition_variable cv;
258
    std::mutex mutex;
259
    bool complete = false;
260
    Status status = Status::OK();
261
};
262

263
static Status wait_for_session(Realm& realm, void (SyncSession::*fn)(util::UniqueFunction<void(Status)>&&),
264
                               std::chrono::seconds timeout)
265
{
1,751✔
266
    auto shared_state = std::make_shared<WaitForSessionState>();
1,751✔
267
    auto& session = *realm.sync_session();
1,751✔
268
    auto delay = TEST_TIMEOUT_EXTRA > 0 ? timeout + std::chrono::seconds(TEST_TIMEOUT_EXTRA) : timeout;
1,751✔
269
    (session.*fn)([weak_state = std::weak_ptr<WaitForSessionState>(shared_state)](Status s) {
1,751✔
270
        auto shared_state = weak_state.lock();
1,751✔
271
        if (!shared_state) {
1,751✔
272
            return;
×
273
        }
×
274
        std::lock_guard<std::mutex> lock(shared_state->mutex);
1,751✔
275
        shared_state->complete = true;
1,751✔
276
        shared_state->status = s;
1,751✔
277
        shared_state->cv.notify_one();
1,751✔
278
    });
1,751✔
279
    std::unique_lock<std::mutex> lock(shared_state->mutex);
1,751✔
280
    bool completed = shared_state->cv.wait_for(lock, delay, [&]() {
3,502✔
281
        return shared_state->complete == true;
3,502✔
282
    });
3,502✔
283
    if (!completed) {
1,751✔
284
        throw std::runtime_error(util::format("wait_for_session() exceeded %1 s", delay.count()));
×
285
    }
×
286
    return shared_state->status;
1,751✔
287
}
1,751✔
288

289
bool wait_for_upload(Realm& realm, std::chrono::seconds timeout)
290
{
844✔
291
    return !wait_for_session(realm, &SyncSession::wait_for_upload_completion, timeout).is_ok();
844✔
292
}
844✔
293

294
bool wait_for_download(Realm& realm, std::chrono::seconds timeout)
295
{
907✔
296
    return !wait_for_session(realm, &SyncSession::wait_for_download_completion, timeout).is_ok();
907✔
297
}
907✔
298

299
#if REALM_APP_SERVICES
300
void set_app_config_defaults(app::AppConfig& app_config,
301
                             const std::shared_ptr<app::GenericNetworkTransport>& transport)
302
{
4,245✔
303
    if (!app_config.transport)
4,245✔
304
        app_config.transport = transport;
3,725✔
305
    if (app_config.device_info.platform_version.empty())
4,245✔
306
        app_config.device_info.platform_version = "Object Store Test Platform Version";
3,725✔
307
    if (app_config.device_info.sdk_version.empty())
4,245✔
308
        app_config.device_info.sdk_version = "SDK Version";
3,725✔
309
    if (app_config.device_info.sdk.empty())
4,245✔
310
        app_config.device_info.sdk = "SDK Name";
3,725✔
311
    if (app_config.device_info.device_name.empty())
4,245✔
312
        app_config.device_info.device_name = "Device Name";
3,725✔
313
    if (app_config.device_info.device_version.empty())
4,245✔
314
        app_config.device_info.device_version = "Device Version";
3,725✔
315
    if (app_config.device_info.framework_name.empty())
4,245✔
316
        app_config.device_info.framework_name = "Framework Name";
3,725✔
317
    if (app_config.device_info.framework_version.empty())
4,245✔
318
        app_config.device_info.framework_version = "Framework Version";
3,725✔
319
    if (app_config.device_info.bundle_id.empty())
4,245✔
320
        app_config.device_info.bundle_id = "Bundle Id";
3,725✔
321
    if (app_config.app_id.empty())
4,245✔
322
        app_config.app_id = "app_id";
3,725✔
323
    app_config.metadata_mode = app::AppConfig::MetadataMode::InMemory;
4,245✔
324
}
4,245✔
325
#endif // REALM_APP_SERVICES
326

327
// MARK: - TestAppSession
328

329
#if REALM_ENABLE_AUTH_TESTS
330

331
TestAppSession::TestAppSession()
332
    : TestAppSession(get_runtime_app_session(), nullptr, DeleteApp{false})
64✔
333
{
128✔
334
}
128✔
335

336
TestAppSession::TestAppSession(AppSession session,
337
                               std::shared_ptr<realm::app::GenericNetworkTransport> custom_transport,
338
                               DeleteApp delete_app, ReconnectMode reconnect_mode,
339
                               std::shared_ptr<realm::sync::SyncSocketProvider> custom_socket_provider)
340
    : m_app_session(std::make_unique<AppSession>(session))
251✔
341
    , m_base_file_path(util::make_temp_dir() + random_string(10))
251✔
342
    , m_delete_app(delete_app)
251✔
343
    , m_transport(custom_transport)
251✔
344
{
520✔
345
    if (!m_transport)
520✔
346
        m_transport = instance_of<SynchronousTestTransport>;
310✔
347
    app_config = get_config(m_transport, *m_app_session);
520✔
348
    set_app_config_defaults(app_config, m_transport);
520✔
349
    app_config.base_file_path = m_base_file_path;
520✔
350
    app_config.metadata_mode = realm::app::AppConfig::MetadataMode::NoEncryption;
520✔
351

352
    util::try_make_dir(m_base_file_path);
520✔
353
    app_config.sync_client_config.reconnect_mode = reconnect_mode;
520✔
354
    app_config.sync_client_config.socket_provider = custom_socket_provider;
520✔
355
    // With multiplexing enabled, the linger time controls how long a
356
    // connection is kept open for reuse. In tests, we want to shut
357
    // down sync clients immediately.
358
    app_config.sync_client_config.timeouts.connection_linger_time = 0;
520✔
359

360
    m_app = app::App::get_app(app::App::CacheMode::Disabled, app_config);
520✔
361

362
    // initialize sync client
363
    m_app->sync_manager()->get_sync_client();
520✔
364
    user_creds = create_user_and_log_in(m_app);
520✔
365
}
520✔
366

367
TestAppSession::~TestAppSession()
368
{
520✔
369
    if (util::File::exists(m_base_file_path)) {
520✔
370
        try {
520✔
371
            m_app->sync_manager()->tear_down_for_testing();
520✔
372
            util::try_remove_dir_recursive(m_base_file_path);
520✔
373
        }
520✔
374
        catch (const std::exception& ex) {
520✔
375
            std::cerr << ex.what() << "\n";
×
376
        }
×
377
        app::App::clear_cached_apps();
520✔
378
    }
520✔
379
    if (m_delete_app) {
520✔
380
        m_app_session->admin_api.delete_app(m_app_session->server_app_id);
366✔
381
    }
366✔
382
}
520✔
383

384
std::vector<bson::BsonDocument> TestAppSession::get_documents(app::User& user, const std::string& object_type,
385
                                                              size_t expected_count) const
1✔
386
{
11✔
387
    app::MongoClient remote_client = user.mongo_client("BackingDB");
11✔
388
    app::MongoDatabase db = remote_client.db(m_app_session->config.mongo_dbname);
10✔
389
    app::MongoCollection collection = db[object_type];
10!
390
    int sleep_time = 10;
10✔
391
    timed_wait_for(
10✔
392
        [&] {
27!
393
            uint64_t count = 0;
27✔
394
            collection.count({}, [&](uint64_t c, util::Optional<app::AppError> error) {
27✔
395
                REQUIRE(!error);
27!
396
                count = c;
28✔
397
            });
27✔
398
            if (count < expected_count) {
28✔
399
                // querying the server too frequently makes it take longer to process the sync changesets we're
1✔
400
                // waiting for
1✔
401
                millisleep(sleep_time);
17✔
402
                if (sleep_time < 500) {
17✔
403
                    sleep_time *= 2;
18!
404
                }
17✔
405
                return false;
17✔
406
            }
17✔
407
            return true;
11✔
408
        },
28✔
409
        std::chrono::minutes(5));
10✔
410

411
    std::vector<bson::BsonDocument> documents;
10✔
412
    collection.find({}, {}, [&](util::Optional<bson::BsonArray>&& result, util::Optional<app::AppError> error) {
11✔
413
        REQUIRE(result);
11!
414
        REQUIRE(!error);
10!
415
        REQUIRE(result->size() == expected_count);
10!
416
        documents.reserve(result->size());
11✔
417
        for (auto&& bson : *result) {
1,144✔
418
            REQUIRE(bson.type() == bson::Bson::Type::Document);
1,144✔
419
            documents.push_back(std::move(static_cast<const bson::BsonDocument&>(bson)));
1,144✔
420
        }
1,144✔
421
    });
11✔
422
    return documents;
10✔
423
}
10✔
424
#endif // REALM_ENABLE_AUTH_TESTS
1✔
425

1✔
426
// MARK: - TestSyncManager
427

428
TestSyncManager::Config::Config() {}
84✔
429

430
TestSyncManager::TestSyncManager(const Config& config, const SyncServer::Config& sync_server_config)
431
    : m_sync_manager(SyncManager::create(SyncClientConfig()))
83✔
432
    , m_sync_server(sync_server_config)
98✔
433
    , m_base_file_path(config.base_path.empty() ? util::make_temp_dir() : config.base_path)
98✔
434
    , m_should_teardown_test_directory(config.should_teardown_test_directory)
98✔
435
{
98✔
436
    util::try_make_dir(m_base_file_path);
98✔
437

15✔
438
    m_sync_manager->set_sync_route(m_sync_server.base_url() + "/realm-sync", true);
171✔
439
    if (config.start_sync_client) {
171✔
440
        m_sync_manager->get_sync_client();
169✔
441
    }
169!
442
}
171✔
443

88✔
444
TestSyncManager::~TestSyncManager()
88✔
445
{
83✔
446
    if (m_should_teardown_test_directory) {
83✔
447
        if (!m_base_file_path.empty() && util::File::exists(m_base_file_path)) {
125✔
448
            try {
125✔
449
                m_sync_manager->tear_down_for_testing();
123✔
450
                util::try_remove_dir_recursive(m_base_file_path);
123✔
451
            }
125✔
452
            catch (const std::exception& ex) {
125✔
453
                std::cerr << ex.what() << "\n";
46✔
454
            }
88✔
455
#if REALM_APP_SERVICES
98✔
456
            app::App::clear_cached_apps();
83✔
457
#endif // REALM_APP_SERVICES
98✔
458
        }
98✔
459
    }
98!
460
}
98!
461

15!
462
std::shared_ptr<TestUser> TestSyncManager::fake_user(const std::string& name)
15✔
463
{
1,264✔
464
    auto user = std::make_shared<TestUser>(name, m_sync_manager);
1,264!
465
    user->m_access_token = fake_access_token;
1,264✔
466
    user->m_refresh_token = fake_refresh_token;
1,264✔
467
    return user;
128✔
468
}
128✔
469

15✔
470
#if REALM_APP_SERVICES
471
OfflineAppSession::Config::Config(std::shared_ptr<realm::app::GenericNetworkTransport> t)
472
    : transport(t)
1,845✔
473
{
1,845✔
474
}
1,991✔
475

476
OfflineAppSession::OfflineAppSession(OfflineAppSession::Config config)
477
    : m_transport(std::move(config.transport))
1,852✔
478
    , m_delete_storage(config.delete_storage)
1,852✔
479
{
1,852✔
480
    REALM_ASSERT(m_transport);
1,852✔
481
    app::AppConfig app_config;
1,998✔
482
    set_app_config_defaults(app_config, m_transport);
1,998✔
483

484
    if (config.storage_path) {
1,998✔
485
        m_base_file_path = *config.storage_path;
160✔
486
        util::try_make_dir(m_base_file_path);
158✔
487
    }
158✔
488
    else {
1,984✔
489
        m_base_file_path = util::make_temp_dir();
1,838✔
490
    }
1,838✔
491

146✔
492
    app_config.base_file_path = m_base_file_path;
1,998✔
493
    app_config.metadata_mode = config.metadata_mode;
1,998✔
494
    if (config.base_url) {
1,998✔
495
        app_config.base_url = *config.base_url;
170✔
496
    }
170✔
497
    if (config.app_id) {
1,998✔
498
        app_config.app_id = *config.app_id;
146✔
499
    }
×
500
    app_config.sync_client_config.socket_provider = config.socket_provider;
1,852✔
501
    m_app = app::App::get_app(app::App::CacheMode::Disabled, app_config);
1,998✔
502
}
1,998✔
503

146✔
504
OfflineAppSession::~OfflineAppSession()
146✔
505
{
1,998✔
506
    if (util::File::exists(m_base_file_path) && m_delete_storage) {
1,998✔
507
        try {
1,845✔
508
            m_app->sync_manager()->tear_down_for_testing();
1,845✔
509
            util::try_remove_dir_recursive(m_base_file_path);
2,034✔
510
        }
2,034✔
511
        catch (const std::exception& ex) {
2,034✔
512
            std::cerr << ex.what() << "\n";
189✔
513
        }
189✔
514
        app::App::clear_cached_apps();
2,034✔
515
    }
1,845✔
516
}
1,852✔
517

518
std::shared_ptr<realm::app::User> OfflineAppSession::make_user() const
519
{
3,662✔
520
    create_user_and_log_in(app());
3,662✔
521
    return app()->current_user();
1,817✔
522
}
1,817✔
523

524
#endif // REALM_APP_SERVICES
525
#endif // REALM_ENABLE_SYNC
1,852✔
526

1,852✔
527
#if REALM_HAVE_CLANG_FEATURE(thread_sanitizer)
1,852✔
528
// MARK: - TsanNotifyWorker
529
// A helper which synchronously runs on_change() on a fixed background thread
1,852✔
530
// so that ThreadSanitizer can potentially detect issues
14✔
531
// This deliberately uses an unsafe spinlock for synchronization to ensure that
14✔
532
// the code being tested has to supply all required safety
14✔
533
static class TsanNotifyWorker {
1,838✔
534
public:
1,838✔
535
    TsanNotifyWorker()
1,838✔
536
    {
537
        m_thread = std::thread([&] {
1,852✔
538
            work();
1,852✔
539
        });
1,852✔
540
    }
24✔
541

24✔
542
    void work()
1,852✔
543
    {
544
        while (true) {
545
            auto value = m_signal.load(std::memory_order_relaxed);
1,852✔
546
            if (value == 0 || value == 1)
1,852✔
547
                continue;
1,852✔
548
            if (value == 2)
549
                return;
550

1,852✔
551
            if (value & 1) {
1,852✔
552
                // Synchronize on the first handover of a given coordinator.
1,845✔
553
                value &= ~1;
1,845✔
554
                m_signal.load();
1,845✔
555
            }
1,845✔
556

1,845✔
557
            auto c = reinterpret_cast<_impl::RealmCoordinator*>(value);
558
            c->on_change();
559
            m_signal.store(1, std::memory_order_relaxed);
1,845✔
560
        }
1,845✔
561
    }
1,852✔
562

563
    ~TsanNotifyWorker()
564
    {
1,817✔
565
        m_signal = 2;
1,817✔
566
        m_thread.join();
1,817✔
567
    }
1,817✔
568

569
    void on_change(const std::shared_ptr<_impl::RealmCoordinator>& c)
570
    {
571
        auto& it = m_published_coordinators[c.get()];
572
        if (it.lock()) {
573
            m_signal.store(reinterpret_cast<uintptr_t>(c.get()), std::memory_order_relaxed);
574
        }
575
        else {
576
            // Synchronize on the first handover of a given coordinator.
577
            it = c;
578
            m_signal = reinterpret_cast<uintptr_t>(c.get()) | 1;
579
        }
580

581
        while (m_signal.load(std::memory_order_relaxed) != 1)
582
            ;
583
    }
584

585
private:
586
    std::atomic<uintptr_t> m_signal{0};
587
    std::thread m_thread;
588
    std::map<_impl::RealmCoordinator*, std::weak_ptr<_impl::RealmCoordinator>> m_published_coordinators;
589
} s_worker;
590

591
void on_change_but_no_notify(Realm& realm)
592
{
593
    s_worker.on_change(_impl::RealmCoordinator::get_existing_coordinator(realm.config().path));
594
}
595

596
void advance_and_notify(Realm& realm)
597
{
598
    on_change_but_no_notify(realm);
599
    realm.notify();
600
}
601

602
#else // REALM_HAVE_CLANG_FEATURE(thread_sanitizer)
603

604
void on_change_but_no_notify(Realm& realm)
605
{
14,022✔
606
    _impl::RealmCoordinator::get_coordinator(realm.config().path)->on_change();
14,022✔
607
}
14,022✔
608

609
void advance_and_notify(Realm& realm)
610
{
8,514✔
611
    on_change_but_no_notify(realm);
8,514✔
612
    realm.notify();
8,514✔
613
}
8,514✔
614
#endif
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