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

realm / realm-core / 2466

02 Jul 2024 04:06AM UTC coverage: 90.974% (-0.2%) from 91.147%
2466

push

Evergreen

web-flow
Merge pull request #7576 from realm/tg/multi-process-launch-actions

RCORE-1900 Make "next launch" metadata actions multiprocess-safe

102260 of 180446 branches covered (56.67%)

348 of 356 new or added lines in 15 files covered. (97.75%)

334 existing lines in 18 files now uncovered.

215128 of 236473 relevant lines covered (90.97%)

5909897.4 hits per line

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

98.32
/test/object-store/sync/flx_sync.cpp
1
////////////////////////////////////////////////////////////////////////////
2
//
3
// Copyright 2021 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
#if REALM_ENABLE_AUTH_TESTS
20

21
#include <catch2/catch_all.hpp>
22

23
#include <util/test_file.hpp>
24
#include <util/crypt_key.hpp>
25
#include <util/sync/flx_sync_harness.hpp>
26
#include <util/sync/sync_test_utils.hpp>
27

28
#include <realm/object_id.hpp>
29
#include <realm/query_expression.hpp>
30

31
#include <realm/object-store/binding_context.hpp>
32
#include <realm/object-store/impl/object_accessor_impl.hpp>
33
#include <realm/object-store/impl/realm_coordinator.hpp>
34
#include <realm/object-store/schema.hpp>
35
#include <realm/object-store/sync/generic_network_transport.hpp>
36
#include <realm/object-store/sync/mongo_client.hpp>
37
#include <realm/object-store/sync/mongo_database.hpp>
38
#include <realm/object-store/sync/mongo_collection.hpp>
39
#include <realm/object-store/sync/async_open_task.hpp>
40
#include <realm/util/bson/bson.hpp>
41
#include <realm/object-store/sync/sync_session.hpp>
42

43
#include <realm/sync/client_base.hpp>
44
#include <realm/sync/config.hpp>
45
#include <realm/sync/noinst/client_history_impl.hpp>
46
#include <realm/sync/noinst/client_reset.hpp>
47
#include <realm/sync/noinst/client_reset_operation.hpp>
48
#include <realm/sync/noinst/pending_bootstrap_store.hpp>
49
#include <realm/sync/noinst/server/access_token.hpp>
50
#include <realm/sync/protocol.hpp>
51
#include <realm/sync/subscriptions.hpp>
52

53
#include <realm/util/future.hpp>
54
#include <realm/util/logger.hpp>
55

56
#include <catch2/catch_all.hpp>
57

58
#include <filesystem>
59
#include <iostream>
60
#include <stdexcept>
61

62
using namespace std::string_literals;
63

64
namespace realm {
65

66
class TestHelper {
67
public:
68
    static DBRef& get_db(SharedRealm const& shared_realm)
69
    {
70
        return Realm::Internal::get_db(*shared_realm);
71
    }
72
};
73

74
} // namespace realm
75

76
namespace realm::app {
77

78
namespace {
79
const Schema g_minimal_schema{
80
    {"TopLevel",
81
     {
82
         {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
83
     }},
84
};
85

86
const Schema g_large_array_schema{
87
    ObjectSchema("TopLevel",
88
                 {
89
                     {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
90
                     {"queryable_int_field", PropertyType::Int | PropertyType::Nullable},
91
                     {"list_of_strings", PropertyType::Array | PropertyType::String},
92
                 }),
93
};
94

95
const Schema g_simple_embedded_obj_schema{
96
    {"TopLevel",
97
     {{"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
98
      {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
99
      {"embedded_obj", PropertyType::Object | PropertyType::Nullable, "TopLevel_embedded_obj"}}},
100
    {"TopLevel_embedded_obj",
101
     ObjectSchema::ObjectType::Embedded,
102
     {
103
         {"str_field", PropertyType::String | PropertyType::Nullable},
104
     }},
105
};
106

107
// Populates a FLXSyncTestHarness with the g_large_array_schema with objects that are large enough that
108
// they are guaranteed to fill multiple bootstrap download messages. Currently this means generating 5
109
// objects each with 1024 array entries of 1024 bytes each.
110
//
111
// Returns a list of the _id values for the objects created.
112
std::vector<ObjectId> fill_large_array_schema(FLXSyncTestHarness& harness)
113
{
14✔
114
    std::vector<ObjectId> ret;
14✔
115
    REQUIRE(harness.schema() == g_large_array_schema);
14!
116
    harness.load_initial_data([&](SharedRealm realm) {
14✔
117
        CppContext c(realm);
14✔
118
        for (int i = 0; i < 5; ++i) {
84✔
119
            auto id = ObjectId::gen();
70✔
120
            auto obj = Object::create(c, realm, "TopLevel",
70✔
121
                                      std::any(AnyDict{{"_id", id},
70✔
122
                                                       {"list_of_strings", AnyVector{}},
70✔
123
                                                       {"queryable_int_field", static_cast<int64_t>(i * 5)}}));
70✔
124
            List str_list(obj, realm->schema().find("TopLevel")->property_for_name("list_of_strings"));
70✔
125
            for (int j = 0; j < 1024; ++j) {
71,750✔
126
                str_list.add(c, std::any(std::string(1024, 'a' + (j % 26))));
71,680✔
127
            }
71,680✔
128

129
            ret.push_back(id);
70✔
130
        }
70✔
131
    });
14✔
132
    return ret;
14✔
133
}
14✔
134

135
} // namespace
136

137
TEST_CASE("flx: connect to FLX-enabled app", "[sync][flx][baas]") {
2✔
138
    FLXSyncTestHarness harness("basic_flx_connect");
2✔
139

140
    auto foo_obj_id = ObjectId::gen();
2✔
141
    auto bar_obj_id = ObjectId::gen();
2✔
142
    harness.load_initial_data([&](SharedRealm realm) {
2✔
143
        CppContext c(realm);
2✔
144
        Object::create(c, realm, "TopLevel",
2✔
145
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
146
                                        {"queryable_str_field", "foo"s},
2✔
147
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
148
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
149
        Object::create(c, realm, "TopLevel",
2✔
150
                       std::any(AnyDict{{"_id", bar_obj_id},
2✔
151
                                        {"queryable_str_field", "bar"s},
2✔
152
                                        {"queryable_int_field", static_cast<int64_t>(10)},
2✔
153
                                        {"non_queryable_field", "non queryable 2"s}}));
2✔
154
    });
2✔
155

156

157
    harness.do_with_new_realm([&](SharedRealm realm) {
2✔
158
        {
2✔
159
            auto empty_subs = realm->get_latest_subscription_set();
2✔
160
            CHECK(empty_subs.size() == 0);
2!
161
            CHECK(empty_subs.version() == 0);
2!
162
            empty_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
163
        }
2✔
164

165
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
166
        auto col_key = table->get_column_key("queryable_str_field");
2✔
167
        Query query_foo(table);
2✔
168
        query_foo.equal(col_key, "foo");
2✔
169
        {
2✔
170
            auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
171
            new_subs.insert_or_assign(query_foo);
2✔
172
            auto subs = new_subs.commit();
2✔
173
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
174
        }
2✔
175

176
        {
2✔
177
            wait_for_advance(*realm);
2✔
178
            Results results(realm, table);
2✔
179
            CHECK(results.size() == 1);
2!
180
            auto obj = results.get<Obj>(0);
2✔
181
            CHECK(obj.is_valid());
2!
182
            CHECK(obj.get<ObjectId>("_id") == foo_obj_id);
2!
183
        }
2✔
184

185
        {
2✔
186
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
187
            Query new_query_bar(table);
2✔
188
            new_query_bar.equal(col_key, "bar");
2✔
189
            mut_subs.insert_or_assign(new_query_bar);
2✔
190
            auto subs = mut_subs.commit();
2✔
191
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
192
        }
2✔
193

194
        {
2✔
195
            wait_for_advance(*realm);
2✔
196
            Results results(realm, Query(table));
2✔
197
            CHECK(results.size() == 2);
2!
198
        }
2✔
199

200
        {
2✔
201
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
202
            CHECK(mut_subs.erase(query_foo));
2!
203
            Query new_query_bar(table);
2✔
204
            new_query_bar.equal(col_key, "bar");
2✔
205
            mut_subs.insert_or_assign(new_query_bar);
2✔
206
            auto subs = mut_subs.commit();
2✔
207
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
208
        }
2✔
209

210
        {
2✔
211
            wait_for_advance(*realm);
2✔
212
            Results results(realm, Query(table));
2✔
213
            CHECK(results.size() == 1);
2!
214
            auto obj = results.get<Obj>(0);
2✔
215
            CHECK(obj.is_valid());
2!
216
            CHECK(obj.get<ObjectId>("_id") == bar_obj_id);
2!
217
        }
2✔
218

219
        {
2✔
220
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
221
            mut_subs.clear();
2✔
222
            auto subs = mut_subs.commit();
2✔
223
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
224
        }
2✔
225

226
        {
2✔
227
            wait_for_advance(*realm);
2✔
228
            Results results(realm, table);
2✔
229
            CHECK(results.size() == 0);
2!
230
        }
2✔
231
    });
2✔
232
}
2✔
233

234
TEST_CASE("flx: test commands work", "[sync][flx][test command][baas]") {
2✔
235
    FLXSyncTestHarness harness("test_commands");
2✔
236
    harness.do_with_new_realm([&](const SharedRealm& realm) {
2✔
237
        wait_for_upload(*realm);
2✔
238
        nlohmann::json command_request = {
2✔
239
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
240
        };
2✔
241
        auto resp_body =
2✔
242
            SyncSession::OnlyForTesting::send_test_command(*realm->sync_session(), command_request.dump()).get();
2✔
243
        REQUIRE(resp_body == "{}");
2!
244

245
        auto bad_status =
2✔
246
            SyncSession::OnlyForTesting::send_test_command(*realm->sync_session(), "foobar: }").get_no_throw();
2✔
247
        REQUIRE(bad_status.get_status() == ErrorCodes::LogicError);
2!
248
        REQUIRE_THAT(bad_status.get_status().reason(),
2✔
249
                     Catch::Matchers::ContainsSubstring("Invalid json input to send_test_command"));
2✔
250

251
        bad_status =
2✔
252
            SyncSession::OnlyForTesting::send_test_command(*realm->sync_session(), "{\"cmd\": \"\"}").get_no_throw();
2✔
253
        REQUIRE_FALSE(bad_status.is_ok());
2!
254
        REQUIRE(bad_status.get_status() == ErrorCodes::LogicError);
2!
255
        REQUIRE(bad_status.get_status().reason() ==
2!
256
                "Must supply command name in \"command\" field of test command json object");
2✔
257
    });
2✔
258
}
2✔
259

260

261
static auto make_error_handler()
262
{
40✔
263
    auto [error_promise, error_future] = util::make_promise_future<SyncError>();
40✔
264
    auto shared_promise = std::make_shared<decltype(error_promise)>(std::move(error_promise));
40✔
265
    auto fn = [error_promise = std::move(shared_promise)](std::shared_ptr<SyncSession>, SyncError err) {
40✔
266
        error_promise->emplace_value(std::move(err));
36✔
267
    };
36✔
268
    return std::make_pair(std::move(error_future), std::move(fn));
40✔
269
}
40✔
270

271
static auto make_client_reset_handler()
272
{
20✔
273
    auto [reset_promise, reset_future] = util::make_promise_future<ClientResyncMode>();
20✔
274
    auto shared_promise = std::make_shared<decltype(reset_promise)>(std::move(reset_promise));
20✔
275
    auto fn = [reset_promise = std::move(shared_promise)](SharedRealm, ThreadSafeReference, bool did_recover) {
20✔
276
        reset_promise->emplace_value(did_recover ? ClientResyncMode::Recover : ClientResyncMode::DiscardLocal);
20✔
277
    };
20✔
278
    return std::make_pair(std::move(reset_future), std::move(fn));
20✔
279
}
20✔
280

281

282
TEST_CASE("app: error handling integration test", "[sync][flx][baas]") {
18✔
283
    static std::optional<FLXSyncTestHarness> harness{"error_handling"};
18✔
284
    create_user_and_log_in(harness->app());
18✔
285
    SyncTestFile config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
18✔
286
    auto&& [error_future, error_handler] = make_error_handler();
18✔
287
    config.sync_config->error_handler = std::move(error_handler);
18✔
288
    config.sync_config->client_resync_mode = ClientResyncMode::Manual;
18✔
289

290
    SECTION("Resuming while waiting for session to auto-resume") {
18✔
291
        enum class TestState { InitialSuspend, InitialResume, SecondBind, SecondSuspend, SecondResume, Done };
2✔
292
        TestingStateMachine<TestState> state(TestState::InitialSuspend);
2✔
293
        config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession>,
2✔
294
                                                            const SyncClientHookData& data) {
30✔
295
            std::optional<TestState> wait_for;
30✔
296
            auto event = data.event;
30✔
297
            state.transition_with([&](TestState state) -> std::optional<TestState> {
30✔
298
                if (state == TestState::InitialSuspend && event == SyncClientHookEvent::SessionSuspended) {
30✔
299
                    // If we're getting suspended for the first time, notify the test thread that we're
300
                    // ready to be resumed.
301
                    wait_for = TestState::SecondBind;
2✔
302
                    return TestState::InitialResume;
2✔
303
                }
2✔
304
                else if (state == TestState::SecondBind && data.event == SyncClientHookEvent::BindMessageSent) {
28✔
305
                    return TestState::SecondSuspend;
2✔
306
                }
2✔
307
                else if (state == TestState::SecondSuspend && event == SyncClientHookEvent::SessionSuspended) {
26✔
308
                    wait_for = TestState::Done;
2✔
309
                    return TestState::SecondResume;
2✔
310
                }
2✔
311
                return std::nullopt;
24✔
312
            });
30✔
313
            if (wait_for) {
30✔
314
                state.wait_for(*wait_for);
4✔
315
            }
4✔
316
            return SyncClientHookAction::NoAction;
30✔
317
        };
30✔
318
        auto r = Realm::get_shared_realm(config);
2✔
319
        wait_for_upload(*r);
2✔
320
        nlohmann::json error_body = {
2✔
321
            {"tryAgain", true},           {"message", "fake error"},
2✔
322
            {"shouldClientReset", false}, {"isRecoveryModeDisabled", false},
2✔
323
            {"action", "Transient"},      {"backoffIntervalSec", 900},
2✔
324
            {"backoffMaxDelaySec", 900},  {"backoffMultiplier", 1},
2✔
325
        };
2✔
326
        nlohmann::json test_command = {{"command", "ECHO_ERROR"},
2✔
327
                                       {"args", nlohmann::json{{"errorCode", 229}, {"errorBody", error_body}}}};
2✔
328

329
        // First we trigger a retryable transient error that should cause the client to try to resume the
330
        // session in 5 minutes.
331
        auto test_cmd_res =
2✔
332
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
2✔
333
                .get();
2✔
334
        REQUIRE(test_cmd_res == "{}");
2!
335

336
        // Wait for the
337
        state.wait_for(TestState::InitialResume);
2✔
338

339
        // Once we're suspended, immediately tell the sync client to resume the session. This should cancel the
340
        // timer that would have auto-resumed the session.
341
        r->sync_session()->handle_reconnect();
2✔
342
        state.transition_with([&](TestState cur_state) {
2✔
343
            REQUIRE(cur_state == TestState::InitialResume);
2!
344
            return TestState::SecondBind;
2✔
345
        });
2✔
346
        state.wait_for(TestState::SecondSuspend);
2✔
347

348
        // Once we're connected again trigger another retryable transient error. Before RCORE-1770 the timer
349
        // to auto-resume the session would have still been active here and we would crash when trying to start
350
        // a second timer to auto-resume after this error.
351
        test_cmd_res =
2✔
352
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
2✔
353
                .get();
2✔
354
        REQUIRE(test_cmd_res == "{}");
2!
355
        state.wait_for(TestState::SecondResume);
2✔
356

357
        // Finally resume the session again which should cancel the second timer and the session should auto-resume
358
        // normally without crashing.
359
        r->sync_session()->handle_reconnect();
2✔
360
        state.transition_with([&](TestState cur_state) {
2✔
361
            REQUIRE(cur_state == TestState::SecondResume);
2!
362
            return TestState::Done;
2✔
363
        });
2✔
364
        wait_for_download(*r);
2✔
365
    }
2✔
366

367
    SECTION("handles unknown errors gracefully") {
18✔
368
        auto r = Realm::get_shared_realm(config);
2✔
369
        wait_for_download(*r);
2✔
370
        nlohmann::json error_body = {
2✔
371
            {"tryAgain", false},         {"message", "fake error"},
2✔
372
            {"shouldClientReset", true}, {"isRecoveryModeDisabled", false},
2✔
373
            {"action", "ClientReset"},
2✔
374
        };
2✔
375
        nlohmann::json test_command = {{"command", "ECHO_ERROR"},
2✔
376
                                       {"args", nlohmann::json{{"errorCode", 299}, {"errorBody", error_body}}}};
2✔
377
        auto test_cmd_res =
2✔
378
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
2✔
379
                .get();
2✔
380
        REQUIRE(test_cmd_res == "{}");
2!
381
        auto error = wait_for_future(std::move(error_future)).get();
2✔
382
        REQUIRE(error.status == ErrorCodes::UnknownError);
2!
383
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::ClientReset);
2!
384
        REQUIRE(error.is_fatal);
2!
385
        REQUIRE_THAT(error.status.reason(),
2✔
386
                     Catch::Matchers::ContainsSubstring("Unknown sync protocol error code 299"));
2✔
387
        REQUIRE_THAT(error.status.reason(), Catch::Matchers::ContainsSubstring("fake error"));
2✔
388
    }
2✔
389

390
    SECTION("unknown errors without actions are application bugs") {
18✔
391
        auto r = Realm::get_shared_realm(config);
2✔
392
        wait_for_download(*r);
2✔
393
        nlohmann::json error_body = {
2✔
394
            {"tryAgain", false},
2✔
395
            {"message", "fake error"},
2✔
396
            {"shouldClientReset", false},
2✔
397
            {"isRecoveryModeDisabled", false},
2✔
398
        };
2✔
399
        nlohmann::json test_command = {{"command", "ECHO_ERROR"},
2✔
400
                                       {"args", nlohmann::json{{"errorCode", 299}, {"errorBody", error_body}}}};
2✔
401
        auto test_cmd_res =
2✔
402
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
2✔
403
                .get();
2✔
404
        REQUIRE(test_cmd_res == "{}");
2!
405
        auto error = wait_for_future(std::move(error_future)).get();
2✔
406
        REQUIRE(error.status == ErrorCodes::UnknownError);
2!
407
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::ApplicationBug);
2!
408
        REQUIRE(error.is_fatal);
2!
409
        REQUIRE_THAT(error.status.reason(),
2✔
410
                     Catch::Matchers::ContainsSubstring("Unknown sync protocol error code 299"));
2✔
411
        REQUIRE_THAT(error.status.reason(), Catch::Matchers::ContainsSubstring("fake error"));
2✔
412
    }
2✔
413

414
    SECTION("handles unknown actions gracefully") {
18✔
415
        auto r = Realm::get_shared_realm(config);
2✔
416
        wait_for_download(*r);
2✔
417
        nlohmann::json error_body = {
2✔
418
            {"tryAgain", false},
2✔
419
            {"message", "fake error"},
2✔
420
            {"shouldClientReset", true},
2✔
421
            {"isRecoveryModeDisabled", false},
2✔
422
            {"action", "FakeActionThatWillNeverExist"},
2✔
423
        };
2✔
424
        nlohmann::json test_command = {{"command", "ECHO_ERROR"},
2✔
425
                                       {"args", nlohmann::json{{"errorCode", 201}, {"errorBody", error_body}}}};
2✔
426
        auto test_cmd_res =
2✔
427
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
2✔
428
                .get();
2✔
429
        REQUIRE(test_cmd_res == "{}");
2!
430
        auto error = wait_for_future(std::move(error_future)).get();
2✔
431
        REQUIRE(error.status == ErrorCodes::RuntimeError);
2!
432
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::ApplicationBug);
2!
433
        REQUIRE(error.is_fatal);
2!
434
        REQUIRE_THAT(error.status.reason(), !Catch::Matchers::ContainsSubstring("Unknown sync protocol error code"));
2✔
435
        REQUIRE_THAT(error.status.reason(), Catch::Matchers::ContainsSubstring("fake error"));
2✔
436
    }
2✔
437

438

439
    SECTION("unknown connection-level errors are still errors") {
18✔
440
        auto r = Realm::get_shared_realm(config);
2✔
441
        wait_for_download(*r);
2✔
442
        nlohmann::json error_body = {{"tryAgain", false},
2✔
443
                                     {"message", "fake error"},
2✔
444
                                     {"shouldClientReset", false},
2✔
445
                                     {"isRecoveryModeDisabled", false},
2✔
446
                                     {"action", "ApplicationBug"}};
2✔
447
        nlohmann::json test_command = {{"command", "ECHO_ERROR"},
2✔
448
                                       {"args", nlohmann::json{{"errorCode", 199}, {"errorBody", error_body}}}};
2✔
449
        auto test_cmd_res =
2✔
450
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
2✔
451
                .get();
2✔
452
        REQUIRE(test_cmd_res == "{}");
2!
453
        auto error = wait_for_future(std::move(error_future)).get();
2✔
454
        REQUIRE(error.status == ErrorCodes::SyncProtocolInvariantFailed);
2!
455
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::ProtocolViolation);
2!
456
        REQUIRE(error.is_fatal);
2!
457
    }
2✔
458

459
    SECTION("client reset errors") {
18✔
460
        auto r = Realm::get_shared_realm(config);
6✔
461
        wait_for_download(*r);
6✔
462
        nlohmann::json error_body = {{"tryAgain", false},
6✔
463
                                     {"message", "fake error"},
6✔
464
                                     {"shouldClientReset", true},
6✔
465
                                     {"isRecoveryModeDisabled", false},
6✔
466
                                     {"action", "ClientReset"}};
6✔
467
        auto code = GENERATE(sync::ProtocolError::bad_client_file_ident, sync::ProtocolError::bad_server_version,
6✔
468
                             sync::ProtocolError::diverging_histories);
6✔
469
        nlohmann::json test_command = {{"command", "ECHO_ERROR"},
6✔
470
                                       {"args", nlohmann::json{{"errorCode", code}, {"errorBody", error_body}}}};
6✔
471
        auto test_cmd_res =
6✔
472
            wait_for_future(SyncSession::OnlyForTesting::send_test_command(*r->sync_session(), test_command.dump()))
6✔
473
                .get();
6✔
474
        REQUIRE(test_cmd_res == "{}");
6!
475
        auto error = wait_for_future(std::move(error_future)).get();
6✔
476
        REQUIRE(error.status == ErrorCodes::SyncClientResetRequired);
6!
477
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::ClientReset);
6!
478
        REQUIRE(error.is_client_reset_requested());
6!
479
        REQUIRE(error.is_fatal);
6!
480
    }
6✔
481

482

483
    SECTION("teardown") {
18✔
484
        harness.reset();
2✔
485
    }
2✔
486
}
18✔
487

488

489
TEST_CASE("flx: client reset", "[sync][flx][client reset][baas]") {
46✔
490
    std::vector<ObjectSchema> schema{
46✔
491
        {"TopLevel",
46✔
492
         {
46✔
493
             {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
46✔
494
             {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
46✔
495
             {"queryable_int_field", PropertyType::Int | PropertyType::Nullable},
46✔
496
             {"non_queryable_field", PropertyType::String | PropertyType::Nullable},
46✔
497
             {"list_of_ints_field", PropertyType::Int | PropertyType::Array},
46✔
498
             {"sum_of_list_field", PropertyType::Int},
46✔
499
             {"any_mixed", PropertyType::Mixed | PropertyType::Nullable},
46✔
500
             {"dictionary_mixed", PropertyType::Dictionary | PropertyType::Mixed | PropertyType::Nullable},
46✔
501
         }},
46✔
502
        {"TopLevel2",
46✔
503
         {
46✔
504
             {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
46✔
505
             {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
46✔
506
         }},
46✔
507
    };
46✔
508

509
    // some of these tests make additive schema changes which is only allowed in dev mode
510
    constexpr bool dev_mode = true;
46✔
511
    FLXSyncTestHarness harness("flx_client_reset",
46✔
512
                               {schema, {"queryable_str_field", "queryable_int_field"}, {}, dev_mode});
46✔
513

514
    auto add_object = [](SharedRealm realm, std::string str_field, int64_t int_field,
46✔
515
                         ObjectId oid = ObjectId::gen()) {
122✔
516
        CppContext c(realm);
122✔
517
        realm->begin_transaction();
122✔
518

519
        int64_t r1 = random_int();
122✔
520
        int64_t r2 = random_int();
122✔
521
        int64_t r3 = random_int();
122✔
522
        int64_t sum = uint64_t(r1) + r2 + r3;
122✔
523

524
        Object::create(c, realm, "TopLevel",
122✔
525
                       std::any(AnyDict{{"_id", oid},
122✔
526
                                        {"queryable_str_field", str_field},
122✔
527
                                        {"queryable_int_field", int_field},
122✔
528
                                        {"non_queryable_field", "non queryable 1"s},
122✔
529
                                        {"list_of_ints_field", std::vector<std::any>{r1, r2, r3}},
122✔
530
                                        {"sum_of_list_field", sum}}));
122✔
531
        realm->commit_transaction();
122✔
532
    };
122✔
533

534
    auto subscribe_to_and_add_objects = [&](SharedRealm realm, size_t num_objects) {
46✔
535
        auto table = realm->read_group().get_table("class_TopLevel");
40✔
536
        auto id_col = table->get_primary_key_column();
40✔
537
        auto sub_set = realm->get_latest_subscription_set();
40✔
538
        for (size_t i = 0; i < num_objects; ++i) {
130✔
539
            auto oid = ObjectId::gen();
90✔
540
            auto mut_sub = sub_set.make_mutable_copy();
90✔
541
            mut_sub.clear();
90✔
542
            mut_sub.insert_or_assign(Query(table).equal(id_col, oid));
90✔
543
            sub_set = mut_sub.commit();
90✔
544
            add_object(realm, util::format("added _id='%1'", oid), 0, oid);
90✔
545
        }
90✔
546
    };
40✔
547

548
    auto add_subscription_for_new_object = [&](SharedRealm realm, std::string str_field,
46✔
549
                                               int64_t int_field) -> sync::SubscriptionSet {
46✔
550
        auto table = realm->read_group().get_table("class_TopLevel");
28✔
551
        auto queryable_str_field = table->get_column_key("queryable_str_field");
28✔
552
        auto sub_set = realm->get_latest_subscription_set().make_mutable_copy();
28✔
553
        sub_set.insert_or_assign(Query(table).equal(queryable_str_field, StringData(str_field)));
28✔
554
        auto resulting_set = sub_set.commit();
28✔
555
        add_object(realm, str_field, int_field);
28✔
556
        return resulting_set;
28✔
557
    };
28✔
558

559
    auto add_invalid_subscription = [](SharedRealm realm) -> sync::SubscriptionSet {
46✔
560
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
561
        auto queryable_str_field = table->get_column_key("non_queryable_field");
2✔
562
        auto sub_set = realm->get_latest_subscription_set().make_mutable_copy();
2✔
563
        sub_set.insert_or_assign(Query(table).equal(queryable_str_field, "foo"));
2✔
564
        auto resulting_set = sub_set.commit();
2✔
565
        return resulting_set;
2✔
566
    };
2✔
567

568
    auto count_queries_with_str = [](sync::SubscriptionSet subs, std::string_view str) {
46✔
569
        size_t count = 0;
8✔
570
        for (auto sub : subs) {
14✔
571
            if (sub.query_string.find(str) != std::string::npos) {
14✔
572
                ++count;
6✔
573
            }
6✔
574
        }
14✔
575
        return count;
8✔
576
    };
8✔
577
    create_user_and_log_in(harness.app());
46✔
578
    auto user1 = harness.app()->current_user();
46✔
579
    create_user_and_log_in(harness.app());
46✔
580
    auto user2 = harness.app()->current_user();
46✔
581
    SyncTestFile config_local(user1, harness.schema(), SyncConfig::FLXSyncEnabled{});
46✔
582
    config_local.path += ".local";
46✔
583
    SyncTestFile config_remote(user2, harness.schema(), SyncConfig::FLXSyncEnabled{});
46✔
584
    config_remote.path += ".remote";
46✔
585
    const std::string str_field_value = "foo";
46✔
586
    const int64_t local_added_int = 100;
46✔
587
    const int64_t local_added_int2 = 150;
46✔
588
    const int64_t remote_added_int = 200;
46✔
589
    size_t before_reset_count = 0;
46✔
590
    size_t after_reset_count = 0;
46✔
591
    config_local.sync_config->notify_before_client_reset = [&before_reset_count](SharedRealm) {
46✔
592
        ++before_reset_count;
30✔
593
    };
30✔
594
    config_local.sync_config->notify_after_client_reset = [&after_reset_count](SharedRealm, ThreadSafeReference,
46✔
595
                                                                               bool) {
46✔
596
        ++after_reset_count;
×
597
    };
×
598

599
    SECTION("Recover: offline writes and subscription (single subscription)") {
46✔
600
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
601
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
602
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
603
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
604
        test_reset
2✔
605
            ->populate_initial_object([&](SharedRealm realm) {
2✔
606
                auto pk_of_added_object = ObjectId::gen();
2✔
607
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
608
                auto table = realm->read_group().get_table(ObjectStore::table_name_for_object_type("TopLevel"));
2✔
609
                REALM_ASSERT(table);
2✔
610
                mut_subs.insert_or_assign(Query(table));
2✔
611
                mut_subs.commit();
2✔
612

613
                realm->begin_transaction();
2✔
614
                CppContext c(realm);
2✔
615
                int64_t r1 = random_int();
2✔
616
                int64_t r2 = random_int();
2✔
617
                int64_t r3 = random_int();
2✔
618
                int64_t sum = uint64_t(r1) + r2 + r3;
2✔
619

620
                Object::create(c, realm, "TopLevel",
2✔
621
                               std::any(AnyDict{{"_id"s, pk_of_added_object},
2✔
622
                                                {"queryable_str_field"s, "initial value"s},
2✔
623
                                                {"list_of_ints_field", std::vector<std::any>{r1, r2, r3}},
2✔
624
                                                {"sum_of_list_field", sum}}));
2✔
625

626
                realm->commit_transaction();
2✔
627
                wait_for_upload(*realm);
2✔
628
                return pk_of_added_object;
2✔
629
            })
2✔
630
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
631
                add_object(local_realm, str_field_value, local_added_int);
2✔
632
            })
2✔
633
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
634
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
635
                sync::SubscriptionSet::State actual =
2✔
636
                    remote_realm->get_latest_subscription_set()
2✔
637
                        .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
638
                        .get();
2✔
639
                REQUIRE(actual == sync::SubscriptionSet::State::Complete);
2!
640
            })
2✔
641
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
642
                wait_for_advance(*local_realm);
2✔
643
                ClientResyncMode mode = client_reset_future.get();
2✔
644
                REQUIRE(mode == ClientResyncMode::Recover);
2!
645
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
646
                auto str_col = table->get_column_key("queryable_str_field");
2✔
647
                auto int_col = table->get_column_key("queryable_int_field");
2✔
648
                auto tv = table->where().equal(str_col, StringData(str_field_value)).find_all();
2✔
649
                tv.sort(int_col);
2✔
650
                // the object we created while offline was recovered, and the remote object was downloaded
651
                REQUIRE(tv.size() == 2);
2!
652
                CHECK(tv.get_object(0).get<Int>(int_col) == local_added_int);
2!
653
                CHECK(tv.get_object(1).get<Int>(int_col) == remote_added_int);
2!
654
            })
2✔
655
            ->run();
2✔
656
    }
2✔
657

658
    SECTION("Recover: subscription and offline writes after client reset failure") {
46✔
659
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
660
        auto&& [error_future, error_handler] = make_error_handler();
2✔
661
        config_local.sync_config->error_handler = error_handler;
2✔
662

663
        std::string fresh_path = realm::_impl::client_reset::get_fresh_path_for(config_local.path);
2✔
664
        // create a non-empty directory that we'll fail to delete
665
        util::make_dir(fresh_path);
2✔
666
        util::File(util::File::resolve("file", fresh_path), util::File::mode_Write);
2✔
667

668
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
669
        test_reset
2✔
670
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
671
                auto mut_sub = local_realm->get_latest_subscription_set().make_mutable_copy();
2✔
672
                auto table = local_realm->read_group().get_table("class_TopLevel2");
2✔
673
                mut_sub.insert_or_assign(Query(table));
2✔
674
                mut_sub.commit();
2✔
675

676
                CppContext c(local_realm);
2✔
677
                local_realm->begin_transaction();
2✔
678
                Object::create(c, local_realm, "TopLevel2",
2✔
679
                               std::any(AnyDict{{"_id"s, ObjectId::gen()}, {"queryable_str_field"s, "foo"s}}));
2✔
680
                local_realm->commit_transaction();
2✔
681
            })
2✔
682
            ->on_post_reset([](SharedRealm local_realm) {
2✔
683
                // Verify offline subscription was not removed.
684
                auto subs = local_realm->get_latest_subscription_set();
2✔
685
                auto table = local_realm->read_group().get_table("class_TopLevel2");
2✔
686
                REQUIRE(subs.find(Query(table)));
2!
687
            })
2✔
688
            ->run();
2✔
689

690
        // Remove the folder preventing the completion of a client reset.
691
        util::try_remove_dir_recursive(fresh_path);
2✔
692

693
        RealmConfig config_copy = config_local;
2✔
694
        config_copy.sync_config = std::make_shared<SyncConfig>(*config_copy.sync_config);
2✔
695
        config_copy.sync_config->error_handler = nullptr;
2✔
696
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
697
        config_copy.sync_config->notify_after_client_reset = reset_handler;
2✔
698

699
        // Attempt to open the realm again.
700
        // This time the client reset succeeds and the offline subscription and writes are recovered.
701
        auto realm = Realm::get_shared_realm(config_copy);
2✔
702
        ClientResyncMode mode = reset_future.get();
2✔
703
        REQUIRE(mode == ClientResyncMode::Recover);
2!
704

705
        auto table = realm->read_group().get_table("class_TopLevel2");
2✔
706
        auto str_col = table->get_column_key("queryable_str_field");
2✔
707
        REQUIRE(table->size() == 1);
2!
708
        REQUIRE(table->get_object(0).get<String>(str_col) == "foo");
2!
709
    }
2✔
710

711
    SECTION("Recover: offline writes and subscriptions (multiple subscriptions)") {
46✔
712
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
713
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
714
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
715
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
716
        test_reset
2✔
717
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
718
                add_subscription_for_new_object(local_realm, str_field_value, local_added_int);
2✔
719
            })
2✔
720
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
721
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
722
                sync::SubscriptionSet::State actual =
2✔
723
                    remote_realm->get_latest_subscription_set()
2✔
724
                        .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
725
                        .get();
2✔
726
                REQUIRE(actual == sync::SubscriptionSet::State::Complete);
2!
727
            })
2✔
728
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
729
                ClientResyncMode mode = client_reset_future.get();
2✔
730
                REQUIRE(mode == ClientResyncMode::Recover);
2!
731
                auto subs = local_realm->get_latest_subscription_set();
2✔
732
                subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
733
                subs.refresh();
2✔
734
                // make sure that the subscription for "foo" survived the reset
735
                size_t count_of_foo = count_queries_with_str(subs, util::format("\"%1\"", str_field_value));
2✔
736
                REQUIRE(subs.state() == sync::SubscriptionSet::State::Complete);
2!
737
                REQUIRE(count_of_foo == 1);
2!
738
                local_realm->refresh();
2✔
739
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
740
                auto str_col = table->get_column_key("queryable_str_field");
2✔
741
                auto int_col = table->get_column_key("queryable_int_field");
2✔
742
                auto tv = table->where().equal(str_col, StringData(str_field_value)).find_all();
2✔
743
                tv.sort(int_col);
2✔
744
                // the object we created while offline was recovered, and the remote object was downloaded
745
                REQUIRE(tv.size() == 2);
2!
746
                CHECK(tv.get_object(0).get<Int>(int_col) == local_added_int);
2!
747
                CHECK(tv.get_object(1).get<Int>(int_col) == remote_added_int);
2!
748
            })
2✔
749
            ->run();
2✔
750
    }
2✔
751

752
    SECTION("Recover: offline writes interleaved with subscriptions and empty writes") {
46✔
753
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
754
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
755
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
756
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
757
        test_reset
2✔
758
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
759
                // The sequence of events bellow generates five changesets:
760
                //  1. create sub1 => empty changeset
761
                //  2. create local_added_int object
762
                //  3. create empty changeset
763
                //  4. create sub2 => empty changeset
764
                //  5. create local_added_int2 object
765
                //
766
                // Before sending 'sub2' to the server, an UPLOAD message is sent first.
767
                // The upload message contains changeset 2. (local_added_int) with the cursor
768
                // of changeset 3. (empty changeset).
769

770
                add_subscription_for_new_object(local_realm, str_field_value, local_added_int);
2✔
771
                // Commit empty changeset.
772
                local_realm->begin_transaction();
2✔
773
                local_realm->commit_transaction();
2✔
774
                add_subscription_for_new_object(local_realm, str_field_value, local_added_int2);
2✔
775
            })
2✔
776
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
777
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
778
                sync::SubscriptionSet::State actual =
2✔
779
                    remote_realm->get_latest_subscription_set()
2✔
780
                        .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
781
                        .get();
2✔
782
                REQUIRE(actual == sync::SubscriptionSet::State::Complete);
2!
783
            })
2✔
784
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
785
                ClientResyncMode mode = client_reset_future.get();
2✔
786
                REQUIRE(mode == ClientResyncMode::Recover);
2!
787
                auto subs = local_realm->get_latest_subscription_set();
2✔
788
                subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
789
                // make sure that the subscription for "foo" survived the reset
790
                size_t count_of_foo = count_queries_with_str(subs, util::format("\"%1\"", str_field_value));
2✔
791
                subs.refresh();
2✔
792
                REQUIRE(subs.state() == sync::SubscriptionSet::State::Complete);
2!
793
                REQUIRE(count_of_foo == 1);
2!
794
                local_realm->refresh();
2✔
795
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
796
                auto str_col = table->get_column_key("queryable_str_field");
2✔
797
                auto int_col = table->get_column_key("queryable_int_field");
2✔
798
                auto tv = table->where().equal(str_col, StringData(str_field_value)).find_all();
2✔
799
                tv.sort(int_col);
2✔
800
                // the objects we created while offline was recovered, and the remote object was downloaded
801
                REQUIRE(tv.size() == 3);
2!
802
                CHECK(tv.get_object(0).get<Int>(int_col) == local_added_int);
2!
803
                CHECK(tv.get_object(1).get<Int>(int_col) == local_added_int2);
2!
804
                CHECK(tv.get_object(2).get<Int>(int_col) == remote_added_int);
2!
805
            })
2✔
806
            ->run();
2✔
807
    }
2✔
808

809
    auto validate_integrity_of_arrays = [](TableRef table) -> size_t {
46✔
810
        auto sum_col = table->get_column_key("sum_of_list_field");
16✔
811
        auto array_col = table->get_column_key("list_of_ints_field");
16✔
812
        auto query = table->column<Lst<Int>>(array_col).sum() == table->column<Int>(sum_col) &&
16✔
813
                     table->column<Lst<Int>>(array_col).size() > 0;
16✔
814
        return query.count();
16✔
815
    };
16✔
816

817
    SECTION("Recover: offline writes with associated subscriptions in the correct order") {
46✔
818
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
819
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
820
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
821
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
822
        constexpr size_t num_objects_added = 20;
2✔
823
        constexpr size_t num_objects_added_by_harness = 1; // BaasFLXClientReset.run()
2✔
824
        constexpr size_t num_objects_added_by_remote = 1;  // make_remote_changes()
2✔
825
        test_reset
2✔
826
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
827
                subscribe_to_and_add_objects(local_realm, num_objects_added);
2✔
828
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
829
                REQUIRE(table->size() == num_objects_added + num_objects_added_by_harness);
2!
830
                size_t count_of_valid_array_data = validate_integrity_of_arrays(table);
2✔
831
                REQUIRE(count_of_valid_array_data == num_objects_added);
2!
832
            })
2✔
833
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
834
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
835
                sync::SubscriptionSet::State actual =
2✔
836
                    remote_realm->get_latest_subscription_set()
2✔
837
                        .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
838
                        .get();
2✔
839
                REQUIRE(actual == sync::SubscriptionSet::State::Complete);
2!
840
            })
2✔
841
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
842
                ClientResyncMode mode = client_reset_future.get();
2✔
843
                REQUIRE(mode == ClientResyncMode::Recover);
2!
844
                local_realm->refresh();
2✔
845
                auto latest_subs = local_realm->get_latest_subscription_set();
2✔
846
                auto state = latest_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
847
                REQUIRE(state == sync::SubscriptionSet::State::Complete);
2!
848
                local_realm->refresh();
2✔
849
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
850
                if (table->size() != 1) {
2✔
851
                    table->to_json(std::cout);
×
UNCOV
852
                }
×
853
                REQUIRE(table->size() == 1);
2!
854
                auto mut_sub = latest_subs.make_mutable_copy();
2✔
855
                mut_sub.clear();
2✔
856
                mut_sub.insert_or_assign(Query(table));
2✔
857
                latest_subs = mut_sub.commit();
2✔
858
                latest_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
859
                local_realm->refresh();
2✔
860
                REQUIRE(table->size() ==
2!
861
                        num_objects_added + num_objects_added_by_harness + num_objects_added_by_remote);
2✔
862
                size_t count_of_valid_array_data = validate_integrity_of_arrays(table);
2✔
863
                REQUIRE(count_of_valid_array_data == num_objects_added + num_objects_added_by_remote);
2!
864
            })
2✔
865
            ->run();
2✔
866
    }
2✔
867

868
    SECTION("Recover: incompatible property changes are rejected") {
46✔
869
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
870
        auto&& [error_future, err_handler] = make_error_handler();
2✔
871
        config_local.sync_config->error_handler = err_handler;
2✔
872
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
873
        constexpr size_t num_objects_added_before = 2;
2✔
874
        constexpr size_t num_objects_added_after = 2;
2✔
875
        constexpr size_t num_objects_added_by_harness = 1; // BaasFLXClientReset.run()
2✔
876
        constexpr std::string_view added_property_name = "new_property";
2✔
877
        test_reset
2✔
878
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
879
                subscribe_to_and_add_objects(local_realm, num_objects_added_before);
2✔
880
                Schema local_update = schema;
2✔
881
                Schema::iterator it = local_update.find("TopLevel");
2✔
882
                REQUIRE(it != local_update.end());
2!
883
                it->persisted_properties.push_back(
2✔
884
                    {std::string(added_property_name), PropertyType::Float | PropertyType::Nullable});
2✔
885
                local_realm->update_schema(local_update);
2✔
886
                subscribe_to_and_add_objects(local_realm, num_objects_added_after);
2✔
887
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
888
                REQUIRE(table->size() ==
2!
889
                        num_objects_added_before + num_objects_added_after + num_objects_added_by_harness);
2✔
890
                size_t count_of_valid_array_data = validate_integrity_of_arrays(table);
2✔
891
                REQUIRE(count_of_valid_array_data == num_objects_added_before + num_objects_added_after);
2!
892
            })
2✔
893
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
894
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
895
                Schema remote_update = schema;
2✔
896
                Schema::iterator it = remote_update.find("TopLevel");
2✔
897
                REQUIRE(it != remote_update.end());
2!
898
                it->persisted_properties.push_back(
2✔
899
                    {std::string(added_property_name), PropertyType::UUID | PropertyType::Nullable});
2✔
900
                remote_realm->update_schema(remote_update);
2✔
901
                sync::SubscriptionSet::State actual =
2✔
902
                    remote_realm->get_latest_subscription_set()
2✔
903
                        .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
904
                        .get();
2✔
905
                REQUIRE(actual == sync::SubscriptionSet::State::Complete);
2!
906
            })
2✔
907
            ->on_post_reset([&, err_future = std::move(error_future)](SharedRealm local_realm) mutable {
2✔
908
                auto sync_error = wait_for_future(std::move(err_future)).get();
2✔
909
                REQUIRE(before_reset_count == 1);
2!
910
                REQUIRE(after_reset_count == 0);
2!
911
                REQUIRE(sync_error.status == ErrorCodes::AutoClientResetFailed);
2!
912
                REQUIRE(sync_error.status.reason().find(
2!
913
                            "SyncClientResetRequired: Bad client file identifier (IDENT)") != std::string::npos);
2✔
914
                REQUIRE(sync_error.is_client_reset_requested());
2!
915
                local_realm->refresh();
2✔
916
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
917
                // since schema validation happens in the first recovery commit, that whole commit is rolled back
918
                // and the final state here is "pre reset"
919
                REQUIRE(table->size() ==
2!
920
                        num_objects_added_before + num_objects_added_by_harness + num_objects_added_after);
2✔
921
                size_t count_of_valid_array_data = validate_integrity_of_arrays(table);
2✔
922
                REQUIRE(count_of_valid_array_data == num_objects_added_before + num_objects_added_after);
2!
923
            })
2✔
924
            ->run();
2✔
925
    }
2✔
926

927
    SECTION("unsuccessful replay of local changes") {
46✔
928
        constexpr size_t num_objects_added_before = 2;
4✔
929
        constexpr size_t num_objects_added_after = 2;
4✔
930
        constexpr size_t num_objects_added_by_harness = 1; // BaasFLXClientReset.run()
4✔
931
        constexpr std::string_view added_property_name = "new_property";
4✔
932
        auto&& [error_future, err_handler] = make_error_handler();
4✔
933
        config_local.sync_config->error_handler = err_handler;
4✔
934

935
        // The local changes here are a bit contrived because removing a column is disallowed
936
        // at the object store layer for sync'd Realms. The only reason a recovery should fail in production
937
        // during the apply stage is due to programmer error or external factors such as out of disk space.
938
        // Any schema discrepancies are caught by the initial diff, so the way to make a recovery fail here is
939
        // to add and remove a column at the core level such that the schema diff passes, but instructions are
940
        // generated which will fail when applied.
941
        auto make_local_changes_that_will_fail = [&](SharedRealm local_realm) {
4✔
942
            subscribe_to_and_add_objects(local_realm, num_objects_added_before);
4✔
943
            auto table = local_realm->read_group().get_table("class_TopLevel");
4✔
944
            REQUIRE(table->size() == num_objects_added_before + num_objects_added_by_harness);
4!
945
            size_t count_of_valid_array_data = validate_integrity_of_arrays(table);
4✔
946
            REQUIRE(count_of_valid_array_data == num_objects_added_before);
4!
947
            local_realm->begin_transaction();
4✔
948
            ColKey added = table->add_column(type_Int, added_property_name);
4✔
949
            table->remove_column(added);
4✔
950
            local_realm->commit_transaction();
4✔
951
            subscribe_to_and_add_objects(local_realm, num_objects_added_after); // these are lost!
4✔
952
        };
4✔
953

954
        VersionID expected_version;
4✔
955

956
        auto store_pre_reset_state = [&](SharedRealm local_realm) {
4✔
957
            expected_version = local_realm->read_transaction_version();
4✔
958
        };
4✔
959

960
        auto verify_post_reset_state = [&, err_future = std::move(error_future)](SharedRealm local_realm) {
4✔
961
            auto sync_error = err_future.get();
4✔
962
            REQUIRE(before_reset_count == 1);
4!
963
            REQUIRE(after_reset_count == 0);
4!
964
            REQUIRE(sync_error.status == ErrorCodes::AutoClientResetFailed);
4!
965
            REQUIRE(sync_error.is_client_reset_requested());
4!
966

967
            // All changes should have been rolled back when recovery hit remove_column(),
968
            // leaving the Realm in the pre-reset state
969
            local_realm->refresh();
4✔
970
            auto table = local_realm->read_group().get_table("class_TopLevel");
4✔
971
            ColKey added = table->get_column_key(added_property_name);
4✔
972
            REQUIRE(!added);
4!
973
            const size_t expected_added_objects = num_objects_added_before + num_objects_added_after;
4✔
974
            REQUIRE(table->size() == num_objects_added_by_harness + expected_added_objects);
4!
975
            size_t count_of_valid_array_data = validate_integrity_of_arrays(table);
4✔
976
            REQUIRE(count_of_valid_array_data == expected_added_objects);
4!
977

978
            // The attempted client reset should have been recorded so that we
979
            // don't attempt it again
980
            REQUIRE(local_realm->read_transaction_version().version == expected_version.version + 1);
4!
981
        };
4✔
982

983
        SECTION("Recover: unsuccessful recovery leads to a manual reset") {
4✔
984
            config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
985
            auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
986
            test_reset->make_local_changes(make_local_changes_that_will_fail)
2✔
987
                ->on_post_local_changes(store_pre_reset_state)
2✔
988
                ->on_post_reset(std::move(verify_post_reset_state))
2✔
989
                ->run();
2✔
990
            RealmConfig config_copy = config_local;
2✔
991
            auto&& [error_future2, err_handler2] = make_error_handler();
2✔
992
            config_copy.sync_config->error_handler = err_handler2;
2✔
993
            auto realm_post_reset = Realm::get_shared_realm(config_copy);
2✔
994
            auto sync_error = wait_for_future(std::move(error_future2)).get();
2✔
995
            REQUIRE(before_reset_count == 2);
2!
996
            REQUIRE(after_reset_count == 0);
2!
997
            REQUIRE(sync_error.status == ErrorCodes::AutoClientResetFailed);
2!
998
            REQUIRE(sync_error.is_client_reset_requested());
2!
999
        }
2✔
1000

1001
        SECTION("RecoverOrDiscard: unsuccessful reapply leads to discard") {
4✔
1002
            config_local.sync_config->client_resync_mode = ClientResyncMode::RecoverOrDiscard;
2✔
1003
            auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1004
            test_reset->make_local_changes(make_local_changes_that_will_fail)
2✔
1005
                ->on_post_local_changes(store_pre_reset_state)
2✔
1006
                ->on_post_reset(std::move(verify_post_reset_state))
2✔
1007
                ->run();
2✔
1008

1009
            RealmConfig config_copy = config_local;
2✔
1010
            auto&& [client_reset_future, reset_handler] = make_client_reset_handler();
2✔
1011
            config_copy.sync_config->error_handler = [](std::shared_ptr<SyncSession>, SyncError err) {
2✔
1012
                REALM_ASSERT_EX(!err.is_fatal, err.status);
×
1013
                CHECK(err.server_requests_action == sync::ProtocolErrorInfo::Action::Transient);
×
UNCOV
1014
            };
×
1015
            config_copy.sync_config->notify_after_client_reset = reset_handler;
2✔
1016
            auto realm_post_reset = Realm::get_shared_realm(config_copy);
2✔
1017
            ClientResyncMode mode = wait_for_future(std::move(client_reset_future)).get();
2✔
1018
            REQUIRE(mode == ClientResyncMode::DiscardLocal);
2!
1019
            realm_post_reset->refresh();
2✔
1020
            auto table = realm_post_reset->read_group().get_table("class_TopLevel");
2✔
1021
            ColKey added = table->get_column_key(added_property_name);
2✔
1022
            REQUIRE(!added);                                        // reverted local changes
2!
1023
            REQUIRE(table->size() == num_objects_added_by_harness); // discarded all offline local changes
2!
1024
        }
2✔
1025
    }
4✔
1026

1027
    SECTION("DiscardLocal: offline writes and subscriptions are lost") {
46✔
1028
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1029
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
1030
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
1031
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1032
        test_reset
2✔
1033
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
1034
                add_subscription_for_new_object(local_realm, str_field_value, local_added_int);
2✔
1035
            })
2✔
1036
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
1037
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
1038
            })
2✔
1039
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) mutable {
2✔
1040
                ClientResyncMode mode = wait_for_future(std::move(client_reset_future)).get();
2✔
1041
                REQUIRE(mode == ClientResyncMode::DiscardLocal);
2!
1042
                auto subs = local_realm->get_latest_subscription_set();
2✔
1043
                wait_for_future(subs.get_state_change_notification(sync::SubscriptionSet::State::Complete)).get();
2✔
1044
                local_realm->refresh();
2✔
1045
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
1046
                auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
1047
                auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
1048
                auto tv = table->where().equal(queryable_str_field, StringData(str_field_value)).find_all();
2✔
1049
                // the object we created while offline was discarded, and the remote object was not downloaded
1050
                REQUIRE(tv.size() == 0);
2!
1051
                size_t count_of_foo = count_queries_with_str(subs, util::format("\"%1\"", str_field_value));
2✔
1052
                // make sure that the subscription for "foo" did not survive the reset
1053
                REQUIRE(count_of_foo == 0);
2!
1054
                REQUIRE(subs.state() == sync::SubscriptionSet::State::Complete);
2!
1055

1056
                // adding data and subscriptions to a reset Realm works as normal
1057
                add_subscription_for_new_object(local_realm, str_field_value, local_added_int);
2✔
1058
                auto latest_subs = local_realm->get_latest_subscription_set();
2✔
1059
                REQUIRE(latest_subs.version() > subs.version());
2!
1060
                wait_for_future(latest_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete))
2✔
1061
                    .get();
2✔
1062
                local_realm->refresh();
2✔
1063
                count_of_foo = count_queries_with_str(latest_subs, util::format("\"%1\"", str_field_value));
2✔
1064
                REQUIRE(count_of_foo == 1);
2!
1065
                tv = table->where().equal(queryable_str_field, StringData(str_field_value)).find_all();
2✔
1066
                REQUIRE(tv.size() == 2);
2!
1067
                tv.sort(queryable_int_field);
2✔
1068
                REQUIRE(tv.get_object(0).get<int64_t>(queryable_int_field) == local_added_int);
2!
1069
                REQUIRE(tv.get_object(1).get<int64_t>(queryable_int_field) == remote_added_int);
2!
1070
            })
2✔
1071
            ->run();
2✔
1072
    }
2✔
1073

1074
    SECTION("DiscardLocal: an invalid subscription made while offline becomes superseded") {
46✔
1075
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1076
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
1077
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
1078
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1079
        std::unique_ptr<sync::SubscriptionSet> invalid_sub;
2✔
1080
        test_reset
2✔
1081
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
1082
                invalid_sub = std::make_unique<sync::SubscriptionSet>(add_invalid_subscription(local_realm));
2✔
1083
                add_subscription_for_new_object(local_realm, str_field_value, local_added_int);
2✔
1084
            })
2✔
1085
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
1086
                add_subscription_for_new_object(remote_realm, str_field_value, remote_added_int);
2✔
1087
            })
2✔
1088
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
1089
                local_realm->refresh();
2✔
1090
                sync::SubscriptionSet::State actual =
2✔
1091
                    invalid_sub->get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1092
                REQUIRE(actual == sync::SubscriptionSet::State::Superseded);
2!
1093
                ClientResyncMode mode = client_reset_future.get();
2✔
1094
                REQUIRE(mode == ClientResyncMode::DiscardLocal);
2!
1095
            })
2✔
1096
            ->run();
2✔
1097
    }
2✔
1098

1099
    SECTION("DiscardLocal: an error is produced if a previously successful query becomes invalid due to "
46✔
1100
            "server changes across a reset") {
2✔
1101
        // Disable dev mode so non-queryable fields are not automatically added as queryable
1102
        const AppSession& app_session = harness.session().app_session();
2✔
1103
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, false);
2✔
1104
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1105
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1106
        config_local.sync_config->error_handler = err_handler;
2✔
1107
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1108
        test_reset
2✔
1109
            ->setup([&](SharedRealm realm) {
2✔
1110
                if (realm->sync_session()->path() == config_local.path) {
2✔
1111
                    auto added_sub = add_subscription_for_new_object(realm, str_field_value, 0);
2✔
1112
                    added_sub.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1113
                }
2✔
1114
            })
2✔
1115
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
1116
                add_object(local_realm, str_field_value, local_added_int);
2✔
1117
                // Make "queryable_str_field" not a valid query field.
1118
                // Pre-reset, the Realm had a successful query on it, but now when the client comes back online
1119
                // and tries to reset, the fresh Realm download will fail with a query error.
1120
                const AppSession& app_session = harness.session().app_session();
2✔
1121
                auto baas_sync_service = app_session.admin_api.get_sync_service(app_session.server_app_id);
2✔
1122
                auto baas_sync_config =
2✔
1123
                    app_session.admin_api.get_config(app_session.server_app_id, baas_sync_service);
2✔
1124
                REQUIRE(baas_sync_config.queryable_field_names->is_array());
2!
1125
                auto it = baas_sync_config.queryable_field_names->begin();
2✔
1126
                for (; it != baas_sync_config.queryable_field_names->end(); ++it) {
2✔
1127
                    if (*it == "queryable_str_field") {
2✔
1128
                        break;
2✔
1129
                    }
2✔
1130
                }
2✔
1131
                REQUIRE(it != baas_sync_config.queryable_field_names->end());
2!
1132
                baas_sync_config.queryable_field_names->erase(it);
2✔
1133
                app_session.admin_api.enable_sync(app_session.server_app_id, baas_sync_service.id, baas_sync_config);
2✔
1134
            })
2✔
1135
            ->on_post_reset([&, err_future = std::move(error_future)](SharedRealm) mutable {
2✔
1136
                auto sync_error = wait_for_future(std::move(err_future)).get();
2✔
1137
                INFO(sync_error.status);
2✔
1138
                CHECK(sync_error.status == ErrorCodes::AutoClientResetFailed);
2!
1139
                REQUIRE(sync_error.status.reason().find(
2!
1140
                            "SyncClientResetRequired: Bad client file identifier (IDENT)") != std::string::npos);
2✔
1141
            })
2✔
1142
            ->run();
2✔
1143
    }
2✔
1144

1145
    SECTION("DiscardLocal: completion callbacks fire after client reset even when there is no data to download") {
46✔
1146
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1147
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
1148
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
1149
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1150
        test_reset
2✔
1151
            ->on_post_local_changes([&](SharedRealm realm) {
2✔
1152
                wait_for_upload(*realm);
2✔
1153
                wait_for_download(*realm);
2✔
1154
            })
2✔
1155
            ->run();
2✔
1156
    }
2✔
1157

1158
    SECTION("DiscardLocal: open realm after client reset failure") {
46✔
1159
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1160
        auto&& [error_future, error_handler] = make_error_handler();
2✔
1161
        config_local.sync_config->error_handler = error_handler;
2✔
1162

1163
        std::string fresh_path = realm::_impl::client_reset::get_fresh_path_for(config_local.path);
2✔
1164
        // create a non-empty directory that we'll fail to delete
1165
        util::make_dir(fresh_path);
2✔
1166
        util::File(util::File::resolve("file", fresh_path), util::File::mode_Write);
2✔
1167

1168
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1169
        test_reset->run();
2✔
1170

1171
        // Client reset fails due to sync client not being able to create the fresh realm.
1172
        auto sync_error = wait_for_future(std::move(error_future)).get();
2✔
1173
        REQUIRE(sync_error.status == ErrorCodes::AutoClientResetFailed);
2!
1174

1175
        // Open the realm again. This should not crash.
1176
        auto&& [err_future, err_handler] = make_error_handler();
2✔
1177
        config_local.sync_config->error_handler = std::move(err_handler);
2✔
1178

1179
        auto realm_post_reset = Realm::get_shared_realm(config_local);
2✔
1180
        sync_error = wait_for_future(std::move(err_future)).get();
2✔
1181
        REQUIRE(sync_error.status == ErrorCodes::AutoClientResetFailed);
2!
1182
    }
2✔
1183

1184
    enum class ResetMode { NoReset, InitiateClientReset };
46✔
1185
    auto seed_realm = [&harness, &subscribe_to_and_add_objects](RealmConfig config, ResetMode reset_mode) {
46✔
1186
        config.sync_config->error_handler = [path = config.path](std::shared_ptr<SyncSession>, SyncError err) {
26✔
1187
            // ignore spurious failures on this instance
1188
            util::format(std::cout, "spurious error while seeding a Realm at '%1': %2\n", path, err.status);
×
UNCOV
1189
        };
×
1190
        SharedRealm realm = Realm::get_shared_realm(config);
26✔
1191
        subscribe_to_and_add_objects(realm, 1);
26✔
1192
        auto subs = realm->get_latest_subscription_set();
26✔
1193
        auto result = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
26✔
1194
        CHECK(result == sync::SubscriptionSet::State::Complete);
26!
1195
        if (reset_mode == ResetMode::InitiateClientReset) {
26✔
1196
            reset_utils::trigger_client_reset(harness.session().app_session(), realm);
18✔
1197
        }
18✔
1198
        realm->close();
26✔
1199
    };
26✔
1200

1201
    auto setup_reset_handlers_for_schema_validation =
46✔
1202
        [&before_reset_count, &after_reset_count](RealmConfig& config, Schema expected_schema) {
46✔
1203
            auto& sync_config = *config.sync_config;
14✔
1204
            sync_config.error_handler = [](std::shared_ptr<SyncSession>, SyncError err) {
14✔
1205
                FAIL(err.status);
×
UNCOV
1206
            };
×
1207
            sync_config.notify_before_client_reset = [&before_reset_count,
14✔
1208
                                                      expected = expected_schema](SharedRealm frozen_before) {
14✔
1209
                ++before_reset_count;
14✔
1210
                REQUIRE(frozen_before->schema().size() > 0);
14!
1211
                REQUIRE(frozen_before->schema_version() != ObjectStore::NotVersioned);
14!
1212
                REQUIRE(frozen_before->schema() == expected);
14!
1213
            };
14✔
1214

1215
            auto [promise, future] = util::make_promise_future<void>();
14✔
1216
            sync_config.notify_after_client_reset =
14✔
1217
                [&after_reset_count, promise = util::CopyablePromiseHolder<void>(std::move(promise)), expected_schema,
14✔
1218
                 reset_mode = config.sync_config->client_resync_mode, has_schema = config.schema.has_value()](
14✔
1219
                    SharedRealm frozen_before, ThreadSafeReference after_ref, bool did_recover) mutable {
14✔
1220
                    ++after_reset_count;
14✔
1221
                    REQUIRE(frozen_before->schema().size() > 0);
14!
1222
                    REQUIRE(frozen_before->schema_version() != ObjectStore::NotVersioned);
14!
1223
                    REQUIRE(frozen_before->schema() == expected_schema);
14!
1224
                    SharedRealm after = Realm::get_shared_realm(std::move(after_ref), util::Scheduler::make_dummy());
14✔
1225
                    if (!has_schema) {
14✔
1226
                        after->set_schema_subset(expected_schema);
4✔
1227
                    }
4✔
1228
                    REQUIRE(after);
14!
1229
                    REQUIRE(after->schema() == expected_schema);
14!
1230
                    // the above check is sufficient unless operator==() is changed to not care about ordering
1231
                    // so future proof that by explicitly checking the order of properties here as well
1232
                    REQUIRE(after->schema().size() == frozen_before->schema().size());
14!
1233
                    auto after_it = after->schema().find("TopLevel");
14✔
1234
                    auto before_it = frozen_before->schema().find("TopLevel");
14✔
1235
                    REQUIRE(after_it != after->schema().end());
14!
1236
                    REQUIRE(before_it != frozen_before->schema().end());
14!
1237
                    REQUIRE(after_it->name == before_it->name);
14!
1238
                    REQUIRE(after_it->persisted_properties.size() == before_it->persisted_properties.size());
14!
1239
                    REQUIRE(after_it->persisted_properties[1].name == "queryable_int_field");
14!
1240
                    REQUIRE(after_it->persisted_properties[2].name == "queryable_str_field");
14!
1241
                    REQUIRE(before_it->persisted_properties[1].name == "queryable_int_field");
14!
1242
                    REQUIRE(before_it->persisted_properties[2].name == "queryable_str_field");
14!
1243
                    REQUIRE(did_recover == (reset_mode == ClientResyncMode::Recover));
14!
1244
                    promise.get_promise().emplace_value();
14✔
1245
                };
14✔
1246
            return std::move(future); // move is not redundant here because of how destructing works
14✔
1247
        };
14✔
1248

1249
    SECTION("Recover: schema indexes match in before and after states") {
46✔
1250
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1251
        // reorder a property such that it does not match the on disk property order
1252
        std::vector<ObjectSchema> local_schema = schema;
2✔
1253
        std::swap(local_schema[0].persisted_properties[1], local_schema[0].persisted_properties[2]);
2✔
1254
        local_schema[0].persisted_properties.push_back(
2✔
1255
            {"queryable_oid_field", PropertyType::ObjectId | PropertyType::Nullable});
2✔
1256
        config_local.schema = local_schema;
2✔
1257
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1258
        auto future = setup_reset_handlers_for_schema_validation(config_local, local_schema);
2✔
1259
        SharedRealm realm = Realm::get_shared_realm(config_local);
2✔
1260
        future.get();
2✔
1261
        CHECK(before_reset_count == 1);
2!
1262
        CHECK(after_reset_count == 1);
2!
1263
    }
2✔
1264

1265
    SECTION("Adding a local property matching a server addition is allowed") {
46✔
1266
        auto mode = GENERATE(ClientResyncMode::DiscardLocal, ClientResyncMode::Recover);
4✔
1267
        config_local.sync_config->client_resync_mode = mode;
4✔
1268
        CHECK_NOTHROW(seed_realm(config_local, ResetMode::InitiateClientReset));
4✔
1269
        std::vector<ObjectSchema> changed_schema = schema;
4✔
1270
        changed_schema[0].persisted_properties.push_back(
4✔
1271
            {"queryable_oid_field", PropertyType::ObjectId | PropertyType::Nullable});
4✔
1272
        // In a separate Realm, make the property addition.
1273
        // Since this is dev mode, it will be added to the server's schema.
1274
        config_remote.schema = changed_schema;
4✔
1275
        CHECK_NOTHROW(seed_realm(config_remote, ResetMode::NoReset));
4✔
1276
        std::swap(changed_schema[0].persisted_properties[1], changed_schema[0].persisted_properties[2]);
4✔
1277
        config_local.schema = changed_schema;
4✔
1278
        auto future = setup_reset_handlers_for_schema_validation(config_local, changed_schema);
4✔
1279
        successfully_async_open_realm(config_local);
4✔
1280
        CHECK_NOTHROW(future.get());
4✔
1281
        CHECK(before_reset_count == 1);
4!
1282
        CHECK(after_reset_count == 1);
4!
1283
    }
4✔
1284

1285
    SECTION("Adding a local property matching a server addition inside the before reset callback is allowed") {
46✔
1286
        auto mode = GENERATE(ClientResyncMode::DiscardLocal, ClientResyncMode::Recover);
4✔
1287
        config_local.sync_config->client_resync_mode = mode;
4✔
1288
        seed_realm(config_local, ResetMode::InitiateClientReset);
4✔
1289
        std::vector<ObjectSchema> changed_schema = schema;
4✔
1290
        changed_schema[0].persisted_properties.push_back(
4✔
1291
            {"queryable_oid_field", PropertyType::ObjectId | PropertyType::Nullable});
4✔
1292
        // In a separate Realm, make the property addition.
1293
        // Since this is dev mode, it will be added to the server's schema.
1294
        config_remote.schema = changed_schema;
4✔
1295
        seed_realm(config_remote, ResetMode::NoReset);
4✔
1296
        std::swap(changed_schema[0].persisted_properties[1], changed_schema[0].persisted_properties[2]);
4✔
1297
        config_local.schema.reset();
4✔
1298
        config_local.sync_config->freeze_before_reset_realm = false;
4✔
1299
        auto future = setup_reset_handlers_for_schema_validation(config_local, changed_schema);
4✔
1300

1301
        auto notify_before = std::move(config_local.sync_config->notify_before_client_reset);
4✔
1302
        config_local.sync_config->notify_before_client_reset = [=](std::shared_ptr<Realm> realm) {
4✔
1303
            realm->update_schema(changed_schema);
4✔
1304
            notify_before(realm);
4✔
1305
        };
4✔
1306

1307
        auto notify_after = std::move(config_local.sync_config->notify_after_client_reset);
4✔
1308
        config_local.sync_config->notify_after_client_reset = [=](std::shared_ptr<Realm> before,
4✔
1309
                                                                  ThreadSafeReference after, bool did_recover) {
4✔
1310
            before->set_schema_subset(changed_schema);
4✔
1311
            notify_after(before, std::move(after), did_recover);
4✔
1312
        };
4✔
1313

1314
        successfully_async_open_realm(config_local);
4✔
1315
        future.get();
4✔
1316
        CHECK(before_reset_count == 1);
4!
1317
        CHECK(after_reset_count == 1);
4!
1318
    }
4✔
1319

1320
    auto make_additive_changes = [](std::vector<ObjectSchema> schema) {
46✔
1321
        schema[0].persisted_properties.push_back(
6✔
1322
            {"added_oid_field", PropertyType::ObjectId | PropertyType::Nullable});
6✔
1323
        std::swap(schema[0].persisted_properties[1], schema[0].persisted_properties[2]);
6✔
1324
        schema.push_back({"AddedClass",
6✔
1325
                          {
6✔
1326
                              {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
6✔
1327
                              {"str_field", PropertyType::String | PropertyType::Nullable},
6✔
1328
                          }});
6✔
1329
        return schema;
6✔
1330
    };
6✔
1331
    SECTION("Recover: additive schema changes are recovered in dev mode") {
46✔
1332
        const AppSession& app_session = harness.session().app_session();
2✔
1333
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, true);
2✔
1334
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1335
        std::vector<ObjectSchema> changed_schema = make_additive_changes(schema);
2✔
1336
        config_local.schema = changed_schema;
2✔
1337
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1338
        ThreadSafeReference ref_async;
2✔
1339
        auto future = setup_reset_handlers_for_schema_validation(config_local, changed_schema);
2✔
1340
        {
2✔
1341
            auto realm = successfully_async_open_realm(config_local);
2✔
1342
            future.get();
2✔
1343
            CHECK(before_reset_count == 1);
2!
1344
            CHECK(after_reset_count == 1);
2!
1345

1346
            // make changes to the newly added property
1347
            realm->begin_transaction();
2✔
1348
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
1349
            ColKey new_col = table->get_column_key("added_oid_field");
2✔
1350
            REQUIRE(new_col);
2!
1351
            for (auto it = table->begin(); it != table->end(); ++it) {
4✔
1352
                it->set(new_col, ObjectId::gen());
2✔
1353
            }
2✔
1354
            realm->commit_transaction();
2✔
1355
            // subscribe to the new Class and add an object
1356
            auto new_table = realm->read_group().get_table("class_AddedClass");
2✔
1357
            auto sub_set = realm->get_latest_subscription_set();
2✔
1358
            auto mut_sub = sub_set.make_mutable_copy();
2✔
1359
            mut_sub.insert_or_assign(Query(new_table));
2✔
1360
            mut_sub.commit();
2✔
1361
            realm->begin_transaction();
2✔
1362
            REQUIRE(new_table);
2!
1363
            new_table->create_object_with_primary_key(ObjectId::gen());
2✔
1364
            realm->commit_transaction();
2✔
1365
            auto result = realm->get_latest_subscription_set()
2✔
1366
                              .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
1367
                              .get();
2✔
1368
            CHECK(result == sync::SubscriptionSet::State::Complete);
2!
1369
            realm->sync_session()->shutdown_and_wait();
2✔
1370
            realm->close();
2✔
1371
        }
2✔
1372
        REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(config_local.path));
2!
1373
        {
2✔
1374
            // ensure that an additional schema change after the successful reset is also accepted by the server
1375
            changed_schema[0].persisted_properties.push_back(
2✔
1376
                {"added_oid_field_second", PropertyType::ObjectId | PropertyType::Nullable});
2✔
1377
            changed_schema.push_back({"AddedClassSecond",
2✔
1378
                                      {
2✔
1379
                                          {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
1380
                                          {"str_field_2", PropertyType::String | PropertyType::Nullable},
2✔
1381
                                      }});
2✔
1382
            config_local.schema = changed_schema;
2✔
1383
            auto realm = Realm::get_shared_realm(config_local);
2✔
1384
            auto table = realm->read_group().get_table("class_AddedClassSecond");
2✔
1385
            ColKey new_col = table->get_column_key("str_field_2");
2✔
1386
            REQUIRE(new_col);
2!
1387
            auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
1388
            new_subs.insert_or_assign(Query(table).equal(new_col, "hello"));
2✔
1389
            auto subs = new_subs.commit();
2✔
1390
            realm->begin_transaction();
2✔
1391
            table->create_object_with_primary_key(Mixed{ObjectId::gen()}, {{new_col, "hello"}});
2✔
1392
            realm->commit_transaction();
2✔
1393
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1394
            wait_for_advance(*realm);
2✔
1395
            REQUIRE(table->size() == 1);
2!
1396
        }
2✔
1397
    }
2✔
1398

1399
    SECTION("DiscardLocal: additive schema changes not allowed") {
46✔
1400
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1401
        std::vector<ObjectSchema> changed_schema = make_additive_changes(schema);
2✔
1402
        config_local.schema = changed_schema;
2✔
1403
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1404
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1405
        config_local.sync_config->error_handler = err_handler;
2✔
1406
        auto status = async_open_realm(config_local);
2✔
1407
        REQUIRE_FALSE(status.is_ok());
2!
1408
        REQUIRE_THAT(status.get_status().reason(),
2✔
1409
                     Catch::Matchers::ContainsSubstring(
2✔
1410
                         "'Client reset cannot recover when classes have been removed: {AddedClass}'"));
2✔
1411
        error_future.get();
2✔
1412
        CHECK(before_reset_count == 1);
2!
1413
        CHECK(after_reset_count == 0);
2!
1414
    }
2✔
1415

1416
    SECTION("Recover: incompatible schema changes on async open are an error") {
46✔
1417
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1418
        std::vector<ObjectSchema> changed_schema = schema;
2✔
1419
        changed_schema[0].persisted_properties[0].type = PropertyType::UUID; // incompatible type change
2✔
1420
        config_local.schema = changed_schema;
2✔
1421
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1422
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1423
        config_local.sync_config->error_handler = err_handler;
2✔
1424
        auto status = async_open_realm(config_local);
2✔
1425
        REQUIRE_FALSE(status.is_ok());
2!
1426
        REQUIRE_THAT(
2✔
1427
            status.get_status().reason(),
2✔
1428
            Catch::Matchers::ContainsSubstring(
2✔
1429
                "'The following changes cannot be made in additive-only schema mode:\n"
2✔
1430
                "- Property 'TopLevel._id' has been changed from 'object id' to 'uuid'.\nIf your app is running in "
2✔
1431
                "development mode, you can delete the realm and restart the app to update your schema.'"));
2✔
1432
        error_future.get();
2✔
1433
        CHECK(before_reset_count == 0); // we didn't even get this far because opening the frozen realm fails
2!
1434
        CHECK(after_reset_count == 0);
2!
1435
    }
2✔
1436

1437
    SECTION("Recover: additive schema changes without dev mode produce an error after client reset") {
46✔
1438
        const AppSession& app_session = harness.session().app_session();
2✔
1439
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, true);
2✔
1440
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1441
        // Disable dev mode so that schema changes are not allowed
1442
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, false);
2✔
1443
        auto cleanup = util::make_scope_exit([&]() noexcept {
2✔
1444
            const AppSession& app_session = harness.session().app_session();
2✔
1445
            app_session.admin_api.set_development_mode_to(app_session.server_app_id, true);
2✔
1446
        });
2✔
1447

1448
        std::vector<ObjectSchema> changed_schema = make_additive_changes(schema);
2✔
1449
        config_local.schema = changed_schema;
2✔
1450
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1451
        (void)setup_reset_handlers_for_schema_validation(config_local, changed_schema);
2✔
1452
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1453
        config_local.sync_config->error_handler = err_handler;
2✔
1454
        auto realm = successfully_async_open_realm(config_local);
2✔
1455
        // make changes to the new property
1456
        realm->begin_transaction();
2✔
1457
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
1458
        ColKey new_col = table->get_column_key("added_oid_field");
2✔
1459
        REQUIRE(new_col);
2!
1460
        for (auto it = table->begin(); it != table->end(); ++it) {
4✔
1461
            it->set(new_col, ObjectId::gen());
2✔
1462
        }
2✔
1463
        realm->commit_transaction();
2✔
1464
        auto err = error_future.get();
2✔
1465
        std::string property_err = "Invalid schema change (UPLOAD): non-breaking schema change: adding "
2✔
1466
                                   "\"ObjectID\" column at field \"added_oid_field\" in schema \"TopLevel\", "
2✔
1467
                                   "schema changes from clients are restricted when developer mode is disabled";
2✔
1468
        std::string class_err = "Invalid schema change (UPLOAD): non-breaking schema change: adding schema "
2✔
1469
                                "for Realm table \"AddedClass\", schema changes from clients are restricted when "
2✔
1470
                                "developer mode is disabled";
2✔
1471
        REQUIRE_THAT(err.status.reason(), Catch::Matchers::ContainsSubstring(property_err) ||
2✔
1472
                                              Catch::Matchers::ContainsSubstring(class_err));
2✔
1473
        CHECK(before_reset_count == 1);
2!
1474
        CHECK(after_reset_count == 1);
2!
1475
    }
2✔
1476

1477
    SECTION("Recover: inserts in collections in mixed - collections cleared remotely") {
46✔
1478
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1479
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
1480
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
1481
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1482
        test_reset
2✔
1483
            ->populate_initial_object([&](SharedRealm realm) {
2✔
1484
                subscribe_to_all_and_bootstrap(*realm);
2✔
1485
                auto pk_of_added_object = ObjectId::gen();
2✔
1486
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
1487

1488
                realm->begin_transaction();
2✔
1489
                CppContext c(realm);
2✔
1490
                auto obj = Object::create(c, realm, "TopLevel",
2✔
1491
                                          std::any(AnyDict{{"_id"s, pk_of_added_object},
2✔
1492
                                                           {"queryable_str_field"s, "initial value"s},
2✔
1493
                                                           {"sum_of_list_field"s, int64_t(42)}}));
2✔
1494
                auto col_any = table->get_column_key("any_mixed");
2✔
1495
                obj.get_obj().set_collection(col_any, CollectionType::List);
2✔
1496
                auto list = obj.get_obj().get_list_ptr<Mixed>(col_any);
2✔
1497
                list->add(1);
2✔
1498
                auto dict = obj.get_obj().get_dictionary("dictionary_mixed");
2✔
1499
                dict.insert("key", 42);
2✔
1500
                realm->commit_transaction();
2✔
1501
                wait_for_upload(*realm);
2✔
1502
                return pk_of_added_object;
2✔
1503
            })
2✔
1504
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
1505
                local_realm->begin_transaction();
2✔
1506
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
1507
                auto col_any = table->get_column_key("any_mixed");
2✔
1508
                auto obj = table->get_object(0);
2✔
1509
                auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
1510
                list->add(2);
2✔
1511
                auto dict = obj.get_dictionary("dictionary_mixed");
2✔
1512
                dict.insert("key2", "value");
2✔
1513
                local_realm->commit_transaction();
2✔
1514
            })
2✔
1515
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
1516
                remote_realm->begin_transaction();
2✔
1517
                auto table = remote_realm->read_group().get_table("class_TopLevel");
2✔
1518
                auto col_any = table->get_column_key("any_mixed");
2✔
1519
                auto obj = table->get_object(0);
2✔
1520
                auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
1521
                list->clear();
2✔
1522
                auto dict = obj.get_dictionary("dictionary_mixed");
2✔
1523
                dict.clear();
2✔
1524
                remote_realm->commit_transaction();
2✔
1525
            })
2✔
1526
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
1527
                wait_for_advance(*local_realm);
2✔
1528
                ClientResyncMode mode = client_reset_future.get();
2✔
1529
                REQUIRE(mode == ClientResyncMode::Recover);
2!
1530
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
1531
                auto obj = table->get_object(0);
2✔
1532
                auto col_any = table->get_column_key("any_mixed");
2✔
1533
                auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
1534
                CHECK(list->size() == 1);
2!
1535
                CHECK(list->get_any(0).get_int() == 2);
2!
1536
                auto dict = obj.get_dictionary("dictionary_mixed");
2✔
1537
                CHECK(dict.size() == 1);
2!
1538
                CHECK(dict.get("key2").get_string() == "value");
2!
1539
            })
2✔
1540
            ->run();
2✔
1541
    }
2✔
1542
}
46✔
1543

1544
TEST_CASE("flx: creating an object on a class with no subscription throws", "[sync][flx][subscription][baas]") {
2✔
1545
    FLXSyncTestHarness harness("flx_bad_query", {g_simple_embedded_obj_schema, {"queryable_str_field"}});
2✔
1546
    harness.do_with_new_user([&](auto user) {
2✔
1547
        SyncTestFile config(user, harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
1548
        auto [error_promise, error_future] = util::make_promise_future<SyncError>();
2✔
1549
        auto shared_promise = std::make_shared<decltype(error_promise)>(std::move(error_promise));
2✔
1550
        config.sync_config->error_handler = [error_promise = std::move(shared_promise)](std::shared_ptr<SyncSession>,
2✔
1551
                                                                                        SyncError err) {
2✔
1552
            CHECK(err.server_requests_action == sync::ProtocolErrorInfo::Action::Transient);
×
1553
            error_promise->emplace_value(std::move(err));
×
UNCOV
1554
        };
×
1555

1556
        auto realm = Realm::get_shared_realm(config);
2✔
1557
        CppContext c(realm);
2✔
1558
        realm->begin_transaction();
2✔
1559
        REQUIRE_THROWS_AS(
2✔
1560
            Object::create(c, realm, "TopLevel",
2✔
1561
                           std::any(AnyDict{{"_id", ObjectId::gen()}, {"queryable_str_field", "foo"s}})),
2✔
1562
            NoSubscriptionForWrite);
2✔
1563
        realm->cancel_transaction();
2✔
1564

1565
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
1566

1567
        REQUIRE(table->is_empty());
2!
1568
        auto col_key = table->get_column_key("queryable_str_field");
2✔
1569
        {
2✔
1570
            auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
1571
            new_subs.insert_or_assign(Query(table).equal(col_key, "foo"));
2✔
1572
            auto subs = new_subs.commit();
2✔
1573
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1574
        }
2✔
1575

1576
        realm->begin_transaction();
2✔
1577
        auto obj = Object::create(c, realm, "TopLevel",
2✔
1578
                                  std::any(AnyDict{{"_id", ObjectId::gen()},
2✔
1579
                                                   {"queryable_str_field", "foo"s},
2✔
1580
                                                   {"embedded_obj", AnyDict{{"str_field", "bar"s}}}}));
2✔
1581
        realm->commit_transaction();
2✔
1582

1583
        realm->begin_transaction();
2✔
1584
        auto embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1585
        embedded_obj.set_property_value(c, "str_field", std::any{"baz"s});
2✔
1586
        realm->commit_transaction();
2✔
1587

1588
        wait_for_upload(*realm);
2✔
1589
        wait_for_download(*realm);
2✔
1590
    });
2✔
1591
}
2✔
1592

1593
TEST_CASE("flx: uploading an object that is out-of-view results in compensating write",
1594
          "[sync][flx][compensating write][baas]") {
16✔
1595
    static std::optional<FLXSyncTestHarness> harness;
16✔
1596
    if (!harness) {
16✔
1597
        Schema schema{{"TopLevel",
2✔
1598
                       {{"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
1599
                        {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1600
                        {"embedded_obj", PropertyType::Object | PropertyType::Nullable, "TopLevel_embedded_obj"}}},
2✔
1601
                      {"TopLevel_embedded_obj",
2✔
1602
                       ObjectSchema::ObjectType::Embedded,
2✔
1603
                       {{"str_field", PropertyType::String | PropertyType::Nullable}}},
2✔
1604
                      {"Int PK",
2✔
1605
                       {
2✔
1606
                           {"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
1607
                           {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1608
                       }},
2✔
1609
                      {"String PK",
2✔
1610
                       {
2✔
1611
                           {"_id", PropertyType::String, Property::IsPrimary{true}},
2✔
1612
                           {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1613
                       }},
2✔
1614
                      {"UUID PK",
2✔
1615
                       {
2✔
1616
                           {"_id", PropertyType::UUID, Property::IsPrimary{true}},
2✔
1617
                           {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1618
                       }}};
2✔
1619

1620
        AppCreateConfig::ServiceRole role;
2✔
1621
        role.name = "compensating_write_perms";
2✔
1622

1623
        AppCreateConfig::ServiceRoleDocumentFilters doc_filters;
2✔
1624
        doc_filters.read = true;
2✔
1625
        doc_filters.write = {{"queryable_str_field", {{"$in", nlohmann::json::array({"foo", "bar"})}}}};
2✔
1626
        role.document_filters = doc_filters;
2✔
1627

1628
        role.insert_filter = true;
2✔
1629
        role.delete_filter = true;
2✔
1630
        role.read = true;
2✔
1631
        role.write = true;
2✔
1632
        FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field"}, {role}};
2✔
1633
        harness.emplace("flx_bad_query", server_schema);
2✔
1634
    }
2✔
1635

1636
    create_user_and_log_in(harness->app());
16✔
1637
    auto user = harness->app()->current_user();
16✔
1638

1639
    auto make_error_handler = [] {
16✔
1640
        auto [error_promise, error_future] = util::make_promise_future<SyncError>();
16✔
1641
        auto shared_promise = std::make_shared<decltype(error_promise)>(std::move(error_promise));
16✔
1642
        auto fn = [error_promise = std::move(shared_promise)](std::shared_ptr<SyncSession>, SyncError err) mutable {
16✔
1643
            if (!error_promise) {
14✔
1644
                util::format(std::cerr,
×
1645
                             "An unexpected sync error was caught by the default SyncTestFile handler: '%1'\n",
×
1646
                             err.status);
×
1647
                abort();
×
UNCOV
1648
            }
×
1649
            error_promise->emplace_value(std::move(err));
14✔
1650
            error_promise.reset();
14✔
1651
        };
14✔
1652

1653
        return std::make_pair(std::move(error_future), std::move(fn));
16✔
1654
    };
16✔
1655

1656
    auto validate_sync_error = [&](const SyncError& sync_error, Mixed expected_pk, const char* expected_object_name,
16✔
1657
                                   const std::string& error_msg_fragment) {
16✔
1658
        CHECK(sync_error.status == ErrorCodes::SyncCompensatingWrite);
14!
1659
        CHECK(!sync_error.is_client_reset_requested());
14!
1660
        CHECK(sync_error.compensating_writes_info.size() == 1);
14!
1661
        CHECK(sync_error.server_requests_action == sync::ProtocolErrorInfo::Action::Warning);
14!
1662
        auto write_info = sync_error.compensating_writes_info[0];
14✔
1663
        CHECK(write_info.primary_key == expected_pk);
14!
1664
        CHECK(write_info.object_name == expected_object_name);
14!
1665
        CHECK_THAT(write_info.reason, Catch::Matchers::ContainsSubstring(error_msg_fragment));
14✔
1666
    };
14✔
1667

1668
    SyncTestFile config(user, harness->schema(), SyncConfig::FLXSyncEnabled{});
16✔
1669
    auto&& [error_future, err_handler] = make_error_handler();
16✔
1670
    config.sync_config->error_handler = err_handler;
16✔
1671
    auto realm = Realm::get_shared_realm(config);
16✔
1672
    auto table = realm->read_group().get_table("class_TopLevel");
16✔
1673

1674
    auto create_subscription = [&](StringData table_name, auto make_query) {
16✔
1675
        auto table = realm->read_group().get_table(table_name);
14✔
1676
        auto queryable_str_field = table->get_column_key("queryable_str_field");
14✔
1677
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
14✔
1678
        new_query.insert_or_assign(make_query(Query(table), queryable_str_field));
14✔
1679
        new_query.commit();
14✔
1680
    };
14✔
1681

1682
    SECTION("compensating write because of permission violation") {
16✔
1683
        create_subscription("class_TopLevel", [](auto q, auto col) {
2✔
1684
            return q.equal(col, "bizz");
2✔
1685
        });
2✔
1686

1687
        CppContext c(realm);
2✔
1688
        realm->begin_transaction();
2✔
1689
        auto invalid_obj = ObjectId::gen();
2✔
1690
        Object::create(c, realm, "TopLevel",
2✔
1691
                       std::any(AnyDict{{"_id", invalid_obj}, {"queryable_str_field", "bizz"s}}));
2✔
1692
        realm->commit_transaction();
2✔
1693

1694
        validate_sync_error(
2✔
1695
            std::move(error_future).get(), invalid_obj, "TopLevel",
2✔
1696
            util::format("write to ObjectID(\"%1\") in table \"TopLevel\" not allowed", invalid_obj.to_string()));
2✔
1697

1698
        wait_for_advance(*realm);
2✔
1699

1700
        auto top_level_table = realm->read_group().get_table("class_TopLevel");
2✔
1701
        REQUIRE(top_level_table->is_empty());
2!
1702
    }
2✔
1703

1704
    SECTION("compensating write because of permission violation with write on embedded object") {
16✔
1705
        create_subscription("class_TopLevel", [](auto q, auto col) {
2✔
1706
            return q.equal(col, "bizz").Or().equal(col, "foo");
2✔
1707
        });
2✔
1708

1709
        CppContext c(realm);
2✔
1710
        realm->begin_transaction();
2✔
1711
        auto invalid_obj = ObjectId::gen();
2✔
1712
        auto obj = Object::create(c, realm, "TopLevel",
2✔
1713
                                  std::any(AnyDict{{"_id", invalid_obj},
2✔
1714
                                                   {"queryable_str_field", "foo"s},
2✔
1715
                                                   {"embedded_obj", AnyDict{{"str_field", "bar"s}}}}));
2✔
1716
        realm->commit_transaction();
2✔
1717
        realm->begin_transaction();
2✔
1718
        obj.set_property_value(c, "queryable_str_field", std::any{"bizz"s});
2✔
1719
        realm->commit_transaction();
2✔
1720
        realm->begin_transaction();
2✔
1721
        auto embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1722
        embedded_obj.set_property_value(c, "str_field", std::any{"baz"s});
2✔
1723
        realm->commit_transaction();
2✔
1724

1725
        validate_sync_error(
2✔
1726
            std::move(error_future).get(), invalid_obj, "TopLevel",
2✔
1727
            util::format("write to ObjectID(\"%1\") in table \"TopLevel\" not allowed", invalid_obj.to_string()));
2✔
1728

1729
        wait_for_advance(*realm);
2✔
1730

1731
        obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(invalid_obj));
2✔
1732
        embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1733
        REQUIRE(util::any_cast<std::string&&>(obj.get_property_value<std::any>(c, "queryable_str_field")) == "foo");
2!
1734
        REQUIRE(util::any_cast<std::string&&>(embedded_obj.get_property_value<std::any>(c, "str_field")) == "bar");
2!
1735

1736
        realm->begin_transaction();
2✔
1737
        embedded_obj.set_property_value(c, "str_field", std::any{"baz"s});
2✔
1738
        realm->commit_transaction();
2✔
1739

1740
        wait_for_upload(*realm);
2✔
1741
        wait_for_download(*realm);
2✔
1742

1743
        wait_for_advance(*realm);
2✔
1744
        obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(invalid_obj));
2✔
1745
        embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1746
        REQUIRE(embedded_obj.get_column_value<StringData>("str_field") == "baz");
2!
1747
    }
2✔
1748

1749
    SECTION("compensating write for writing a top-level object that is out-of-view") {
16✔
1750
        create_subscription("class_TopLevel", [](auto q, auto col) {
2✔
1751
            return q.equal(col, "foo");
2✔
1752
        });
2✔
1753

1754
        CppContext c(realm);
2✔
1755
        realm->begin_transaction();
2✔
1756
        auto valid_obj = ObjectId::gen();
2✔
1757
        auto invalid_obj = ObjectId::gen();
2✔
1758
        Object::create(c, realm, "TopLevel",
2✔
1759
                       std::any(AnyDict{
2✔
1760
                           {"_id", valid_obj},
2✔
1761
                           {"queryable_str_field", "foo"s},
2✔
1762
                       }));
2✔
1763
        Object::create(c, realm, "TopLevel",
2✔
1764
                       std::any(AnyDict{
2✔
1765
                           {"_id", invalid_obj},
2✔
1766
                           {"queryable_str_field", "bar"s},
2✔
1767
                       }));
2✔
1768
        realm->commit_transaction();
2✔
1769

1770
        validate_sync_error(std::move(error_future).get(), invalid_obj, "TopLevel",
2✔
1771
                            "object is outside of the current query view");
2✔
1772

1773
        wait_for_advance(*realm);
2✔
1774

1775
        auto top_level_table = realm->read_group().get_table("class_TopLevel");
2✔
1776
        REQUIRE(top_level_table->size() == 1);
2!
1777
        REQUIRE(top_level_table->get_object_with_primary_key(valid_obj));
2!
1778

1779
        // Verify that a valid object afterwards does not produce an error
1780
        realm->begin_transaction();
2✔
1781
        Object::create(c, realm, "TopLevel",
2✔
1782
                       std::any(AnyDict{
2✔
1783
                           {"_id", ObjectId::gen()},
2✔
1784
                           {"queryable_str_field", "foo"s},
2✔
1785
                       }));
2✔
1786
        realm->commit_transaction();
2✔
1787

1788
        wait_for_upload(*realm);
2✔
1789
        wait_for_download(*realm);
2✔
1790
    }
2✔
1791

1792
    SECTION("compensating writes for each primary key type") {
16✔
1793
        SECTION("int") {
8✔
1794
            create_subscription("class_Int PK", [](auto q, auto col) {
2✔
1795
                return q.equal(col, "foo");
2✔
1796
            });
2✔
1797
            realm->begin_transaction();
2✔
1798
            realm->read_group().get_table("class_Int PK")->create_object_with_primary_key(123456);
2✔
1799
            realm->commit_transaction();
2✔
1800

1801
            validate_sync_error(std::move(error_future).get(), 123456, "Int PK",
2✔
1802
                                "write to 123456 in table \"Int PK\" not allowed");
2✔
1803
        }
2✔
1804

1805
        SECTION("short string") {
8✔
1806
            create_subscription("class_String PK", [](auto q, auto col) {
2✔
1807
                return q.equal(col, "foo");
2✔
1808
            });
2✔
1809
            realm->begin_transaction();
2✔
1810
            realm->read_group().get_table("class_String PK")->create_object_with_primary_key("short");
2✔
1811
            realm->commit_transaction();
2✔
1812

1813
            validate_sync_error(std::move(error_future).get(), "short", "String PK",
2✔
1814
                                "write to \"short\" in table \"String PK\" not allowed");
2✔
1815
        }
2✔
1816

1817
        SECTION("long string") {
8✔
1818
            create_subscription("class_String PK", [](auto q, auto col) {
2✔
1819
                return q.equal(col, "foo");
2✔
1820
            });
2✔
1821
            realm->begin_transaction();
2✔
1822
            const char* pk = "long string which won't fit in the SSO buffer";
2✔
1823
            realm->read_group().get_table("class_String PK")->create_object_with_primary_key(pk);
2✔
1824
            realm->commit_transaction();
2✔
1825

1826
            validate_sync_error(std::move(error_future).get(), pk, "String PK",
2✔
1827
                                util::format("write to \"%1\" in table \"String PK\" not allowed", pk));
2✔
1828
        }
2✔
1829

1830
        SECTION("uuid") {
8✔
1831
            create_subscription("class_UUID PK", [](auto q, auto col) {
2✔
1832
                return q.equal(col, "foo");
2✔
1833
            });
2✔
1834
            realm->begin_transaction();
2✔
1835
            UUID pk("01234567-9abc-4def-9012-3456789abcde");
2✔
1836
            realm->read_group().get_table("class_UUID PK")->create_object_with_primary_key(pk);
2✔
1837
            realm->commit_transaction();
2✔
1838

1839
            validate_sync_error(std::move(error_future).get(), pk, "UUID PK",
2✔
1840
                                util::format("write to UUID(%1) in table \"UUID PK\" not allowed", pk));
2✔
1841
        }
2✔
1842
    }
8✔
1843

1844
    // Clear the Realm afterwards as we're reusing an app
1845
    realm->begin_transaction();
16✔
1846
    table->clear();
16✔
1847
    realm->commit_transaction();
16✔
1848
    wait_for_upload(*realm);
16✔
1849
    realm.reset();
16✔
1850

1851
    // Add new sections before this
1852
    SECTION("teardown") {
16✔
1853
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
1854
        harness.reset();
2✔
1855
    }
2✔
1856
}
16✔
1857

1858
TEST_CASE("flx: query on non-queryable field results in query error message", "[sync][flx][query][baas]") {
8✔
1859
    static std::optional<FLXSyncTestHarness> harness;
8✔
1860
    if (!harness) {
8✔
1861
        harness.emplace("flx_bad_query");
2✔
1862
    }
2✔
1863

1864
    auto create_subscription = [](SharedRealm realm, StringData table_name, StringData column_name, auto make_query) {
10✔
1865
        auto table = realm->read_group().get_table(table_name);
10✔
1866
        auto queryable_field = table->get_column_key(column_name);
10✔
1867
        auto new_query = realm->get_active_subscription_set().make_mutable_copy();
10✔
1868
        new_query.insert_or_assign(make_query(Query(table), queryable_field));
10✔
1869
        return new_query.commit();
10✔
1870
    };
10✔
1871

1872
    auto check_status = [](auto status) {
8✔
1873
        CHECK(!status.is_ok());
8!
1874
        std::string reason = status.get_status().reason();
8✔
1875
        // Depending on the version of baas used, it may return 'Invalid query:' or
1876
        // 'Client provided query with bad syntax:'
1877
        if ((reason.find("Invalid query:") == std::string::npos &&
8✔
1878
             reason.find("Client provided query with bad syntax:") == std::string::npos) ||
8!
1879
            reason.find("\"TopLevel\": key \"non_queryable_field\" is not a queryable field") == std::string::npos) {
8✔
1880
            FAIL(util::format("Error reason did not match expected: `%1`", reason));
×
UNCOV
1881
        }
×
1882
    };
8✔
1883

1884
    SECTION("Good query after bad query") {
8✔
1885
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1886
            auto subs = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1887
                return q.equal(c, "bar");
2✔
1888
            });
2✔
1889
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1890
            check_status(sub_res);
2✔
1891

1892
            CHECK(realm->get_active_subscription_set().version() == 0);
2!
1893
            CHECK(realm->get_latest_subscription_set().version() == 1);
2!
1894

1895
            subs = create_subscription(realm, "class_TopLevel", "queryable_str_field", [](auto q, auto c) {
2✔
1896
                return q.equal(c, "foo");
2✔
1897
            });
2✔
1898
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1899

1900
            CHECK(realm->get_active_subscription_set().version() == 2);
2!
1901
            CHECK(realm->get_latest_subscription_set().version() == 2);
2!
1902
        });
2✔
1903
    }
2✔
1904

1905
    SECTION("Bad query after bad query") {
8✔
1906
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1907
            auto sync_session = realm->sync_session();
2✔
1908
            sync_session->pause();
2✔
1909

1910
            auto subs = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1911
                return q.equal(c, "bar");
2✔
1912
            });
2✔
1913
            auto subs2 = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1914
                return q.equal(c, "bar");
2✔
1915
            });
2✔
1916

1917
            sync_session->resume();
2✔
1918

1919
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1920
            auto sub_res2 =
2✔
1921
                subs2.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1922

1923
            check_status(sub_res);
2✔
1924
            check_status(sub_res2);
2✔
1925

1926
            CHECK(realm->get_active_subscription_set().version() == 0);
2!
1927
            CHECK(realm->get_latest_subscription_set().version() == 2);
2!
1928
        });
2✔
1929
    }
2✔
1930

1931
    // Test for issue #6839, where wait for download after committing a new subscription and then
1932
    // wait for the subscription complete notification was leading to a garbage reason value in the
1933
    // status provided to the subscription complete callback.
1934
    SECTION("Download during bad query") {
8✔
1935
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1936
            // Wait for steady state before committing the new subscription
1937
            REQUIRE(!wait_for_download(*realm));
2!
1938

1939
            auto subs = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1940
                return q.equal(c, "bar");
2✔
1941
            });
2✔
1942
            // Wait for download is actually waiting for the subscription to be applied after it was committed
1943
            REQUIRE(!wait_for_download(*realm));
2!
1944
            // After subscription is complete or fails during wait for download, this function completes
1945
            // without blocking
1946
            auto result = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1947
            // Verify error occurred
1948
            check_status(result);
2✔
1949
        });
2✔
1950
    }
2✔
1951

1952
    // Add new sections before this
1953
    SECTION("teardown") {
8✔
1954
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
1955
        harness.reset();
2✔
1956
    }
2✔
1957
}
8✔
1958

1959
#if REALM_ENABLE_GEOSPATIAL
1960
TEST_CASE("flx: geospatial", "[sync][flx][geospatial][baas]") {
6✔
1961
    static std::optional<FLXSyncTestHarness> harness;
6✔
1962
    if (!harness) {
6✔
1963
        Schema schema{
2✔
1964
            {"restaurant",
2✔
1965
             {
2✔
1966
                 {"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
1967
                 {"queryable_str_field", PropertyType::String},
2✔
1968
                 {"location", PropertyType::Object | PropertyType::Nullable, "geoPointType"},
2✔
1969
                 {"array", PropertyType::Object | PropertyType::Array, "geoPointType"},
2✔
1970
             }},
2✔
1971
            {"geoPointType",
2✔
1972
             ObjectSchema::ObjectType::Embedded,
2✔
1973
             {
2✔
1974
                 {"type", PropertyType::String},
2✔
1975
                 {"coordinates", PropertyType::Double | PropertyType::Array},
2✔
1976
             }},
2✔
1977
        };
2✔
1978
        FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field", "location"}};
2✔
1979
        harness.emplace("flx_geospatial", server_schema);
2✔
1980
    }
2✔
1981

1982
    auto create_subscription = [](SharedRealm realm, StringData table_name, StringData column_name, auto make_query) {
18✔
1983
        auto table = realm->read_group().get_table(table_name);
18✔
1984
        auto queryable_field = table->get_column_key(column_name);
18✔
1985
        auto new_query = realm->get_active_subscription_set().make_mutable_copy();
18✔
1986
        new_query.insert_or_assign(make_query(Query(table), queryable_field));
18✔
1987
        return new_query.commit();
18✔
1988
    };
18✔
1989

1990
    SECTION("Server supports a basic geowithin FLX query") {
6✔
1991
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1992
            const realm::AppSession& app_session = harness->session().app_session();
2✔
1993
            auto sync_service = app_session.admin_api.get_sync_service(app_session.server_app_id);
2✔
1994

1995
            AdminAPISession::ServiceConfig config =
2✔
1996
                app_session.admin_api.get_config(app_session.server_app_id, sync_service);
2✔
1997
            auto subs = create_subscription(realm, "class_restaurant", "location", [](Query q, ColKey c) {
2✔
1998
                GeoBox area{GeoPoint{0.2, 0.2}, GeoPoint{0.7, 0.7}};
2✔
1999
                Query query = q.get_table()->column<Link>(c).geo_within(area);
2✔
2000
                std::string ser = query.get_description();
2✔
2001
                return query;
2✔
2002
            });
2✔
2003
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
2004
            CHECK(sub_res.is_ok());
2!
2005
            CHECK(realm->get_active_subscription_set().version() == 1);
2!
2006
            CHECK(realm->get_latest_subscription_set().version() == 1);
2!
2007
        });
2✔
2008
    }
2✔
2009

2010
    SECTION("geospatial query consistency: local/server/FLX") {
6✔
2011
        harness->do_with_new_user([&](std::shared_ptr<SyncUser> user) {
2✔
2012
            SyncTestFile config(user, harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
2013
            auto error_pf = util::make_promise_future<SyncError>();
2✔
2014
            config.sync_config->error_handler =
2✔
2015
                [promise = std::make_shared<util::Promise<SyncError>>(std::move(error_pf.promise))](
2✔
2016
                    std::shared_ptr<SyncSession>, SyncError error) {
2✔
2017
                    promise->emplace_value(std::move(error));
2✔
2018
                };
2✔
2019

2020
            auto realm = Realm::get_shared_realm(config);
2✔
2021

2022
            auto subs = create_subscription(realm, "class_restaurant", "queryable_str_field", [](Query q, ColKey c) {
2✔
2023
                return q.equal(c, "synced");
2✔
2024
            });
2✔
2025
            auto make_polygon_filter = [&](const GeoPolygon& polygon) -> bson::BsonDocument {
20✔
2026
                bson::BsonArray inner{};
20✔
2027
                REALM_ASSERT_3(polygon.points.size(), ==, 1);
20✔
2028
                for (auto& point : polygon.points[0]) {
94✔
2029
                    inner.push_back(bson::BsonArray{point.longitude, point.latitude});
94✔
2030
                }
94✔
2031
                bson::BsonArray coords;
20✔
2032
                coords.push_back(inner);
20✔
2033
                bson::BsonDocument geo_bson{{{"type", "Polygon"}, {"coordinates", coords}}};
20✔
2034
                bson::BsonDocument filter{
20✔
2035
                    {"location", bson::BsonDocument{{"$geoWithin", bson::BsonDocument{{"$geometry", geo_bson}}}}}};
20✔
2036
                return filter;
20✔
2037
            };
20✔
2038
            auto make_circle_filter = [&](const GeoCircle& circle) -> bson::BsonDocument {
6✔
2039
                bson::BsonArray coords{circle.center.longitude, circle.center.latitude};
6✔
2040
                bson::BsonArray inner;
6✔
2041
                inner.push_back(coords);
6✔
2042
                inner.push_back(circle.radius_radians);
6✔
2043
                bson::BsonDocument filter{
6✔
2044
                    {"location", bson::BsonDocument{{"$geoWithin", bson::BsonDocument{{"$centerSphere", inner}}}}}};
6✔
2045
                return filter;
6✔
2046
            };
6✔
2047
            auto run_query_on_server = [&](const bson::BsonDocument& filter,
2✔
2048
                                           std::optional<std::string> expected_error = {}) -> size_t {
26✔
2049
                auto remote_client = harness->app()->current_user()->mongo_client("BackingDB");
26✔
2050
                auto db = remote_client.db(harness->session().app_session().config.mongo_dbname);
26✔
2051
                auto restaurant_collection = db["restaurant"];
26✔
2052
                bool processed = false;
26✔
2053
                constexpr int64_t limit = 1000;
26✔
2054
                size_t matches = 0;
26✔
2055
                restaurant_collection.count(filter, limit, [&](uint64_t count, util::Optional<AppError> error) {
26✔
2056
                    processed = true;
26✔
2057
                    if (error) {
26✔
2058
                        if (!expected_error) {
12✔
2059
                            util::format(std::cout, "query error: %1\n", error->reason());
×
2060
                            FAIL(error);
×
UNCOV
2061
                        }
×
2062
                        else {
12✔
2063
                            std::string reason = std::string(error->reason());
12✔
2064
                            std::transform(reason.begin(), reason.end(), reason.begin(), toLowerAscii);
12✔
2065
                            std::transform(expected_error->begin(), expected_error->end(), expected_error->begin(),
12✔
2066
                                           toLowerAscii);
12✔
2067
                            auto pos = reason.find(*expected_error);
12✔
2068
                            if (pos == std::string::npos) {
12✔
2069
                                util::format(std::cout, "mismatch error: '%1' and '%2'\n", reason, *expected_error);
×
2070
                                FAIL(reason);
×
UNCOV
2071
                            }
×
2072
                        }
12✔
2073
                    }
12✔
2074
                    matches = size_t(count);
26✔
2075
                });
26✔
2076
                REQUIRE(processed);
26!
2077
                return matches;
26✔
2078
            };
26✔
2079
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
2080
            CHECK(sub_res.is_ok());
2!
2081
            CHECK(realm->get_active_subscription_set().version() == 1);
2!
2082
            CHECK(realm->get_latest_subscription_set().version() == 1);
2!
2083

2084
            CppContext c(realm);
2✔
2085
            int64_t pk = 0;
2✔
2086
            auto add_point = [&](GeoPoint p) {
16✔
2087
                Object::create(
16✔
2088
                    c, realm, "restaurant",
16✔
2089
                    std::any(AnyDict{
16✔
2090
                        {"_id", ++pk},
16✔
2091
                        {"queryable_str_field", "synced"s},
16✔
2092
                        {"location", AnyDict{{"type", "Point"s},
16✔
2093
                                             {"coordinates", std::vector<std::any>{p.longitude, p.latitude}}}}}));
16✔
2094
            };
16✔
2095
            std::vector<GeoPoint> points = {
2✔
2096
                GeoPoint{-74.006, 40.712800000000001},            // New York city
2✔
2097
                GeoPoint{12.568300000000001, 55.676099999999998}, // Copenhagen
2✔
2098
                GeoPoint{12.082599999999999, 55.628},             // ragnarok, Roskilde
2✔
2099
                GeoPoint{-180.1, -90.1},                          // invalid
2✔
2100
                GeoPoint{0, 90},                                  // north pole
2✔
2101
                GeoPoint{-82.68193, 84.74653},                    // northern point that falls within a box later
2✔
2102
                GeoPoint{82.55243, 84.54981}, // another northern point, but on the other side of the pole
2✔
2103
                GeoPoint{2129, 89},           // invalid
2✔
2104
            };
2✔
2105
            constexpr size_t invalids_to_be_compensated = 2; // 4, 8
2✔
2106
            realm->begin_transaction();
2✔
2107
            for (auto& point : points) {
16✔
2108
                add_point(point);
16✔
2109
            }
16✔
2110
            realm->commit_transaction();
2✔
2111
            const auto& error = error_pf.future.get();
2✔
2112
            REQUIRE(!error.is_fatal);
2!
2113
            REQUIRE(error.status == ErrorCodes::SyncCompensatingWrite);
2!
2114
            REQUIRE(error.compensating_writes_info.size() == invalids_to_be_compensated);
2!
2115
            REQUIRE_THAT(error.compensating_writes_info[0].reason,
2✔
2116
                         Catch::Matchers::ContainsSubstring("in table \"restaurant\" will corrupt geojson data"));
2✔
2117
            REQUIRE_THAT(error.compensating_writes_info[1].reason,
2✔
2118
                         Catch::Matchers::ContainsSubstring("in table \"restaurant\" will corrupt geojson data"));
2✔
2119

2120
            {
2✔
2121
                auto table = realm->read_group().get_table("class_restaurant");
2✔
2122
                CHECK(table->size() == points.size());
2!
2123
                Obj obj = table->get_object_with_primary_key(Mixed{1});
2✔
2124
                REQUIRE(obj);
2!
2125
                Geospatial geo = obj.get<Geospatial>("location");
2✔
2126
                REQUIRE(geo.get_type_string() == "Point");
2!
2127
                REQUIRE(geo.get_type() == Geospatial::Type::Point);
2!
2128
                GeoPoint point = geo.get<GeoPoint>();
2✔
2129
                REQUIRE(point.longitude == points[0].longitude);
2!
2130
                REQUIRE(point.latitude == points[0].latitude);
2!
2131
                REQUIRE(!point.get_altitude());
2!
2132
                ColKey location_col = table->get_column_key("location");
2✔
2133
                auto run_query_locally = [&table, &location_col](Geospatial bounds) -> size_t {
26✔
2134
                    Query query = table->column<Link>(location_col).geo_within(Geospatial(bounds));
26✔
2135
                    return query.find_all().size();
26✔
2136
                };
26✔
2137
                auto run_query_as_flx = [&](Geospatial bounds) -> size_t {
14✔
2138
                    size_t num_objects = 0;
14✔
2139
                    harness->do_with_new_realm([&](SharedRealm realm) {
14✔
2140
                        auto subs =
14✔
2141
                            create_subscription(realm, "class_restaurant", "location", [&](Query q, ColKey c) {
14✔
2142
                                return q.get_table()->column<Link>(c).geo_within(Geospatial(bounds));
14✔
2143
                            });
14✔
2144
                        auto sub_res =
14✔
2145
                            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
14✔
2146
                        CHECK(sub_res.is_ok());
14!
2147
                        CHECK(realm->get_active_subscription_set().version() == 1);
14!
2148
                        realm->refresh();
14✔
2149
                        num_objects = realm->get_class("restaurant").num_objects();
14✔
2150
                    });
14✔
2151
                    return num_objects;
14✔
2152
                };
14✔
2153

2154
                reset_utils::wait_for_num_objects_in_atlas(harness->app()->current_user(),
2✔
2155
                                                           harness->session().app_session(), "restaurant",
2✔
2156
                                                           points.size() - invalids_to_be_compensated);
2✔
2157

2158
                {
2✔
2159
                    GeoPolygon bounds{
2✔
2160
                        {{GeoPoint{-80, 40.7128}, GeoPoint{20, 60}, GeoPoint{20, 20}, GeoPoint{-80, 40.7128}}}};
2✔
2161
                    size_t local_matches = run_query_locally(bounds);
2✔
2162
                    size_t server_results = run_query_on_server(make_polygon_filter(bounds));
2✔
2163
                    size_t flx_results = run_query_as_flx(bounds);
2✔
2164
                    CHECK(flx_results == local_matches);
2!
2165
                    CHECK(server_results == local_matches);
2!
2166
                }
2✔
2167
                {
2✔
2168
                    GeoCircle circle{.5, GeoPoint{0, 90}};
2✔
2169
                    size_t local_matches = run_query_locally(circle);
2✔
2170
                    size_t server_results = run_query_on_server(make_circle_filter(circle));
2✔
2171
                    size_t flx_results = run_query_as_flx(circle);
2✔
2172
                    CHECK(server_results == local_matches);
2!
2173
                    CHECK(flx_results == local_matches);
2!
2174
                }
2✔
2175
                { // a ring with 3 points without a matching begin/end is an error
2✔
2176
                    GeoPolygon open_bounds{{{GeoPoint{-80, 40.7128}, GeoPoint{20, 60}, GeoPoint{20, 20}}}};
2✔
2177
                    CHECK_THROWS_WITH(run_query_locally(open_bounds),
2✔
2178
                                      "Invalid region in GEOWITHIN query for parameter 'GeoPolygon({[-80, 40.7128], "
2✔
2179
                                      "[20, 60], [20, 20]})': 'Ring is not closed, first vertex 'GeoPoint([-80, "
2✔
2180
                                      "40.7128])' does not equal last vertex 'GeoPoint([20, 20])''");
2✔
2181
                    run_query_on_server(make_polygon_filter(open_bounds), "(BadValue) Loop is not closed");
2✔
2182
                }
2✔
2183
                {
2✔
2184
                    GeoCircle circle = GeoCircle::from_kms(10, GeoPoint{-180.1, -90.1});
2✔
2185
                    CHECK_THROWS_WITH(run_query_locally(circle),
2✔
2186
                                      "Invalid region in GEOWITHIN query for parameter 'GeoCircle([-180.1, -90.1], "
2✔
2187
                                      "0.00156787)': 'Longitude/latitude is out of bounds, lng: -180.1 lat: -90.1'");
2✔
2188
                    run_query_on_server(make_circle_filter(circle), "(BadValue) longitude/latitude is out of bounds");
2✔
2189
                }
2✔
2190
                {
2✔
2191
                    GeoCircle circle = GeoCircle::from_kms(-1, GeoPoint{0, 0});
2✔
2192
                    CHECK_THROWS_WITH(run_query_locally(circle),
2✔
2193
                                      "Invalid region in GEOWITHIN query for parameter 'GeoCircle([0, 0], "
2✔
2194
                                      "-0.000156787)': 'The radius of a circle must be a non-negative number'");
2✔
2195
                    run_query_on_server(make_circle_filter(circle),
2✔
2196
                                        "(BadValue) radius must be a non-negative number");
2✔
2197
                }
2✔
2198
                {
2✔
2199
                    // This box is from Gershøj to CPH airport. It includes CPH and Ragnarok but not NYC.
2200
                    std::vector<Geospatial> valid_box_variations = {
2✔
2201
                        GeoBox{GeoPoint{11.97575, 55.71601},
2✔
2202
                               GeoPoint{12.64773, 55.61211}}, // Gershøj, CPH Airport (Top Left, Bottom Right)
2✔
2203
                        GeoBox{GeoPoint{12.64773, 55.61211},
2✔
2204
                               GeoPoint{11.97575, 55.71601}}, // CPH Airport, Gershøj (Bottom Right, Top Left)
2✔
2205
                        GeoBox{GeoPoint{12.64773, 55.71601},
2✔
2206
                               GeoPoint{11.97575, 55.61211}}, // Upper Right, Bottom Left
2✔
2207
                        GeoBox{GeoPoint{11.97575, 55.61211},
2✔
2208
                               GeoPoint{12.64773, 55.71601}}, // Bottom Left, Upper Right
2✔
2209
                    };
2✔
2210
                    constexpr size_t expected_results = 2;
2✔
2211
                    for (auto& geo : valid_box_variations) {
8✔
2212
                        size_t local_matches = run_query_locally(geo);
8✔
2213
                        size_t server_matches =
8✔
2214
                            run_query_on_server(make_polygon_filter(geo.get<GeoBox>().to_polygon()));
8✔
2215
                        size_t flx_matches = run_query_as_flx(geo);
8✔
2216
                        CHECK(local_matches == expected_results);
8!
2217
                        CHECK(server_matches == expected_results);
8!
2218
                        CHECK(flx_matches == expected_results);
8!
2219
                    }
8✔
2220
                    std::vector<Geospatial> invalid_boxes = {
2✔
2221
                        GeoBox{GeoPoint{11.97575, 55.71601}, GeoPoint{11.97575, 55.71601}}, // same point twice
2✔
2222
                        GeoBox{GeoPoint{11.97575, 55.71601},
2✔
2223
                               GeoPoint{11.97575, 57.0}}, // two points on the same longitude
2✔
2224
                        GeoBox{GeoPoint{11.97575, 55.71601},
2✔
2225
                               GeoPoint{12, 55.71601}}, // two points on the same latitude
2✔
2226
                    };
2✔
2227
                    for (auto& geo : invalid_boxes) {
6✔
2228
                        REQUIRE_THROWS_CONTAINING(run_query_locally(geo),
6✔
2229
                                                  "Invalid region in GEOWITHIN query for parameter 'GeoPolygon");
6✔
2230
                        run_query_on_server(make_polygon_filter(geo.get<GeoBox>().to_polygon()),
6✔
2231
                                            "(BadValue) Loop must have at least 3 different vertices");
6✔
2232
                    }
6✔
2233
                }
2✔
2234
                { // a box region that wraps the north pole. It contains the north pole point
2✔
2235
                    // and two others, one each on distinct sides of the globe.
2236
                    constexpr double lat = 82.83799;
2✔
2237
                    Geospatial north_pole_box =
2✔
2238
                        GeoPolygon{{{GeoPoint{-78.33951, lat}, GeoPoint{-90.33951, lat}, GeoPoint{90.33951, lat},
2✔
2239
                                     GeoPoint{78.33951, lat}, GeoPoint{-78.33951, lat}}}};
2✔
2240
                    constexpr size_t num_matching_points = 3;
2✔
2241
                    size_t local_matches = run_query_locally(north_pole_box);
2✔
2242
                    size_t server_matches =
2✔
2243
                        run_query_on_server(make_polygon_filter(north_pole_box.get<GeoPolygon>()));
2✔
2244
                    size_t flx_matches = run_query_as_flx(north_pole_box);
2✔
2245
                    CHECK(local_matches == num_matching_points);
2!
2246
                    CHECK(server_matches == num_matching_points);
2!
2247
                    CHECK(flx_matches == num_matching_points);
2!
2248
                }
2✔
2249
            }
2✔
2250
        });
2✔
2251
    }
2✔
2252

2253
    // Add new sections before this
2254
    SECTION("teardown") {
6✔
2255
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
2256
        harness.reset();
2✔
2257
    }
2✔
2258
}
6✔
2259
#endif // REALM_ENABLE_GEOSPATIAL
2260

2261
TEST_CASE("flx: interrupted bootstrap restarts/recovers on reconnect", "[sync][flx][bootstrap][baas]") {
2✔
2262
    FLXSyncTestHarness harness("flx_bootstrap_reconnect", {g_large_array_schema, {"queryable_int_field"}});
2✔
2263

2264
    std::vector<ObjectId> obj_ids_at_end = fill_large_array_schema(harness);
2✔
2265
    SyncTestFile interrupted_realm_config(harness.app()->current_user(), harness.schema(),
2✔
2266
                                          SyncConfig::FLXSyncEnabled{});
2✔
2267

2268
    {
2✔
2269
        auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2270
        Realm::Config config = interrupted_realm_config;
2✔
2271
        config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2272
        auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
2273
        config.sync_config->on_sync_client_event_hook =
2✔
2274
            [promise = std::move(shared_promise), seen_version_one = false](std::weak_ptr<SyncSession> weak_session,
2✔
2275
                                                                            const SyncClientHookData& data) mutable {
24✔
2276
                if (data.event != SyncClientHookEvent::DownloadMessageReceived) {
24✔
2277
                    return SyncClientHookAction::NoAction;
16✔
2278
                }
16✔
2279

2280
                auto session = weak_session.lock();
8✔
2281
                if (!session) {
8✔
2282
                    return SyncClientHookAction::NoAction;
×
UNCOV
2283
                }
×
2284

2285
                // If we haven't seen at least one download message for query version 1, then do nothing yet.
2286
                if (data.query_version == 0 || (data.query_version == 1 && !std::exchange(seen_version_one, true))) {
8✔
2287
                    return SyncClientHookAction::NoAction;
6✔
2288
                }
6✔
2289

2290
                REQUIRE(data.query_version == 1);
2!
2291
                REQUIRE(data.batch_state == sync::DownloadBatchState::MoreToCome);
2!
2292
                auto latest_subs = session->get_flx_subscription_store()->get_latest();
2✔
2293
                REQUIRE(latest_subs.version() == 1);
2!
2294
                REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::Bootstrapping);
2!
2295

2296
                session->close();
2✔
2297
                promise->emplace_value();
2✔
2298

2299
                return SyncClientHookAction::TriggerReconnect;
2✔
2300
            };
2✔
2301

2302
        auto realm = Realm::get_shared_realm(config);
2✔
2303
        {
2✔
2304
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2305
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
2306
            mut_subs.insert_or_assign(Query(table));
2✔
2307
            mut_subs.commit();
2✔
2308
        }
2✔
2309

2310
        interrupted.get();
2✔
2311
        realm->sync_session()->shutdown_and_wait();
2✔
2312
    }
2✔
2313

2314
    // Verify that the file was fully closed
2315
    REQUIRE(DB::call_with_lock(interrupted_realm_config.path, [](auto&) {}));
2!
2316

2317
    {
2✔
2318
        DBOptions options;
2✔
2319
        options.encryption_key = test_util::crypt_key();
2✔
2320
        auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
2321
        auto sub_store = sync::SubscriptionStore::create(realm);
2✔
2322
        auto version_info = sub_store->get_version_info();
2✔
2323
        REQUIRE(version_info.active == 0);
2!
2324
        REQUIRE(version_info.latest == 1);
2!
2325
        auto latest_subs = sub_store->get_latest();
2✔
2326
        REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::Bootstrapping);
2!
2327
        REQUIRE(latest_subs.size() == 1);
2!
2328
        REQUIRE(latest_subs.at(0).object_class_name == "TopLevel");
2!
2329
    }
2✔
2330

2331
    auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
2332
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
2333
    realm->get_latest_subscription_set().get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2334
    wait_for_advance(*realm);
2✔
2335
    REQUIRE(table->size() == obj_ids_at_end.size());
2!
2336
    for (auto& id : obj_ids_at_end) {
10✔
2337
        REQUIRE(table->find_primary_key(Mixed{id}));
10!
2338
    }
10✔
2339

2340
    auto active_subs = realm->get_active_subscription_set();
2✔
2341
    auto latest_subs = realm->get_latest_subscription_set();
2✔
2342
    REQUIRE(active_subs.version() == latest_subs.version());
2!
2343
    REQUIRE(active_subs.version() == int64_t(1));
2!
2344
}
2✔
2345

2346
TEST_CASE("flx: dev mode uploads schema before query change", "[sync][flx][query][baas]") {
2✔
2347
    FLXSyncTestHarness::ServerSchema server_schema;
2✔
2348
    auto default_schema = FLXSyncTestHarness::default_server_schema();
2✔
2349
    server_schema.queryable_fields = default_schema.queryable_fields;
2✔
2350
    server_schema.dev_mode_enabled = true;
2✔
2351
    server_schema.schema = Schema{};
2✔
2352

2353
    FLXSyncTestHarness harness("flx_dev_mode", server_schema);
2✔
2354
    auto foo_obj_id = ObjectId::gen();
2✔
2355
    auto bar_obj_id = ObjectId::gen();
2✔
2356
    harness.do_with_new_realm(
2✔
2357
        [&](SharedRealm realm) {
2✔
2358
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
2359
            // auto queryable_str_field = table->get_column_key("queryable_str_field");
2360
            // auto queryable_int_field = table->get_column_key("queryable_int_field");
2361
            auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2362
            new_query.insert_or_assign(Query(table));
2✔
2363
            new_query.commit();
2✔
2364

2365
            CppContext c(realm);
2✔
2366
            realm->begin_transaction();
2✔
2367
            Object::create(c, realm, "TopLevel",
2✔
2368
                           std::any(AnyDict{{"_id", foo_obj_id},
2✔
2369
                                            {"queryable_str_field", "foo"s},
2✔
2370
                                            {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2371
                                            {"non_queryable_field", "non queryable 1"s}}));
2✔
2372
            Object::create(c, realm, "TopLevel",
2✔
2373
                           std::any(AnyDict{{"_id", bar_obj_id},
2✔
2374
                                            {"queryable_str_field", "bar"s},
2✔
2375
                                            {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2376
                                            {"non_queryable_field", "non queryable 2"s}}));
2✔
2377
            realm->commit_transaction();
2✔
2378

2379
            wait_for_upload(*realm);
2✔
2380
        },
2✔
2381
        default_schema.schema);
2✔
2382

2383
    harness.do_with_new_realm(
2✔
2384
        [&](SharedRealm realm) {
2✔
2385
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
2386
            auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
2387
            auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2388
            new_query.insert_or_assign(Query(table).greater_equal(queryable_int_field, int64_t(5)));
2✔
2389
            auto subs = new_query.commit();
2✔
2390
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2391
            wait_for_download(*realm);
2✔
2392
            Results results(realm, table);
2✔
2393

2394
            realm->refresh();
2✔
2395
            CHECK(results.size() == 2);
2!
2396
            CHECK(table->get_object_with_primary_key({foo_obj_id}).is_valid());
2!
2397
            CHECK(table->get_object_with_primary_key({bar_obj_id}).is_valid());
2!
2398
        },
2✔
2399
        default_schema.schema);
2✔
2400
}
2✔
2401

2402
// This is a test case for the server's fix for RCORE-969
2403
TEST_CASE("flx: change-of-query history divergence", "[sync][flx][query][baas]") {
2✔
2404
    FLXSyncTestHarness harness("flx_coq_divergence");
2✔
2405

2406
    // first we create an object on the server and upload it.
2407
    auto foo_obj_id = ObjectId::gen();
2✔
2408
    harness.load_initial_data([&](SharedRealm realm) {
2✔
2409
        CppContext c(realm);
2✔
2410
        Object::create(c, realm, "TopLevel",
2✔
2411
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
2412
                                        {"queryable_str_field", "foo"s},
2✔
2413
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2414
                                        {"non_queryable_field", "created as initial data seed"s}}));
2✔
2415
    });
2✔
2416

2417
    // Now create another realm and wait for it to be fully synchronized with bootstrap version zero. i.e.
2418
    // our progress counters should be past the history entry containing the object created above.
2419
    auto test_file_config = harness.make_test_file();
2✔
2420
    auto realm = Realm::get_shared_realm(test_file_config);
2✔
2421
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
2422
    auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
2423

2424
    realm->get_latest_subscription_set().get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2425
    wait_for_upload(*realm);
2✔
2426
    wait_for_download(*realm);
2✔
2427

2428
    // Now disconnect the sync session
2429
    realm->sync_session()->pause();
2✔
2430

2431
    // And move the "foo" object created above into view and create a different diverging copy of it locally.
2432
    auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2433
    mut_subs.insert_or_assign(Query(table).equal(queryable_str_field, "foo"));
2✔
2434
    auto subs = mut_subs.commit();
2✔
2435

2436
    realm->begin_transaction();
2✔
2437
    CppContext c(realm);
2✔
2438
    Object::create(c, realm, "TopLevel",
2✔
2439
                   std::any(AnyDict{{"_id", foo_obj_id},
2✔
2440
                                    {"queryable_str_field", "foo"s},
2✔
2441
                                    {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2442
                                    {"non_queryable_field", "created locally"s}}));
2✔
2443
    realm->commit_transaction();
2✔
2444

2445
    // Reconnect the sync session and wait for the subscription that moved "foo" into view to be fully synchronized.
2446
    realm->sync_session()->resume();
2✔
2447
    wait_for_upload(*realm);
2✔
2448
    wait_for_download(*realm);
2✔
2449
    subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2450

2451
    wait_for_advance(*realm);
2✔
2452

2453
    // The bootstrap should have erase/re-created our object and we should have the version from the server
2454
    // locally.
2455
    auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any{foo_obj_id});
2✔
2456
    REQUIRE(obj.get_obj().get<int64_t>("queryable_int_field") == 5);
2!
2457
    REQUIRE(obj.get_obj().get<StringData>("non_queryable_field") == "created as initial data seed");
2!
2458

2459
    // Likewise, if we create a new realm and download all the objects, we should see the initial server version
2460
    // in the new realm rather than the "created locally" one.
2461
    harness.load_initial_data([&](SharedRealm realm) {
2✔
2462
        CppContext c(realm);
2✔
2463

2464
        auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any{foo_obj_id});
2✔
2465
        REQUIRE(obj.get_obj().get<int64_t>("queryable_int_field") == 5);
2!
2466
        REQUIRE(obj.get_obj().get<StringData>("non_queryable_field") == "created as initial data seed");
2!
2467
    });
2✔
2468
}
2✔
2469

2470
TEST_CASE("flx: writes work offline", "[sync][flx][baas]") {
2✔
2471
    FLXSyncTestHarness harness("flx_offline_writes");
2✔
2472

2473
    harness.do_with_new_realm([&](SharedRealm realm) {
2✔
2474
        auto sync_session = realm->sync_session();
2✔
2475
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
2476
        auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
2477
        auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
2478
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2479
        new_query.insert_or_assign(Query(table));
2✔
2480
        new_query.commit();
2✔
2481

2482
        auto foo_obj_id = ObjectId::gen();
2✔
2483
        auto bar_obj_id = ObjectId::gen();
2✔
2484

2485
        CppContext c(realm);
2✔
2486
        realm->begin_transaction();
2✔
2487
        Object::create(c, realm, "TopLevel",
2✔
2488
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
2489
                                        {"queryable_str_field", "foo"s},
2✔
2490
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2491
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
2492
        Object::create(c, realm, "TopLevel",
2✔
2493
                       std::any(AnyDict{{"_id", bar_obj_id},
2✔
2494
                                        {"queryable_str_field", "bar"s},
2✔
2495
                                        {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2496
                                        {"non_queryable_field", "non queryable 2"s}}));
2✔
2497
        realm->commit_transaction();
2✔
2498

2499
        wait_for_upload(*realm);
2✔
2500
        wait_for_download(*realm);
2✔
2501
        sync_session->pause();
2✔
2502

2503
        // Make it so the subscriptions only match the "foo" object
2504
        {
2✔
2505
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2506
            mut_subs.clear();
2✔
2507
            mut_subs.insert_or_assign(Query(table).equal(queryable_str_field, "foo"));
2✔
2508
            mut_subs.commit();
2✔
2509
        }
2✔
2510

2511
        // Make foo so that it will match the next subscription update. This checks whether you can do
2512
        // multiple subscription set updates offline and that the last one eventually takes effect when
2513
        // you come back online and fully synchronize.
2514
        {
2✔
2515
            Results results(realm, table);
2✔
2516
            realm->begin_transaction();
2✔
2517
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2518
            foo_obj.set<int64_t>(queryable_int_field, 15);
2✔
2519
            realm->commit_transaction();
2✔
2520
        }
2✔
2521

2522
        // Update our subscriptions so that both foo/bar will be included
2523
        {
2✔
2524
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2525
            mut_subs.clear();
2✔
2526
            mut_subs.insert_or_assign(Query(table).greater_equal(queryable_int_field, static_cast<int64_t>(10)));
2✔
2527
            mut_subs.commit();
2✔
2528
        }
2✔
2529

2530
        // Make foo out of view for the current subscription.
2531
        {
2✔
2532
            Results results(realm, table);
2✔
2533
            realm->begin_transaction();
2✔
2534
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2535
            foo_obj.set<int64_t>(queryable_int_field, 0);
2✔
2536
            realm->commit_transaction();
2✔
2537
        }
2✔
2538

2539
        sync_session->resume();
2✔
2540
        wait_for_upload(*realm);
2✔
2541
        wait_for_download(*realm);
2✔
2542

2543
        realm->refresh();
2✔
2544
        Results results(realm, table);
2✔
2545
        CHECK(results.size() == 1);
2!
2546
        CHECK(table->get_object_with_primary_key({bar_obj_id}).is_valid());
2!
2547
    });
2✔
2548
}
2✔
2549

2550
TEST_CASE("flx: writes work without waiting for sync", "[sync][flx][baas]") {
2✔
2551
    FLXSyncTestHarness harness("flx_offline_writes");
2✔
2552

2553
    harness.do_with_new_realm([&](SharedRealm realm) {
2✔
2554
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
2555
        auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
2556
        auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
2557
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2558
        new_query.insert_or_assign(Query(table));
2✔
2559
        new_query.commit();
2✔
2560

2561
        auto foo_obj_id = ObjectId::gen();
2✔
2562
        auto bar_obj_id = ObjectId::gen();
2✔
2563

2564
        CppContext c(realm);
2✔
2565
        realm->begin_transaction();
2✔
2566
        Object::create(c, realm, "TopLevel",
2✔
2567
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
2568
                                        {"queryable_str_field", "foo"s},
2✔
2569
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2570
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
2571
        Object::create(c, realm, "TopLevel",
2✔
2572
                       std::any(AnyDict{{"_id", bar_obj_id},
2✔
2573
                                        {"queryable_str_field", "bar"s},
2✔
2574
                                        {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2575
                                        {"non_queryable_field", "non queryable 2"s}}));
2✔
2576
        realm->commit_transaction();
2✔
2577

2578
        wait_for_upload(*realm);
2✔
2579

2580
        // Make it so the subscriptions only match the "foo" object
2581
        {
2✔
2582
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2583
            mut_subs.clear();
2✔
2584
            mut_subs.insert_or_assign(Query(table).equal(queryable_str_field, "foo"));
2✔
2585
            mut_subs.commit();
2✔
2586
        }
2✔
2587

2588
        // Make foo so that it will match the next subscription update. This checks whether you can do
2589
        // multiple subscription set updates without waiting and that the last one eventually takes effect when
2590
        // you fully synchronize.
2591
        {
2✔
2592
            Results results(realm, table);
2✔
2593
            realm->begin_transaction();
2✔
2594
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2595
            foo_obj.set<int64_t>(queryable_int_field, 15);
2✔
2596
            realm->commit_transaction();
2✔
2597
        }
2✔
2598

2599
        // Update our subscriptions so that both foo/bar will be included
2600
        {
2✔
2601
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2602
            mut_subs.clear();
2✔
2603
            mut_subs.insert_or_assign(Query(table).greater_equal(queryable_int_field, static_cast<int64_t>(10)));
2✔
2604
            mut_subs.commit();
2✔
2605
        }
2✔
2606

2607
        // Make foo out-of-view for the current subscription.
2608
        {
2✔
2609
            Results results(realm, table);
2✔
2610
            realm->begin_transaction();
2✔
2611
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2612
            foo_obj.set<int64_t>(queryable_int_field, 0);
2✔
2613
            realm->commit_transaction();
2✔
2614
        }
2✔
2615

2616
        wait_for_upload(*realm);
2✔
2617
        wait_for_download(*realm);
2✔
2618

2619
        realm->refresh();
2✔
2620
        Results results(realm, table);
2✔
2621
        CHECK(results.size() == 1);
2!
2622
        Obj obj = results.get(0);
2✔
2623
        CHECK(obj.get_primary_key().get_object_id() == bar_obj_id);
2!
2624
        CHECK(table->get_object_with_primary_key({bar_obj_id}).is_valid());
2!
2625
    });
2✔
2626
}
2✔
2627

2628
TEST_CASE("flx: verify websocket protocol number and prefixes", "[sync][protocol]") {
2✔
2629
    // Update the expected value whenever the protocol version is updated - this ensures
2630
    // that the current protocol version does not change unexpectedly.
2631
    REQUIRE(13 == sync::get_current_protocol_version());
2✔
2632
    // This was updated in Protocol V8 to use '#' instead of '/' to support the Web SDK
2633
    REQUIRE("com.mongodb.realm-sync#" == sync::get_pbs_websocket_protocol_prefix());
2✔
2634
    REQUIRE("com.mongodb.realm-query-sync#" == sync::get_flx_websocket_protocol_prefix());
2✔
2635
}
2✔
2636

2637
// TODO: remote-baas: This test fails consistently with Windows remote baas server - to be fixed in RCORE-1674
2638
#ifndef _WIN32
2639
TEST_CASE("flx: subscriptions persist after closing/reopening", "[sync][flx][baas]") {
2✔
2640
    FLXSyncTestHarness harness("flx_bad_query");
2✔
2641
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
2642

2643
    {
2✔
2644
        auto orig_realm = Realm::get_shared_realm(config);
2✔
2645
        auto mut_subs = orig_realm->get_latest_subscription_set().make_mutable_copy();
2✔
2646
        mut_subs.insert_or_assign(Query(orig_realm->read_group().get_table("class_TopLevel")));
2✔
2647
        mut_subs.commit();
2✔
2648
        orig_realm->close();
2✔
2649
    }
2✔
2650

2651
    {
2✔
2652
        auto new_realm = Realm::get_shared_realm(config);
2✔
2653
        auto latest_subs = new_realm->get_latest_subscription_set();
2✔
2654
        CHECK(latest_subs.size() == 1);
2!
2655
        latest_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2656
    }
2✔
2657
}
2✔
2658
#endif
2659

2660
TEST_CASE("flx: no subscription store created for PBS app", "[sync][flx][baas]") {
2✔
2661
    auto server_app_config = minimal_app_config("flx_connect_as_pbs", g_minimal_schema);
2✔
2662
    TestAppSession session(create_app(server_app_config));
2✔
2663
    SyncTestFile config(session.app()->current_user(), bson::Bson{}, g_minimal_schema);
2✔
2664

2665
    auto realm = Realm::get_shared_realm(config);
2✔
2666
    CHECK(!wait_for_download(*realm));
2!
2667
    CHECK(!wait_for_upload(*realm));
2!
2668

2669
    CHECK(!realm->sync_session()->get_flx_subscription_store());
2!
2670

2671
    CHECK_THROWS_AS(realm->get_active_subscription_set(), IllegalOperation);
2✔
2672
    CHECK_THROWS_AS(realm->get_latest_subscription_set(), IllegalOperation);
2✔
2673
}
2✔
2674

2675
TEST_CASE("flx: connect to FLX as PBS returns an error", "[sync][flx][baas]") {
2✔
2676
    FLXSyncTestHarness harness("connect_to_flx_as_pbs");
2✔
2677
    SyncTestFile config(harness.app()->current_user(), bson::Bson{}, harness.schema());
2✔
2678
    std::mutex sync_error_mutex;
2✔
2679
    util::Optional<SyncError> sync_error;
2✔
2680
    config.sync_config->error_handler = [&](std::shared_ptr<SyncSession>, SyncError error) mutable {
2✔
2681
        std::lock_guard<std::mutex> lk(sync_error_mutex);
2✔
2682
        sync_error = std::move(error);
2✔
2683
    };
2✔
2684
    auto realm = Realm::get_shared_realm(config);
2✔
2685
    timed_wait_for([&] {
5,469✔
2686
        std::lock_guard<std::mutex> lk(sync_error_mutex);
5,469✔
2687
        return static_cast<bool>(sync_error);
5,469✔
2688
    });
5,469✔
2689

2690
    CHECK(sync_error->status == ErrorCodes::WrongSyncType);
2!
2691
    CHECK(sync_error->server_requests_action == sync::ProtocolErrorInfo::Action::ApplicationBug);
2!
2692
}
2✔
2693

2694
TEST_CASE("flx: connect to FLX with partition value returns an error", "[sync][flx][protocol][baas]") {
2✔
2695
    FLXSyncTestHarness harness("connect_to_flx_as_pbs");
2✔
2696
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
2697
    config.sync_config->partition_value = "\"foobar\"";
2✔
2698

2699
    REQUIRE_EXCEPTION(Realm::get_shared_realm(config), IllegalCombination,
2✔
2700
                      "Cannot specify a partition value when flexible sync is enabled");
2✔
2701
}
2✔
2702

2703
TEST_CASE("flx: connect to PBS as FLX returns an error", "[sync][flx][protocol][baas]") {
2✔
2704
    auto server_app_config = minimal_app_config("flx_connect_as_pbs", g_minimal_schema);
2✔
2705
    TestAppSession session(create_app(server_app_config));
2✔
2706
    auto app = session.app();
2✔
2707
    auto user = app->current_user();
2✔
2708

2709
    SyncTestFile config(user, g_minimal_schema, SyncConfig::FLXSyncEnabled{});
2✔
2710

2711
    std::mutex sync_error_mutex;
2✔
2712
    util::Optional<SyncError> sync_error;
2✔
2713
    config.sync_config->error_handler = [&](std::shared_ptr<SyncSession>, SyncError error) mutable {
2✔
2714
        std::lock_guard lk(sync_error_mutex);
2✔
2715
        sync_error = std::move(error);
2✔
2716
    };
2✔
2717
    auto realm = Realm::get_shared_realm(config);
2✔
2718
    timed_wait_for([&] {
28,552✔
2719
        std::lock_guard lk(sync_error_mutex);
28,552✔
2720
        return static_cast<bool>(sync_error);
28,552✔
2721
    });
28,552✔
2722

2723
    CHECK(sync_error->status == ErrorCodes::WrongSyncType);
2!
2724
    CHECK(sync_error->server_requests_action == sync::ProtocolErrorInfo::Action::ApplicationBug);
2!
2725
}
2✔
2726

2727
TEST_CASE("flx: commit subscription while refreshing the access token", "[sync][flx][token][baas]") {
2✔
2728
    auto transport = std::make_shared<HookedTransport<>>();
2✔
2729
    FLXSyncTestHarness harness("flx_wait_access_token2", FLXSyncTestHarness::default_server_schema(), transport);
2✔
2730
    auto app = harness.app();
2✔
2731
    std::shared_ptr<User> user = app->current_user();
2✔
2732
    REQUIRE(user);
2!
2733
    REQUIRE(!user->access_token_refresh_required());
2!
2734
    // Set a bad access token, with an expired time. This will trigger a refresh initiated by the client.
2735
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2✔
2736
    using namespace std::chrono_literals;
2✔
2737
    auto expires = std::chrono::system_clock::to_time_t(now - 30s);
2✔
2738
    user->update_data_for_testing([&](UserData& data) {
2✔
2739
        data.access_token = RealmJWT(encode_fake_jwt("fake_access_token", expires));
2✔
2740
    });
2✔
2741
    REQUIRE(user->access_token_refresh_required());
2!
2742

2743
    bool seen_waiting_for_access_token = false;
2✔
2744
    // Commit a subcription set while there is no sync session.
2745
    // A session is created when the access token is refreshed.
2746
    transport->request_hook = [&](const Request&) {
2✔
2747
        auto user = app->current_user();
2✔
2748
        REQUIRE(user);
2!
2749
        for (auto& session : app->sync_manager()->get_all_sessions_for(*user)) {
2✔
2750
            if (session->state() == SyncSession::State::WaitingForAccessToken) {
2✔
2751
                REQUIRE(!seen_waiting_for_access_token);
2!
2752
                seen_waiting_for_access_token = true;
2✔
2753

2754
                auto store = session->get_flx_subscription_store();
2✔
2755
                REQUIRE(store);
2!
2756
                auto mut_subs = store->get_latest().make_mutable_copy();
2✔
2757
                mut_subs.commit();
2✔
2758
            }
2✔
2759
        }
2✔
2760
        return std::nullopt;
2✔
2761
    };
2✔
2762
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
2763
    // This triggers the token refresh.
2764
    auto r = Realm::get_shared_realm(config);
2✔
2765
    REQUIRE(seen_waiting_for_access_token);
2!
2766
}
2✔
2767

2768
TEST_CASE("flx: bootstrap batching prevents orphan documents", "[sync][flx][bootstrap][baas]") {
8✔
2769
    struct NovelException : public std::exception {
8✔
2770
        const char* what() const noexcept override
8✔
2771
        {
8✔
2772
            return "Oh no, a really weird exception happened!";
2✔
2773
        }
2✔
2774
    };
8✔
2775

2776
    FLXSyncTestHarness harness("flx_bootstrap_batching", {g_large_array_schema, {"queryable_int_field"}});
8✔
2777

2778
    std::vector<ObjectId> obj_ids_at_end = fill_large_array_schema(harness);
8✔
2779
    SyncTestFile interrupted_realm_config(harness.app()->current_user(), harness.schema(),
8✔
2780
                                          SyncConfig::FLXSyncEnabled{});
8✔
2781

2782
    auto check_interrupted_state = [&](const DBRef& realm) {
8✔
2783
        auto tr = realm->start_read();
8✔
2784
        auto top_level = tr->get_table("class_TopLevel");
8✔
2785
        REQUIRE(top_level);
8!
2786
        REQUIRE(top_level->is_empty());
8!
2787

2788
        auto sub_store = sync::SubscriptionStore::create(realm);
8✔
2789
        auto version_info = sub_store->get_version_info();
8✔
2790
        REQUIRE(version_info.latest == 1);
8!
2791
        REQUIRE(version_info.active == 0);
8!
2792
        auto latest_subs = sub_store->get_latest();
8✔
2793
        REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::Bootstrapping);
8!
2794
        REQUIRE(latest_subs.size() == 1);
8!
2795
        REQUIRE(latest_subs.at(0).object_class_name == "TopLevel");
8!
2796
    };
8✔
2797

2798
    auto mutate_realm = [&] {
8✔
2799
        harness.load_initial_data([&](SharedRealm realm) {
4✔
2800
            auto table = realm->read_group().get_table("class_TopLevel");
4✔
2801
            Results res(realm, Query(table).greater(table->get_column_key("queryable_int_field"), int64_t(10)));
4✔
2802
            REQUIRE(res.size() == 2);
4!
2803
            res.clear();
4✔
2804
        });
4✔
2805
    };
4✔
2806

2807
    SECTION("unknown exception occurs during bootstrap application on session startup") {
8✔
2808
        {
2✔
2809
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2810
            Realm::Config config = interrupted_realm_config;
2✔
2811
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2812
            auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
2813
            config.sync_config->on_sync_client_event_hook =
2✔
2814
                [promise = std::move(shared_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
2815
                                                      const SyncClientHookData& data) mutable {
42✔
2816
                    if (data.event != SyncClientHookEvent::BootstrapMessageProcessed) {
42✔
2817
                        return SyncClientHookAction::NoAction;
28✔
2818
                    }
28✔
2819
                    auto session = weak_session.lock();
14✔
2820
                    if (!session) {
14✔
2821
                        return SyncClientHookAction::NoAction;
×
UNCOV
2822
                    }
×
2823

2824
                    if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::LastInBatch) {
14✔
2825
                        session->close();
2✔
2826
                        promise->emplace_value();
2✔
2827
                        return SyncClientHookAction::EarlyReturn;
2✔
2828
                    }
2✔
2829
                    return SyncClientHookAction::NoAction;
12✔
2830
                };
14✔
2831
            auto realm = Realm::get_shared_realm(config);
2✔
2832
            {
2✔
2833
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2834
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
2835
                mut_subs.insert_or_assign(Query(table));
2✔
2836
                mut_subs.commit();
2✔
2837
            }
2✔
2838

2839
            interrupted.get();
2✔
2840
            realm->sync_session()->shutdown_and_wait();
2✔
2841
            realm->close();
2✔
2842
        }
2✔
2843

2844
        REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(interrupted_realm_config.path));
2!
2845

2846
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
2847
        // we expected it to be in.
2848
        {
2✔
2849
            DBOptions options;
2✔
2850
            options.encryption_key = test_util::crypt_key();
2✔
2851
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
2852
            auto logger = util::Logger::get_default_logger();
2✔
2853
            sync::PendingBootstrapStore bootstrap_store(realm, *logger);
2✔
2854
            REQUIRE(bootstrap_store.has_pending());
2!
2855
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
2856
            REQUIRE(pending_batch.query_version == 1);
2!
2857
            REQUIRE(pending_batch.progress);
2!
2858

2859
            check_interrupted_state(realm);
2✔
2860
        }
2✔
2861

2862
        auto error_pf = util::make_promise_future<SyncError>();
2✔
2863
        interrupted_realm_config.sync_config->error_handler =
2✔
2864
            [promise = std::make_shared<util::Promise<SyncError>>(std::move(error_pf.promise))](
2✔
2865
                std::shared_ptr<SyncSession>, SyncError error) {
2✔
2866
                promise->emplace_value(std::move(error));
2✔
2867
            };
2✔
2868

2869
        interrupted_realm_config.sync_config->on_sync_client_event_hook =
2✔
2870
            [&, download_message_received = false](std::weak_ptr<SyncSession>,
2✔
2871
                                                   const SyncClientHookData& data) mutable {
6✔
2872
                if (data.event == SyncClientHookEvent::DownloadMessageReceived) {
6✔
2873
                    download_message_received = true;
×
UNCOV
2874
                }
×
2875
                if (data.event != SyncClientHookEvent::BootstrapBatchAboutToProcess) {
6✔
2876
                    return SyncClientHookAction::NoAction;
4✔
2877
                }
4✔
2878

2879
                REQUIRE(!download_message_received);
2!
2880
                throw NovelException{};
2✔
UNCOV
2881
                return SyncClientHookAction::NoAction;
×
2882
            };
2✔
2883

2884
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
2885
        const auto& error = error_pf.future.get();
2✔
2886
        REQUIRE(!error.is_fatal);
2!
2887
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::Warning);
2!
2888
        REQUIRE(error.status == ErrorCodes::UnknownError);
2!
2889
        REQUIRE_THAT(error.status.reason(),
2✔
2890
                     Catch::Matchers::ContainsSubstring("Oh no, a really weird exception happened!"));
2✔
2891
    }
2✔
2892

2893
    SECTION("exception occurs during bootstrap application") {
8✔
2894
        Status error_status(ErrorCodes::OutOfMemory, "no more memory!");
2✔
2895
        {
2✔
2896
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2897
            Realm::Config config = interrupted_realm_config;
2✔
2898
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2899
            config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_session,
2✔
2900
                                                                const SyncClientHookData& data) mutable {
44✔
2901
                if (data.event != SyncClientHookEvent::BootstrapBatchAboutToProcess) {
44✔
2902
                    return SyncClientHookAction::NoAction;
40✔
2903
                }
40✔
2904
                auto session = weak_session.lock();
4✔
2905
                if (!session) {
4✔
2906
                    return SyncClientHookAction::NoAction;
×
UNCOV
2907
                }
×
2908

2909
                if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::MoreToCome) {
4✔
2910
                    throw sync::IntegrationException(error_status);
2✔
2911
                }
2✔
2912
                return SyncClientHookAction::NoAction;
2✔
2913
            };
4✔
2914
            auto error_pf = util::make_promise_future<SyncError>();
2✔
2915
            config.sync_config->error_handler =
2✔
2916
                [promise = std::make_shared<util::Promise<SyncError>>(std::move(error_pf.promise))](
2✔
2917
                    std::shared_ptr<SyncSession>, SyncError error) {
2✔
2918
                    promise->emplace_value(std::move(error));
2✔
2919
                };
2✔
2920

2921

2922
            auto realm = Realm::get_shared_realm(config);
2✔
2923
            {
2✔
2924
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2925
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
2926
                mut_subs.insert_or_assign(Query(table));
2✔
2927
                mut_subs.commit();
2✔
2928
            }
2✔
2929

2930
            auto error = error_pf.future.get();
2✔
2931
            REQUIRE(error.status.reason() == error_status.reason());
2!
2932
            REQUIRE(error.status == error_status);
2!
2933
            realm->sync_session()->shutdown_and_wait();
2✔
2934
            realm->close();
2✔
2935
        }
2✔
2936

2937
        REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(interrupted_realm_config.path));
2!
2938

2939
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
2940
        // we expected it to be in.
2941
        {
2✔
2942
            DBOptions options;
2✔
2943
            options.encryption_key = test_util::crypt_key();
2✔
2944
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
2945
            util::StderrLogger logger;
2✔
2946
            sync::PendingBootstrapStore bootstrap_store(realm, logger);
2✔
2947
            REQUIRE(bootstrap_store.has_pending());
2!
2948
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
2949
            REQUIRE(pending_batch.query_version == 1);
2!
2950
            REQUIRE(pending_batch.progress);
2!
2951

2952
            check_interrupted_state(realm);
2✔
2953
        }
2✔
2954

2955
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
2956
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
2957
        realm->get_latest_subscription_set()
2✔
2958
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
2959
            .get();
2✔
2960

2961
        wait_for_advance(*realm);
2✔
2962

2963
        REQUIRE(table->size() == obj_ids_at_end.size());
2!
2964
        for (auto& id : obj_ids_at_end) {
10✔
2965
            REQUIRE(table->find_primary_key(Mixed{id}));
10!
2966
        }
10✔
2967
    }
2✔
2968

2969
    SECTION("interrupted before final bootstrap message") {
8✔
2970
        {
2✔
2971
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2972
            Realm::Config config = interrupted_realm_config;
2✔
2973
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2974
            auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
2975
            config.sync_config->on_sync_client_event_hook =
2✔
2976
                [promise = std::move(shared_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
2977
                                                      const SyncClientHookData& data) mutable {
22✔
2978
                    if (data.event != SyncClientHookEvent::BootstrapMessageProcessed) {
22✔
2979
                        return SyncClientHookAction::NoAction;
18✔
2980
                    }
18✔
2981
                    auto session = weak_session.lock();
4✔
2982
                    if (!session) {
4✔
2983
                        return SyncClientHookAction::NoAction;
×
UNCOV
2984
                    }
×
2985

2986
                    if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::MoreToCome) {
4✔
2987
                        session->force_close();
2✔
2988
                        promise->emplace_value();
2✔
2989
                        return SyncClientHookAction::TriggerReconnect;
2✔
2990
                    }
2✔
2991
                    return SyncClientHookAction::NoAction;
2✔
2992
                };
4✔
2993
            auto realm = Realm::get_shared_realm(config);
2✔
2994
            {
2✔
2995
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2996
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
2997
                mut_subs.insert_or_assign(Query(table));
2✔
2998
                mut_subs.commit();
2✔
2999
            }
2✔
3000

3001
            interrupted.get();
2✔
3002
            realm->sync_session()->shutdown_and_wait();
2✔
3003
            realm->close();
2✔
3004
        }
2✔
3005

3006
        REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(interrupted_realm_config.path));
2!
3007

3008
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
3009
        // we expected it to be in.
3010
        {
2✔
3011
            DBOptions options;
2✔
3012
            options.encryption_key = test_util::crypt_key();
2✔
3013
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
3014
            auto logger = util::Logger::get_default_logger();
2✔
3015
            sync::PendingBootstrapStore bootstrap_store(realm, *logger);
2✔
3016
            REQUIRE(bootstrap_store.has_pending());
2!
3017
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
3018
            REQUIRE(pending_batch.query_version == 1);
2!
3019
            REQUIRE(!pending_batch.progress);
2!
3020
            REQUIRE(pending_batch.remaining_changesets == 0);
2!
3021
            REQUIRE(pending_batch.changesets.size() == 1);
2!
3022

3023
            check_interrupted_state(realm);
2✔
3024
        }
2✔
3025

3026
        // Now we'll open a different realm and make some changes that would leave orphan objects on the client
3027
        // if the bootstrap batches weren't being cached until lastInBatch were true.
3028
        mutate_realm();
2✔
3029

3030
        // Finally re-open the realm whose bootstrap we interrupted and just wait for it to finish downloading.
3031
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
3032
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
3033
        realm->get_latest_subscription_set()
2✔
3034
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
3035
            .get();
2✔
3036

3037
        wait_for_advance(*realm);
2✔
3038
        auto expected_obj_ids = util::Span<ObjectId>(obj_ids_at_end).sub_span(0, 3);
2✔
3039

3040
        REQUIRE(table->size() == expected_obj_ids.size());
2!
3041
        for (auto& id : expected_obj_ids) {
6✔
3042
            REQUIRE(table->find_primary_key(Mixed{id}));
6!
3043
        }
6✔
3044
    }
2✔
3045

3046
    SECTION("interrupted after final bootstrap message before processing") {
8✔
3047
        {
2✔
3048
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
3049
            Realm::Config config = interrupted_realm_config;
2✔
3050
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
3051
            auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
3052
            config.sync_config->on_sync_client_event_hook =
2✔
3053
                [promise = std::move(shared_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
3054
                                                      const SyncClientHookData& data) mutable {
42✔
3055
                    if (data.event != SyncClientHookEvent::BootstrapMessageProcessed) {
42✔
3056
                        return SyncClientHookAction::NoAction;
28✔
3057
                    }
28✔
3058
                    auto session = weak_session.lock();
14✔
3059
                    if (!session) {
14✔
3060
                        return SyncClientHookAction::NoAction;
×
UNCOV
3061
                    }
×
3062

3063
                    if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::LastInBatch) {
14✔
3064
                        session->force_close();
2✔
3065
                        promise->emplace_value();
2✔
3066
                        return SyncClientHookAction::TriggerReconnect;
2✔
3067
                    }
2✔
3068
                    return SyncClientHookAction::NoAction;
12✔
3069
                };
14✔
3070
            auto realm = Realm::get_shared_realm(config);
2✔
3071
            {
2✔
3072
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3073
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
3074
                mut_subs.insert_or_assign(Query(table));
2✔
3075
                mut_subs.commit();
2✔
3076
            }
2✔
3077

3078
            interrupted.get();
2✔
3079
            realm->sync_session()->shutdown_and_wait();
2✔
3080
            realm->close();
2✔
3081
        }
2✔
3082

3083
        REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(interrupted_realm_config.path));
2!
3084

3085
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
3086
        // we expected it to be in.
3087
        {
2✔
3088
            DBOptions options;
2✔
3089
            options.encryption_key = test_util::crypt_key();
2✔
3090
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
3091
            auto logger = util::Logger::get_default_logger();
2✔
3092
            sync::PendingBootstrapStore bootstrap_store(realm, *logger);
2✔
3093
            REQUIRE(bootstrap_store.has_pending());
2!
3094
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
3095
            REQUIRE(pending_batch.query_version == 1);
2!
3096
            REQUIRE(static_cast<bool>(pending_batch.progress));
2!
3097
            REQUIRE(pending_batch.remaining_changesets == 0);
2!
3098
            REQUIRE(pending_batch.changesets.size() == 6);
2!
3099

3100
            check_interrupted_state(realm);
2✔
3101
        }
2✔
3102

3103
        // Now we'll open a different realm and make some changes that would leave orphan objects on the client
3104
        // if the bootstrap batches weren't being cached until lastInBatch were true.
3105
        mutate_realm();
2✔
3106

3107
        auto [saw_valid_state_promise, saw_valid_state_future] = util::make_promise_future<void>();
2✔
3108
        auto shared_saw_valid_state_promise =
2✔
3109
            std::make_shared<decltype(saw_valid_state_promise)>(std::move(saw_valid_state_promise));
2✔
3110
        // This hook will let us check what the state of the realm is before it's integrated any new download
3111
        // messages from the server. This should be the full 5 object bootstrap that was received before we
3112
        // called mutate_realm().
3113
        interrupted_realm_config.sync_config->on_sync_client_event_hook =
2✔
3114
            [&, promise = std::move(shared_saw_valid_state_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
3115
                                                                     const SyncClientHookData& data) {
34✔
3116
                if (data.event != SyncClientHookEvent::DownloadMessageReceived) {
34✔
3117
                    return SyncClientHookAction::NoAction;
32✔
3118
                }
32✔
3119
                auto session = weak_session.lock();
2✔
3120
                if (!session) {
2✔
3121
                    return SyncClientHookAction::NoAction;
×
UNCOV
3122
                }
×
3123

3124
                if (data.query_version != 1 || data.batch_state == sync::DownloadBatchState::MoreToCome) {
2✔
3125
                    return SyncClientHookAction::NoAction;
×
UNCOV
3126
                }
×
3127

3128
                auto latest_sub_set = session->get_flx_subscription_store()->get_latest();
2✔
3129
                auto active_sub_set = session->get_flx_subscription_store()->get_active();
2✔
3130
                auto version_info = session->get_flx_subscription_store()->get_version_info();
2✔
3131
                REQUIRE(version_info.pending_mark == active_sub_set.version());
2!
3132
                REQUIRE(version_info.active == active_sub_set.version());
2!
3133
                REQUIRE(version_info.latest == latest_sub_set.version());
2!
3134
                REQUIRE(latest_sub_set.version() == active_sub_set.version());
2!
3135
                REQUIRE(active_sub_set.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3136

3137
                auto db = SyncSession::OnlyForTesting::get_db(*session);
2✔
3138
                auto tr = db->start_read();
2✔
3139

3140
                auto table = tr->get_table("class_TopLevel");
2✔
3141
                REQUIRE(table->size() == obj_ids_at_end.size());
2!
3142
                for (auto& id : obj_ids_at_end) {
10✔
3143
                    REQUIRE(table->find_primary_key(Mixed{id}));
10!
3144
                }
10✔
3145

3146
                promise->emplace_value();
2✔
3147
                return SyncClientHookAction::NoAction;
2✔
3148
            };
2✔
3149

3150
        // Finally re-open the realm whose bootstrap we interrupted and just wait for it to finish downloading.
3151
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
3152
        saw_valid_state_future.get();
2✔
3153
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
3154
        realm->get_latest_subscription_set()
2✔
3155
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
3156
            .get();
2✔
3157

3158
        wait_for_advance(*realm);
2✔
3159
        auto expected_obj_ids = util::Span<ObjectId>(obj_ids_at_end).sub_span(0, 3);
2✔
3160

3161
        // After we've downloaded all the mutations there should only by 3 objects left.
3162
        REQUIRE(table->size() == expected_obj_ids.size());
2!
3163
        for (auto& id : expected_obj_ids) {
6✔
3164
            REQUIRE(table->find_primary_key(Mixed{id}));
6!
3165
        }
6✔
3166
    }
2✔
3167
}
8✔
3168

3169
// Check that a document with the given id is present and has the expected fields
3170
static void check_document(const std::vector<bson::BsonDocument>& documents, ObjectId id,
3171
                           std::initializer_list<std::pair<const char*, bson::Bson>> fields)
3172
{
428✔
3173
    auto it = std::find_if(documents.begin(), documents.end(), [&](auto&& doc) {
43,096✔
3174
        auto val = doc.find("_id");
43,096✔
3175
        REQUIRE(val);
43,096!
3176
        return *val == id;
43,096✔
3177
    });
43,096✔
3178
    REQUIRE(it != documents.end());
428!
3179
    auto& doc = *it;
428✔
3180
    for (auto& [name, expected_value] : fields) {
434✔
3181
        auto val = doc.find(name);
434✔
3182
        REQUIRE(val);
434!
3183

3184
        // bson documents are ordered  but Realm dictionaries aren't, so the
3185
        // document might validly be in a different order than we expected and
3186
        // we need to do a comparison that doesn't check order.
3187
        if (expected_value.type() == bson::Bson::Type::Document) {
434✔
3188
            REQUIRE(static_cast<const bson::BsonDocument&>(*val) ==
8!
3189
                    static_cast<const bson::BsonDocument&>(expected_value));
8✔
3190
        }
8✔
3191
        else {
426✔
3192
            REQUIRE(*val == expected_value);
426!
3193
        }
426✔
3194
    }
434✔
3195
}
428✔
3196

3197
TEST_CASE("flx: data ingest", "[sync][flx][data ingest][baas]") {
22✔
3198
    using namespace ::realm::bson;
22✔
3199

3200
    static auto server_schema = [] {
22✔
3201
        FLXSyncTestHarness::ServerSchema server_schema;
2✔
3202
        server_schema.queryable_fields = {"queryable_str_field"};
2✔
3203
        server_schema.schema = {
2✔
3204
            {"Asymmetric",
2✔
3205
             ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3206
             {
2✔
3207
                 {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3208
                 {"location", PropertyType::String | PropertyType::Nullable},
2✔
3209
                 {"embedded obj", PropertyType::Object | PropertyType::Nullable, "Embedded"},
2✔
3210
                 {"embedded list", PropertyType::Object | PropertyType::Array, "Embedded"},
2✔
3211
                 {"embedded dictionary", PropertyType::Object | PropertyType::Nullable | PropertyType::Dictionary,
2✔
3212
                  "Embedded"},
2✔
3213
                 {"link obj", PropertyType::Object | PropertyType::Nullable, "TopLevel"},
2✔
3214
                 {"link list", PropertyType::Object | PropertyType::Array, "TopLevel"},
2✔
3215
                 {"link dictionary", PropertyType::Object | PropertyType::Nullable | PropertyType::Dictionary,
2✔
3216
                  "TopLevel"},
2✔
3217
             }},
2✔
3218
            {"Embedded", ObjectSchema::ObjectType::Embedded, {{"value", PropertyType::String}}},
2✔
3219
            {"TopLevel",
2✔
3220
             {
2✔
3221
                 {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3222
                 {"value", PropertyType::Int},
2✔
3223
             }},
2✔
3224
        };
2✔
3225
        return server_schema;
2✔
3226
    }();
2✔
3227
    static auto harness = std::make_unique<FLXSyncTestHarness>("asymmetric_sync", server_schema);
22✔
3228

3229
    // We reuse a single app for each section, so tests will see the documents
3230
    // created by previous tests and we need to add those documents to the count
3231
    // we're waiting for
3232
    static std::unordered_map<std::string, size_t> previous_count;
22✔
3233
    auto get_documents = [&](const char* name, size_t expected_count) {
22✔
3234
        auto& count = previous_count[name];
18✔
3235
        auto documents =
18✔
3236
            harness->session().get_documents(*harness->app()->current_user(), name, count + expected_count);
18✔
3237
        count = documents.size();
18✔
3238
        return documents;
18✔
3239
    };
18✔
3240

3241
    SECTION("basic object construction") {
22✔
3242
        auto foo_obj_id = ObjectId::gen();
2✔
3243
        auto bar_obj_id = ObjectId::gen();
2✔
3244
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3245
            realm->begin_transaction();
2✔
3246
            CppContext c(realm);
2✔
3247
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "foo"s}}));
2✔
3248
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", bar_obj_id}, {"location", "bar"s}}));
2✔
3249
            realm->commit_transaction();
2✔
3250

3251
            auto documents = get_documents("Asymmetric", 2);
2✔
3252
            check_document(documents, foo_obj_id, {{"location", "foo"}});
2✔
3253
            check_document(documents, bar_obj_id, {{"location", "bar"}});
2✔
3254
        });
2✔
3255

3256
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3257
            wait_for_download(*realm);
2✔
3258

3259
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3260
            REQUIRE(table->size() == 0);
2!
3261
            // Cannot query asymmetric tables.
3262
            CHECK_THROWS_AS(Query(table), LogicError);
2✔
3263
        });
2✔
3264
    }
2✔
3265

3266
    SECTION("do not allow objects with same key within the same transaction") {
22✔
3267
        auto foo_obj_id = ObjectId::gen();
2✔
3268
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3269
            realm->begin_transaction();
2✔
3270
            CppContext c(realm);
2✔
3271
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "foo"s}}));
2✔
3272
            CHECK_THROWS_WITH(
2✔
3273
                Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "bar"s}})),
2✔
3274
                "Attempting to create an object of type 'Asymmetric' with an existing primary key value 'not "
2✔
3275
                "implemented'");
2✔
3276
            realm->commit_transaction();
2✔
3277

3278
            auto documents = get_documents("Asymmetric", 1);
2✔
3279
            check_document(documents, foo_obj_id, {{"location", "foo"}});
2✔
3280
        });
2✔
3281
    }
2✔
3282

3283
    SECTION("create multiple objects - separate commits") {
22✔
3284
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3285
            CppContext c(realm);
2✔
3286
            std::vector<ObjectId> obj_ids;
2✔
3287
            for (int i = 0; i < 100; ++i) {
202✔
3288
                realm->begin_transaction();
200✔
3289
                obj_ids.push_back(ObjectId::gen());
200✔
3290
                Object::create(c, realm, "Asymmetric",
200✔
3291
                               std::any(AnyDict{
200✔
3292
                                   {"_id", obj_ids.back()},
200✔
3293
                                   {"location", util::format("foo_%1", i)},
200✔
3294
                               }));
200✔
3295
                realm->commit_transaction();
200✔
3296
            }
200✔
3297

3298
            wait_for_upload(*realm);
2✔
3299
            wait_for_download(*realm);
2✔
3300

3301
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3302
            REQUIRE(table->size() == 0);
2!
3303

3304
            auto documents = get_documents("Asymmetric", 100);
2✔
3305
            for (int i = 0; i < 100; ++i) {
202✔
3306
                check_document(documents, obj_ids[i], {{"location", util::format("foo_%1", i)}});
200✔
3307
            }
200✔
3308
        });
2✔
3309
    }
2✔
3310

3311
    SECTION("create multiple objects - same commit") {
22✔
3312
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3313
            CppContext c(realm);
2✔
3314
            realm->begin_transaction();
2✔
3315
            std::vector<ObjectId> obj_ids;
2✔
3316
            for (int i = 0; i < 100; ++i) {
202✔
3317
                obj_ids.push_back(ObjectId::gen());
200✔
3318
                Object::create(c, realm, "Asymmetric",
200✔
3319
                               std::any(AnyDict{
200✔
3320
                                   {"_id", obj_ids.back()},
200✔
3321
                                   {"location", util::format("bar_%1", i)},
200✔
3322
                               }));
200✔
3323
            }
200✔
3324
            realm->commit_transaction();
2✔
3325

3326
            wait_for_upload(*realm);
2✔
3327
            wait_for_download(*realm);
2✔
3328

3329
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3330
            REQUIRE(table->size() == 0);
2!
3331

3332
            auto documents = get_documents("Asymmetric", 100);
2✔
3333
            for (int i = 0; i < 100; ++i) {
202✔
3334
                check_document(documents, obj_ids[i], {{"location", util::format("bar_%1", i)}});
200✔
3335
            }
200✔
3336
        });
2✔
3337
    }
2✔
3338

3339
    SECTION("open with schema mismatch on IsAsymmetric") {
22✔
3340
        auto schema = server_schema.schema;
2✔
3341
        schema.find("Asymmetric")->table_type = ObjectSchema::ObjectType::TopLevel;
2✔
3342

3343
        harness->do_with_new_user([&](std::shared_ptr<SyncUser> user) {
2✔
3344
            SyncTestFile config(user, schema, SyncConfig::FLXSyncEnabled{});
2✔
3345
            auto [error_promise, error_future] = util::make_promise_future<SyncError>();
2✔
3346
            auto error_count = 0;
2✔
3347
            auto err_handler = [promise = util::CopyablePromiseHolder(std::move(error_promise)),
2✔
3348
                                &error_count](std::shared_ptr<SyncSession>, SyncError err) mutable {
4✔
3349
                ++error_count;
4✔
3350
                if (error_count == 1) {
4✔
3351
                    // Bad changeset detected by the client.
3352
                    CHECK(err.status == ErrorCodes::BadChangeset);
2!
3353
                }
2✔
3354
                else if (error_count == 2) {
2✔
3355
                    // Server asking for a client reset.
3356
                    CHECK(err.status == ErrorCodes::SyncClientResetRequired);
2!
3357
                    CHECK(err.is_client_reset_requested());
2!
3358
                    promise.get_promise().emplace_value(std::move(err));
2✔
3359
                }
2✔
3360
            };
4✔
3361

3362
            config.sync_config->error_handler = err_handler;
2✔
3363
            auto realm = Realm::get_shared_realm(config);
2✔
3364

3365
            auto err = error_future.get();
2✔
3366
            CHECK(error_count == 2);
2!
3367
        });
2✔
3368
    }
2✔
3369

3370
    SECTION("basic embedded object construction") {
22✔
3371
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3372
            auto obj_id = ObjectId::gen();
2✔
3373
            realm->begin_transaction();
2✔
3374
            CppContext c(realm);
2✔
3375
            Object::create(c, realm, "Asymmetric",
2✔
3376
                           std::any(AnyDict{
2✔
3377
                               {"_id", obj_id},
2✔
3378
                               {"embedded obj", AnyDict{{"value", "foo"s}}},
2✔
3379
                           }));
2✔
3380
            realm->commit_transaction();
2✔
3381
            wait_for_upload(*realm);
2✔
3382

3383
            auto documents = get_documents("Asymmetric", 1);
2✔
3384
            check_document(documents, obj_id, {{"embedded obj", BsonDocument{{"value", "foo"}}}});
2✔
3385
        });
2✔
3386

3387
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3388
            wait_for_download(*realm);
2✔
3389

3390
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3391
            REQUIRE(table->size() == 0);
2!
3392
        });
2✔
3393
    }
2✔
3394

3395
    SECTION("replace embedded object") {
22✔
3396
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3397
            CppContext c(realm);
2✔
3398
            auto foo_obj_id = ObjectId::gen();
2✔
3399

3400
            realm->begin_transaction();
2✔
3401
            Object::create(c, realm, "Asymmetric",
2✔
3402
                           std::any(AnyDict{
2✔
3403
                               {"_id", foo_obj_id},
2✔
3404
                               {"embedded obj", AnyDict{{"value", "foo"s}}},
2✔
3405
                           }));
2✔
3406
            realm->commit_transaction();
2✔
3407

3408
            // Update embedded field to `null`. The server discards this write
3409
            // as asymmetric sync can only create new objects.
3410
            realm->begin_transaction();
2✔
3411
            Object::create(c, realm, "Asymmetric",
2✔
3412
                           std::any(AnyDict{
2✔
3413
                               {"_id", foo_obj_id},
2✔
3414
                               {"embedded obj", std::any()},
2✔
3415
                           }));
2✔
3416
            realm->commit_transaction();
2✔
3417

3418
            // create a second object so that we can know when the translator
3419
            // has processed everything
3420
            realm->begin_transaction();
2✔
3421
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", ObjectId::gen()}, {}}));
2✔
3422
            realm->commit_transaction();
2✔
3423

3424
            wait_for_upload(*realm);
2✔
3425
            wait_for_download(*realm);
2✔
3426

3427
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3428
            REQUIRE(table->size() == 0);
2!
3429

3430
            auto documents = get_documents("Asymmetric", 2);
2✔
3431
            check_document(documents, foo_obj_id, {{"embedded obj", BsonDocument{{"value", "foo"}}}});
2✔
3432
        });
2✔
3433
    }
2✔
3434

3435
    SECTION("embedded collections") {
22✔
3436
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3437
            CppContext c(realm);
2✔
3438
            auto obj_id = ObjectId::gen();
2✔
3439

3440
            realm->begin_transaction();
2✔
3441
            Object::create(c, realm, "Asymmetric",
2✔
3442
                           std::any(AnyDict{
2✔
3443
                               {"_id", obj_id},
2✔
3444
                               {"embedded list", AnyVector{AnyDict{{"value", "foo"s}}, AnyDict{{"value", "bar"s}}}},
2✔
3445
                               {"embedded dictionary",
2✔
3446
                                AnyDict{
2✔
3447
                                    {"key1", AnyDict{{"value", "foo"s}}},
2✔
3448
                                    {"key2", AnyDict{{"value", "bar"s}}},
2✔
3449
                                }},
2✔
3450
                           }));
2✔
3451
            realm->commit_transaction();
2✔
3452

3453
            auto documents = get_documents("Asymmetric", 1);
2✔
3454
            check_document(
2✔
3455
                documents, obj_id,
2✔
3456
                {
2✔
3457
                    {"embedded list", BsonArray{BsonDocument{{"value", "foo"}}, BsonDocument{{"value", "bar"}}}},
2✔
3458
                    {"embedded dictionary",
2✔
3459
                     BsonDocument{
2✔
3460
                         {"key1", BsonDocument{{"value", "foo"}}},
2✔
3461
                         {"key2", BsonDocument{{"value", "bar"}}},
2✔
3462
                     }},
2✔
3463
                });
2✔
3464
        });
2✔
3465
    }
2✔
3466

3467
    SECTION("asymmetric table not allowed in PBS") {
22✔
3468
        Schema schema{
2✔
3469
            {"Asymmetric2",
2✔
3470
             ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3471
             {
2✔
3472
                 {"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
3473
                 {"location", PropertyType::Int},
2✔
3474
                 {"reading", PropertyType::Int},
2✔
3475
             }},
2✔
3476
        };
2✔
3477

3478
        SyncTestFile config(harness->app()->current_user(), Bson{}, schema);
2✔
3479
        REQUIRE_EXCEPTION(
2✔
3480
            Realm::get_shared_realm(config), SchemaValidationFailed,
2✔
3481
            Catch::Matchers::ContainsSubstring("Asymmetric table 'Asymmetric2' not allowed in partition based sync"));
2✔
3482
    }
2✔
3483

3484
    SECTION("links to top-level objects") {
22✔
3485
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3486
            subscribe_to_all_and_bootstrap(*realm);
2✔
3487

3488
            ObjectId obj_id = ObjectId::gen();
2✔
3489
            std::array<ObjectId, 5> target_obj_ids;
2✔
3490
            for (auto& id : target_obj_ids) {
10✔
3491
                id = ObjectId::gen();
10✔
3492
            }
10✔
3493

3494
            realm->begin_transaction();
2✔
3495
            CppContext c(realm);
2✔
3496
            Object::create(c, realm, "Asymmetric",
2✔
3497
                           std::any(AnyDict{
2✔
3498
                               {"_id", obj_id},
2✔
3499
                               {"link obj", AnyDict{{"_id", target_obj_ids[0]}, {"value", INT64_C(10)}}},
2✔
3500
                               {"link list",
2✔
3501
                                AnyVector{
2✔
3502
                                    AnyDict{{"_id", target_obj_ids[1]}, {"value", INT64_C(11)}},
2✔
3503
                                    AnyDict{{"_id", target_obj_ids[2]}, {"value", INT64_C(12)}},
2✔
3504
                                }},
2✔
3505
                               {"link dictionary",
2✔
3506
                                AnyDict{
2✔
3507
                                    {"key1", AnyDict{{"_id", target_obj_ids[3]}, {"value", INT64_C(13)}}},
2✔
3508
                                    {"key2", AnyDict{{"_id", target_obj_ids[4]}, {"value", INT64_C(14)}}},
2✔
3509
                                }},
2✔
3510
                           }));
2✔
3511
            realm->commit_transaction();
2✔
3512
            wait_for_upload(*realm);
2✔
3513

3514
            auto docs1 = get_documents("Asymmetric", 1);
2✔
3515
            check_document(docs1, obj_id,
2✔
3516
                           {{"link obj", target_obj_ids[0]},
2✔
3517
                            {"link list", BsonArray{{target_obj_ids[1], target_obj_ids[2]}}},
2✔
3518
                            {
2✔
3519
                                "link dictionary",
2✔
3520
                                BsonDocument{
2✔
3521
                                    {"key1", target_obj_ids[3]},
2✔
3522
                                    {"key2", target_obj_ids[4]},
2✔
3523
                                },
2✔
3524
                            }});
2✔
3525

3526
            auto docs2 = get_documents("TopLevel", 5);
2✔
3527
            for (int64_t i = 0; i < 5; ++i) {
12✔
3528
                check_document(docs2, target_obj_ids[i], {{"value", 10 + i}});
10✔
3529
            }
10✔
3530
        });
2✔
3531
    }
2✔
3532

3533
    // Add any new test sections above this point
3534

3535
    SECTION("teardown") {
22✔
3536
        harness.reset();
2✔
3537
    }
2✔
3538
}
22✔
3539

3540
TEST_CASE("flx: data ingest - dev mode", "[sync][flx][data ingest][baas]") {
2✔
3541
    FLXSyncTestHarness::ServerSchema server_schema;
2✔
3542
    server_schema.dev_mode_enabled = true;
2✔
3543
    server_schema.schema = Schema{};
2✔
3544

3545
    auto schema = Schema{{"Asymmetric",
2✔
3546
                          ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3547
                          {
2✔
3548
                              {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3549
                              {"location", PropertyType::String | PropertyType::Nullable},
2✔
3550
                          }},
2✔
3551
                         {"TopLevel",
2✔
3552
                          {
2✔
3553
                              {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3554
                              {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
3555
                          }}};
2✔
3556

3557
    FLXSyncTestHarness harness("asymmetric_sync", server_schema);
2✔
3558

3559
    auto foo_obj_id = ObjectId::gen();
2✔
3560
    auto bar_obj_id = ObjectId::gen();
2✔
3561

3562
    harness.do_with_new_realm(
2✔
3563
        [&](SharedRealm realm) {
2✔
3564
            CppContext c(realm);
2✔
3565
            realm->begin_transaction();
2✔
3566
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "foo"s}}));
2✔
3567
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", bar_obj_id}, {"location", "bar"s}}));
2✔
3568
            realm->commit_transaction();
2✔
3569
            User* user = dynamic_cast<User*>(realm->config().sync_config->user.get());
2✔
3570
            REALM_ASSERT(user);
2✔
3571
            auto docs = harness.session().get_documents(*user, "Asymmetric", 2);
2✔
3572
            check_document(docs, foo_obj_id, {{"location", "foo"}});
2✔
3573
            check_document(docs, bar_obj_id, {{"location", "bar"}});
2✔
3574
        },
2✔
3575
        schema);
2✔
3576
}
2✔
3577

3578
TEST_CASE("flx: data ingest - write not allowed", "[sync][flx][data ingest][baas]") {
2✔
3579
    AppCreateConfig::ServiceRole role;
2✔
3580
    role.name = "asymmetric_write_perms";
2✔
3581

3582
    AppCreateConfig::ServiceRoleDocumentFilters doc_filters;
2✔
3583
    doc_filters.read = true;
2✔
3584
    doc_filters.write = false;
2✔
3585
    role.document_filters = doc_filters;
2✔
3586

3587
    role.insert_filter = true;
2✔
3588
    role.delete_filter = true;
2✔
3589
    role.read = true;
2✔
3590
    role.write = true;
2✔
3591

3592
    Schema schema({
2✔
3593
        {"Asymmetric",
2✔
3594
         ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3595
         {
2✔
3596
             {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3597
             {"location", PropertyType::String | PropertyType::Nullable},
2✔
3598
             {"embedded_obj", PropertyType::Object | PropertyType::Nullable, "Embedded"},
2✔
3599
         }},
2✔
3600
        {"Embedded",
2✔
3601
         ObjectSchema::ObjectType::Embedded,
2✔
3602
         {
2✔
3603
             {"value", PropertyType::String | PropertyType::Nullable},
2✔
3604
         }},
2✔
3605
    });
2✔
3606
    FLXSyncTestHarness::ServerSchema server_schema{schema, {}, {role}};
2✔
3607
    FLXSyncTestHarness harness("asymmetric_sync", server_schema);
2✔
3608

3609
    auto error_received_pf = util::make_promise_future<void>();
2✔
3610
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3611
    config.sync_config->on_sync_client_event_hook =
2✔
3612
        [promise = util::CopyablePromiseHolder(std::move(error_received_pf.promise))](
2✔
3613
            std::weak_ptr<SyncSession> weak_session, const SyncClientHookData& data) mutable {
22✔
3614
            if (data.event != SyncClientHookEvent::ErrorMessageReceived) {
22✔
3615
                return SyncClientHookAction::NoAction;
18✔
3616
            }
18✔
3617
            auto session = weak_session.lock();
4✔
3618
            REQUIRE(session);
4!
3619

3620
            auto error_code = sync::ProtocolError(data.error_info->raw_error_code);
4✔
3621

3622
            if (error_code == sync::ProtocolError::initial_sync_not_completed) {
4✔
3623
                return SyncClientHookAction::NoAction;
2✔
3624
            }
2✔
3625

3626
            REQUIRE(error_code == sync::ProtocolError::write_not_allowed);
2!
3627
            REQUIRE_FALSE(data.error_info->compensating_write_server_version.has_value());
2!
3628
            REQUIRE_FALSE(data.error_info->compensating_writes.empty());
2!
3629
            promise.get_promise().emplace_value();
2✔
3630

3631
            return SyncClientHookAction::EarlyReturn;
2✔
3632
        };
2✔
3633

3634
    auto realm = Realm::get_shared_realm(config);
2✔
3635

3636
    // Create an asymmetric object and upload it to the server.
3637
    {
2✔
3638
        realm->begin_transaction();
2✔
3639
        CppContext c(realm);
2✔
3640
        Object::create(c, realm, "Asymmetric",
2✔
3641
                       std::any(AnyDict{{"_id", ObjectId::gen()}, {"embedded_obj", AnyDict{{"value", "foo"s}}}}));
2✔
3642
        realm->commit_transaction();
2✔
3643
    }
2✔
3644

3645
    error_received_pf.future.get();
2✔
3646
    realm->close();
2✔
3647
}
2✔
3648

3649
TEST_CASE("flx: send client error", "[sync][flx][baas]") {
2✔
3650
    FLXSyncTestHarness harness("flx_client_error");
2✔
3651

3652
    // An integration error is simulated while bootstrapping.
3653
    // This results in the client sending an error message to the server.
3654
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3655
    config.sync_config->simulate_integration_error = true;
2✔
3656

3657
    auto [error_promise, error_future] = util::make_promise_future<SyncError>();
2✔
3658
    auto error_count = 0;
2✔
3659
    auto err_handler = [promise = util::CopyablePromiseHolder(std::move(error_promise)),
2✔
3660
                        &error_count](std::shared_ptr<SyncSession>, SyncError err) mutable {
4✔
3661
        ++error_count;
4✔
3662
        if (error_count == 1) {
4✔
3663
            // Bad changeset detected by the client.
3664
            CHECK(err.status == ErrorCodes::BadChangeset);
2!
3665
        }
2✔
3666
        else if (error_count == 2) {
2✔
3667
            // Server asking for a client reset.
3668
            CHECK(err.status == ErrorCodes::SyncClientResetRequired);
2!
3669
            CHECK(err.is_client_reset_requested());
2!
3670
            promise.get_promise().emplace_value(std::move(err));
2✔
3671
        }
2✔
3672
    };
4✔
3673

3674
    config.sync_config->error_handler = err_handler;
2✔
3675
    auto realm = Realm::get_shared_realm(config);
2✔
3676
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
3677
    auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3678
    new_query.insert_or_assign(Query(table));
2✔
3679
    new_query.commit();
2✔
3680

3681
    auto err = error_future.get();
2✔
3682
    CHECK(error_count == 2);
2!
3683
}
2✔
3684

3685
TEST_CASE("flx: bootstraps contain all changes", "[sync][flx][bootstrap][baas]") {
6✔
3686
    FLXSyncTestHarness harness("bootstrap_full_sync");
6✔
3687

3688
    auto setup_subs = [](SharedRealm& realm) {
12✔
3689
        auto table = realm->read_group().get_table("class_TopLevel");
12✔
3690
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
12✔
3691
        new_query.clear();
12✔
3692
        auto col = table->get_column_key("queryable_str_field");
12✔
3693
        new_query.insert_or_assign(Query(table).equal(col, StringData("bar")).Or().equal(col, StringData("bizz")));
12✔
3694
        return new_query.commit();
12✔
3695
    };
12✔
3696

3697
    auto bar_obj_id = ObjectId::gen();
6✔
3698
    auto bizz_obj_id = ObjectId::gen();
6✔
3699
    auto setup_and_poison_cache = [&] {
6✔
3700
        harness.load_initial_data([&](SharedRealm realm) {
6✔
3701
            CppContext c(realm);
6✔
3702
            Object::create(c, realm, "TopLevel",
6✔
3703
                           std::any(AnyDict{{"_id", bar_obj_id},
6✔
3704
                                            {"queryable_str_field", std::string{"bar"}},
6✔
3705
                                            {"queryable_int_field", static_cast<int64_t>(10)},
6✔
3706
                                            {"non_queryable_field", std::string{"non queryable 2"}}}));
6✔
3707
        });
6✔
3708

3709
        harness.do_with_new_realm([&](SharedRealm realm) {
6✔
3710
            // first set a subscription to force the creation/caching of a broker snapshot on the server.
3711
            setup_subs(realm).get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
6✔
3712
            wait_for_advance(*realm);
6✔
3713
            auto table = realm->read_group().get_table("class_TopLevel");
6✔
3714
            REQUIRE(table->find_primary_key(bar_obj_id));
6!
3715

3716
            // Then create an object that won't be in the cached snapshot - this is the object that if we didn't
3717
            // wait for a MARK message to come back, we'd miss it in our results.
3718
            CppContext c(realm);
6✔
3719
            realm->begin_transaction();
6✔
3720
            Object::create(c, realm, "TopLevel",
6✔
3721
                           std::any(AnyDict{{"_id", bizz_obj_id},
6✔
3722
                                            {"queryable_str_field", std::string{"bizz"}},
6✔
3723
                                            {"queryable_int_field", static_cast<int64_t>(15)},
6✔
3724
                                            {"non_queryable_field", std::string{"non queryable 3"}}}));
6✔
3725
            realm->commit_transaction();
6✔
3726
            wait_for_upload(*realm);
6✔
3727
        });
6✔
3728
    };
6✔
3729

3730
    SECTION("regular subscription change") {
6✔
3731
        SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3732
        std::atomic<bool> saw_truncated_bootstrap{false};
2✔
3733
        triggered_config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_sess,
2✔
3734
                                                                      const SyncClientHookData& data) {
32✔
3735
            auto sess = weak_sess.lock();
32✔
3736
            if (!sess || data.event != SyncClientHookEvent::BootstrapProcessed || data.query_version != 1) {
32✔
3737
                return SyncClientHookAction::NoAction;
30✔
3738
            }
30✔
3739

3740
            auto latest_subs = sess->get_flx_subscription_store()->get_latest();
2✔
3741
            REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3742
            REQUIRE(data.num_changesets == 1);
2!
3743
            auto db = SyncSession::OnlyForTesting::get_db(*sess);
2✔
3744
            auto read_tr = db->start_read();
2✔
3745
            auto table = read_tr->get_table("class_TopLevel");
2✔
3746
            REQUIRE(table->find_primary_key(bar_obj_id));
2!
3747
            REQUIRE_FALSE(table->find_primary_key(bizz_obj_id));
2!
3748
            saw_truncated_bootstrap.store(true);
2✔
3749

3750
            return SyncClientHookAction::NoAction;
2✔
3751
        };
2✔
3752
        auto problem_realm = Realm::get_shared_realm(triggered_config);
2✔
3753

3754
        // Setup the problem realm by waiting for it to be fully synchronized with an empty query, so the router
3755
        // on the server should have no new history entries, and then pause the router so it doesn't get any of
3756
        // the changes we're about to create.
3757
        wait_for_upload(*problem_realm);
2✔
3758
        wait_for_download(*problem_realm);
2✔
3759

3760
        nlohmann::json command_request = {
2✔
3761
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
3762
        };
2✔
3763
        auto resp_body =
2✔
3764
            SyncSession::OnlyForTesting::send_test_command(*problem_realm->sync_session(), command_request.dump())
2✔
3765
                .get();
2✔
3766
        REQUIRE(resp_body == "{}");
2!
3767

3768
        // Put some data into the server, this will be the data that will be in the broker cache.
3769
        setup_and_poison_cache();
2✔
3770

3771
        // Setup queries on the problem realm to bootstrap from the cached object. Bootstrapping will also resume
3772
        // the router, so all we need to do is wait for the subscription set to be complete and notifications to be
3773
        // processed.
3774
        setup_subs(problem_realm).get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
3775
        wait_for_advance(*problem_realm);
2✔
3776

3777
        REQUIRE(saw_truncated_bootstrap.load());
2!
3778
        auto table = problem_realm->read_group().get_table("class_TopLevel");
2✔
3779
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3780
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3781
    }
2✔
3782

3783
// TODO: remote-baas: This test fails intermittently with Windows remote baas server - to be fixed in RCORE-1674
3784
#ifndef _WIN32
6✔
3785
    SECTION("disconnect between bootstrap and mark") {
6✔
3786
        SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3787
        auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
3788
        triggered_config.sync_config->on_sync_client_event_hook =
2✔
3789
            [promise = util::CopyablePromiseHolder(std::move(interrupted_promise)), &bizz_obj_id,
2✔
3790
             &bar_obj_id](std::weak_ptr<SyncSession> weak_sess, const SyncClientHookData& data) mutable {
36✔
3791
                auto sess = weak_sess.lock();
36✔
3792
                if (!sess || data.event != SyncClientHookEvent::BootstrapProcessed || data.query_version != 1) {
36✔
3793
                    return SyncClientHookAction::NoAction;
34✔
3794
                }
34✔
3795

3796
                auto latest_subs = sess->get_flx_subscription_store()->get_latest();
2✔
3797
                REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3798
                REQUIRE(data.num_changesets == 1);
2!
3799
                auto db = SyncSession::OnlyForTesting::get_db(*sess);
2✔
3800
                auto read_tr = db->start_read();
2✔
3801
                auto table = read_tr->get_table("class_TopLevel");
2✔
3802
                REQUIRE(table->find_primary_key(bar_obj_id));
2!
3803
                REQUIRE_FALSE(table->find_primary_key(bizz_obj_id));
2!
3804

3805
                sess->pause();
2✔
3806
                promise.get_promise().emplace_value();
2✔
3807
                return SyncClientHookAction::NoAction;
2✔
3808
            };
2✔
3809
        auto problem_realm = Realm::get_shared_realm(triggered_config);
2✔
3810

3811
        // Setup the problem realm by waiting for it to be fully synchronized with an empty query, so the router
3812
        // on the server should have no new history entries, and then pause the router so it doesn't get any of
3813
        // the changes we're about to create.
3814
        wait_for_upload(*problem_realm);
2✔
3815
        wait_for_download(*problem_realm);
2✔
3816

3817
        nlohmann::json command_request = {
2✔
3818
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
3819
        };
2✔
3820
        auto resp_body =
2✔
3821
            SyncSession::OnlyForTesting::send_test_command(*problem_realm->sync_session(), command_request.dump())
2✔
3822
                .get();
2✔
3823
        REQUIRE(resp_body == "{}");
2!
3824

3825
        // Put some data into the server, this will be the data that will be in the broker cache.
3826
        setup_and_poison_cache();
2✔
3827

3828
        // Setup queries on the problem realm to bootstrap from the cached object. Bootstrapping will also resume
3829
        // the router, so all we need to do is wait for the subscription set to be complete and notifications to be
3830
        // processed.
3831
        auto sub_set = setup_subs(problem_realm);
2✔
3832
        auto sub_complete_future = sub_set.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
3833

3834
        interrupted.get();
2✔
3835
        problem_realm->sync_session()->shutdown_and_wait();
2✔
3836
        REQUIRE(sub_complete_future.is_ready());
2!
3837
        sub_set.refresh();
2✔
3838
        REQUIRE(sub_set.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3839

3840
        sub_complete_future = sub_set.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
3841
        problem_realm->sync_session()->resume();
2✔
3842
        sub_complete_future.get();
2✔
3843
        wait_for_advance(*problem_realm);
2✔
3844

3845
        sub_set.refresh();
2✔
3846
        REQUIRE(sub_set.state() == sync::SubscriptionSet::State::Complete);
2!
3847
        auto table = problem_realm->read_group().get_table("class_TopLevel");
2✔
3848
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3849
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3850
    }
2✔
3851
#endif
6✔
3852
    SECTION("error/suspend between bootstrap and mark") {
6✔
3853
        SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3854
        triggered_config.sync_config->on_sync_client_event_hook =
2✔
3855
            [&bizz_obj_id, &bar_obj_id](std::weak_ptr<SyncSession> weak_sess, const SyncClientHookData& data) {
34✔
3856
                auto sess = weak_sess.lock();
34✔
3857
                if (!sess || data.event != SyncClientHookEvent::BootstrapProcessed || data.query_version != 1) {
34✔
3858
                    return SyncClientHookAction::NoAction;
32✔
3859
                }
32✔
3860

3861
                auto latest_subs = sess->get_flx_subscription_store()->get_latest();
2✔
3862
                REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3863
                REQUIRE(data.num_changesets == 1);
2!
3864
                auto db = SyncSession::OnlyForTesting::get_db(*sess);
2✔
3865
                auto read_tr = db->start_read();
2✔
3866
                auto table = read_tr->get_table("class_TopLevel");
2✔
3867
                REQUIRE(table->find_primary_key(bar_obj_id));
2!
3868
                REQUIRE_FALSE(table->find_primary_key(bizz_obj_id));
2!
3869

3870
                return SyncClientHookAction::TriggerReconnect;
2✔
3871
            };
2✔
3872
        auto problem_realm = Realm::get_shared_realm(triggered_config);
2✔
3873

3874
        // Setup the problem realm by waiting for it to be fully synchronized with an empty query, so the router
3875
        // on the server should have no new history entries, and then pause the router so it doesn't get any of
3876
        // the changes we're about to create.
3877
        wait_for_upload(*problem_realm);
2✔
3878
        wait_for_download(*problem_realm);
2✔
3879

3880
        nlohmann::json command_request = {
2✔
3881
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
3882
        };
2✔
3883
        auto resp_body =
2✔
3884
            SyncSession::OnlyForTesting::send_test_command(*problem_realm->sync_session(), command_request.dump())
2✔
3885
                .get();
2✔
3886
        REQUIRE(resp_body == "{}");
2!
3887

3888
        // Put some data into the server, this will be the data that will be in the broker cache.
3889
        setup_and_poison_cache();
2✔
3890

3891
        // Setup queries on the problem realm to bootstrap from the cached object. Bootstrapping will also resume
3892
        // the router, so all we need to do is wait for the subscription set to be complete and notifications to be
3893
        // processed.
3894
        auto sub_set = setup_subs(problem_realm);
2✔
3895
        auto sub_complete_future = sub_set.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
3896

3897
        sub_complete_future.get();
2✔
3898
        wait_for_advance(*problem_realm);
2✔
3899

3900
        sub_set.refresh();
2✔
3901
        REQUIRE(sub_set.state() == sync::SubscriptionSet::State::Complete);
2!
3902
        auto table = problem_realm->read_group().get_table("class_TopLevel");
2✔
3903
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3904
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3905
    }
2✔
3906
}
6✔
3907

3908
TEST_CASE("flx: convert flx sync realm to bundled realm", "[app][flx][baas]") {
12✔
3909
    static auto foo_obj_id = ObjectId::gen();
12✔
3910
    static auto bar_obj_id = ObjectId::gen();
12✔
3911
    static auto bizz_obj_id = ObjectId::gen();
12✔
3912
    static std::optional<FLXSyncTestHarness> harness;
12✔
3913
    if (!harness) {
12✔
3914
        harness.emplace("bundled_flx_realms");
2✔
3915
        harness->load_initial_data([&](SharedRealm realm) {
2✔
3916
            CppContext c(realm);
2✔
3917
            Object::create(c, realm, "TopLevel",
2✔
3918
                           std::any(AnyDict{{"_id", foo_obj_id},
2✔
3919
                                            {"queryable_str_field", "foo"s},
2✔
3920
                                            {"queryable_int_field", static_cast<int64_t>(5)},
2✔
3921
                                            {"non_queryable_field", "non queryable 1"s}}));
2✔
3922
            Object::create(c, realm, "TopLevel",
2✔
3923
                           std::any(AnyDict{{"_id", bar_obj_id},
2✔
3924
                                            {"queryable_str_field", "bar"s},
2✔
3925
                                            {"queryable_int_field", static_cast<int64_t>(10)},
2✔
3926
                                            {"non_queryable_field", "non queryable 2"s}}));
2✔
3927
        });
2✔
3928
    }
2✔
3929

3930
    SECTION("flx to flx (should succeed)") {
12✔
3931
        create_user_and_log_in(harness->app());
2✔
3932
        SyncTestFile target_config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
3933
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3934
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
3935
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3936
            mut_subs.insert_or_assign(Query(table).greater(table->get_column_key("queryable_int_field"), 5));
2✔
3937
            auto subs = std::move(mut_subs).commit();
2✔
3938

3939
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
3940
            wait_for_advance(*realm);
2✔
3941

3942
            realm->convert(target_config);
2✔
3943
        });
2✔
3944

3945
        auto target_realm = Realm::get_shared_realm(target_config);
2✔
3946

3947
        target_realm->begin_transaction();
2✔
3948
        CppContext c(target_realm);
2✔
3949
        Object::create(c, target_realm, "TopLevel",
2✔
3950
                       std::any(AnyDict{{"_id", bizz_obj_id},
2✔
3951
                                        {"queryable_str_field", "bizz"s},
2✔
3952
                                        {"queryable_int_field", static_cast<int64_t>(15)},
2✔
3953
                                        {"non_queryable_field", "non queryable 3"s}}));
2✔
3954
        target_realm->commit_transaction();
2✔
3955

3956
        wait_for_upload(*target_realm);
2✔
3957
        wait_for_download(*target_realm);
2✔
3958

3959
        auto latest_subs = target_realm->get_active_subscription_set();
2✔
3960
        auto table = target_realm->read_group().get_table("class_TopLevel");
2✔
3961
        REQUIRE(latest_subs.size() == 1);
2!
3962
        REQUIRE(latest_subs.at(0).object_class_name == "TopLevel");
2!
3963
        REQUIRE(latest_subs.at(0).query_string ==
2!
3964
                Query(table).greater(table->get_column_key("queryable_int_field"), 5).get_description());
2✔
3965

3966
        REQUIRE(table->size() == 2);
2!
3967
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3968
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3969
        REQUIRE_FALSE(table->find_primary_key(foo_obj_id));
2!
3970
    }
2✔
3971

3972
    SECTION("flx to local (should succeed)") {
12✔
3973
        TestFile target_config;
2✔
3974

3975
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3976
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
3977
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3978
            mut_subs.insert_or_assign(Query(table).greater(table->get_column_key("queryable_int_field"), 5));
2✔
3979
            auto subs = std::move(mut_subs).commit();
2✔
3980

3981
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
3982
            wait_for_advance(*realm);
2✔
3983

3984
            target_config.schema = realm->schema();
2✔
3985
            target_config.schema_version = realm->schema_version();
2✔
3986
            realm->convert(target_config);
2✔
3987
        });
2✔
3988

3989
        auto target_realm = Realm::get_shared_realm(target_config);
2✔
3990
        REQUIRE_THROWS(target_realm->get_active_subscription_set());
2✔
3991

3992
        auto table = target_realm->read_group().get_table("class_TopLevel");
2✔
3993
        REQUIRE(table->size() == 2);
2!
3994
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3995
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3996
        REQUIRE_FALSE(table->find_primary_key(foo_obj_id));
2!
3997
    }
2✔
3998

3999
    SECTION("flx to pbs (should fail to convert)") {
12✔
4000
        create_user_and_log_in(harness->app());
2✔
4001
        SyncTestFile target_config(harness->app()->current_user(), "12345"s, harness->schema());
2✔
4002
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
4003
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
4004
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4005
            mut_subs.insert_or_assign(Query(table).greater(table->get_column_key("queryable_int_field"), 5));
2✔
4006
            auto subs = std::move(mut_subs).commit();
2✔
4007

4008
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
4009
            wait_for_advance(*realm);
2✔
4010

4011
            REQUIRE_THROWS(realm->convert(target_config));
2✔
4012
        });
2✔
4013
    }
2✔
4014

4015
    SECTION("pbs to flx (should fail to convert)") {
12✔
4016
        create_user_and_log_in(harness->app());
2✔
4017
        SyncTestFile target_config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
4018

4019
        auto pbs_app_config = minimal_app_config("pbs_to_flx_convert", harness->schema());
2✔
4020

4021
        TestAppSession pbs_app_session(create_app(pbs_app_config));
2✔
4022
        SyncTestFile source_config(pbs_app_session.app()->current_user(), "54321"s, pbs_app_config.schema);
2✔
4023
        auto realm = Realm::get_shared_realm(source_config);
2✔
4024

4025
        realm->begin_transaction();
2✔
4026
        CppContext c(realm);
2✔
4027
        Object::create(c, realm, "TopLevel",
2✔
4028
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
4029
                                        {"queryable_str_field", "foo"s},
2✔
4030
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4031
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
4032
        realm->commit_transaction();
2✔
4033

4034
        REQUIRE_THROWS(realm->convert(target_config));
2✔
4035
    }
2✔
4036

4037
    SECTION("local to flx (should fail to convert)") {
12✔
4038
        TestFile source_config;
2✔
4039
        source_config.schema = harness->schema();
2✔
4040
        source_config.schema_version = 1;
2✔
4041

4042
        auto realm = Realm::get_shared_realm(source_config);
2✔
4043
        auto foo_obj_id = ObjectId::gen();
2✔
4044

4045
        realm->begin_transaction();
2✔
4046
        CppContext c(realm);
2✔
4047
        Object::create(c, realm, "TopLevel",
2✔
4048
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
4049
                                        {"queryable_str_field", "foo"s},
2✔
4050
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4051
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
4052
        realm->commit_transaction();
2✔
4053

4054
        create_user_and_log_in(harness->app());
2✔
4055
        SyncTestFile target_config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
4056

4057
        REQUIRE_THROWS(realm->convert(target_config));
2✔
4058
    }
2✔
4059

4060
    // Add new sections before this
4061
    SECTION("teardown") {
12✔
4062
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
4063
        harness.reset();
2✔
4064
    }
2✔
4065
}
12✔
4066

4067
TEST_CASE("flx: compensating write errors get re-sent across sessions", "[sync][flx][compensating write][baas]") {
2✔
4068
    AppCreateConfig::ServiceRole role;
2✔
4069
    role.name = "compensating_write_perms";
2✔
4070

4071
    AppCreateConfig::ServiceRoleDocumentFilters doc_filters;
2✔
4072
    doc_filters.read = true;
2✔
4073
    doc_filters.write =
2✔
4074
        nlohmann::json{{"queryable_str_field", nlohmann::json{{"$in", nlohmann::json::array({"foo", "bar"})}}}};
2✔
4075
    role.document_filters = doc_filters;
2✔
4076

4077
    role.insert_filter = true;
2✔
4078
    role.delete_filter = true;
2✔
4079
    role.read = true;
2✔
4080
    role.write = true;
2✔
4081
    FLXSyncTestHarness::ServerSchema server_schema{
2✔
4082
        g_simple_embedded_obj_schema, {"queryable_str_field", "queryable_int_field"}, {role}};
2✔
4083
    FLXSyncTestHarness::Config harness_config("flx_bad_query", server_schema);
2✔
4084
    harness_config.reconnect_mode = ReconnectMode::testing;
2✔
4085
    FLXSyncTestHarness harness(std::move(harness_config));
2✔
4086

4087
    auto test_obj_id_1 = ObjectId::gen();
2✔
4088
    auto test_obj_id_2 = ObjectId::gen();
2✔
4089

4090
    create_user_and_log_in(harness.app());
2✔
4091
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4092

4093
    {
2✔
4094
        auto error_received_pf = util::make_promise_future<void>();
2✔
4095
        config.sync_config->on_sync_client_event_hook =
2✔
4096
            [promise = util::CopyablePromiseHolder(std::move(error_received_pf.promise))](
2✔
4097
                std::weak_ptr<SyncSession> weak_session, const SyncClientHookData& data) mutable {
30✔
4098
                if (data.event != SyncClientHookEvent::ErrorMessageReceived) {
30✔
4099
                    return SyncClientHookAction::NoAction;
28✔
4100
                }
28✔
4101
                auto session = weak_session.lock();
2✔
4102
                REQUIRE(session);
2!
4103

4104
                auto error_code = sync::ProtocolError(data.error_info->raw_error_code);
2✔
4105

4106
                if (error_code == sync::ProtocolError::initial_sync_not_completed) {
2✔
4107
                    return SyncClientHookAction::NoAction;
×
UNCOV
4108
                }
×
4109

4110
                REQUIRE(error_code == sync::ProtocolError::compensating_write);
2!
4111
                REQUIRE_FALSE(data.error_info->compensating_writes.empty());
2!
4112
                promise.get_promise().emplace_value();
2✔
4113

4114
                return SyncClientHookAction::TriggerReconnect;
2✔
4115
            };
2✔
4116

4117
        auto realm = Realm::get_shared_realm(config);
2✔
4118
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4119
        auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
4120
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4121
        new_query.insert_or_assign(Query(table).equal(queryable_str_field, "bizz"));
2✔
4122
        std::move(new_query).commit();
2✔
4123

4124
        wait_for_upload(*realm);
2✔
4125
        wait_for_download(*realm);
2✔
4126

4127
        CppContext c(realm);
2✔
4128
        realm->begin_transaction();
2✔
4129
        Object::create(c, realm, "TopLevel",
2✔
4130
                       util::Any(AnyDict{
2✔
4131
                           {"_id", test_obj_id_1},
2✔
4132
                           {"queryable_str_field", std::string{"foo"}},
2✔
4133
                       }));
2✔
4134
        realm->commit_transaction();
2✔
4135

4136
        realm->begin_transaction();
2✔
4137
        Object::create(c, realm, "TopLevel",
2✔
4138
                       util::Any(AnyDict{
2✔
4139
                           {"_id", test_obj_id_2},
2✔
4140
                           {"queryable_str_field", std::string{"baz"}},
2✔
4141
                       }));
2✔
4142
        realm->commit_transaction();
2✔
4143

4144
        error_received_pf.future.get();
2✔
4145
        realm->sync_session()->shutdown_and_wait();
2✔
4146
        config.sync_config->on_sync_client_event_hook = {};
2✔
4147
    }
2✔
4148

4149
    _impl::RealmCoordinator::clear_all_caches();
2✔
4150

4151
    std::mutex errors_mutex;
2✔
4152
    std::condition_variable new_compensating_write;
2✔
4153
    std::vector<std::pair<ObjectId, sync::version_type>> error_to_download_version;
2✔
4154
    std::vector<sync::CompensatingWriteErrorInfo> compensating_writes;
2✔
4155
    sync::version_type download_version;
2✔
4156

4157
    config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_session,
2✔
4158
                                                        const SyncClientHookData& data) mutable {
16✔
4159
        auto session = weak_session.lock();
16✔
4160
        if (!session) {
16✔
4161
            return SyncClientHookAction::NoAction;
×
UNCOV
4162
        }
×
4163

4164
        if (data.event != SyncClientHookEvent::ErrorMessageReceived) {
16✔
4165
            if (data.event == SyncClientHookEvent::DownloadMessageReceived) {
12✔
4166
                download_version = data.progress.download.server_version;
4✔
4167
            }
4✔
4168

4169
            return SyncClientHookAction::NoAction;
12✔
4170
        }
12✔
4171

4172
        auto error_code = sync::ProtocolError(data.error_info->raw_error_code);
4✔
4173
        REQUIRE(error_code == sync::ProtocolError::compensating_write);
4!
4174
        REQUIRE(!data.error_info->compensating_writes.empty());
4!
4175
        std::lock_guard<std::mutex> lk(errors_mutex);
4✔
4176
        for (const auto& compensating_write : data.error_info->compensating_writes) {
4✔
4177
            error_to_download_version.emplace_back(compensating_write.primary_key.get_object_id(),
4✔
4178
                                                   *data.error_info->compensating_write_server_version);
4✔
4179
        }
4✔
4180

4181
        return SyncClientHookAction::NoAction;
4✔
4182
    };
4✔
4183

4184
    config.sync_config->error_handler = [&](std::shared_ptr<SyncSession>, SyncError error) {
4✔
4185
        std::unique_lock<std::mutex> lk(errors_mutex);
4✔
4186
        REQUIRE(error.status == ErrorCodes::SyncCompensatingWrite);
4!
4187
        for (const auto& compensating_write : error.compensating_writes_info) {
4✔
4188
            auto tracked_error = std::find_if(error_to_download_version.begin(), error_to_download_version.end(),
4✔
4189
                                              [&](const auto& pair) {
6✔
4190
                                                  return pair.first == compensating_write.primary_key.get_object_id();
6✔
4191
                                              });
6✔
4192
            REQUIRE(tracked_error != error_to_download_version.end());
4!
4193
            CHECK(tracked_error->second <= download_version);
4!
4194
            compensating_writes.push_back(compensating_write);
4✔
4195
        }
4✔
4196
        new_compensating_write.notify_one();
4✔
4197
    };
4✔
4198

4199
    auto realm = Realm::get_shared_realm(config);
2✔
4200

4201
    wait_for_upload(*realm);
2✔
4202
    wait_for_download(*realm);
2✔
4203

4204
    std::unique_lock<std::mutex> lk(errors_mutex);
2✔
4205
    new_compensating_write.wait_for(lk, std::chrono::seconds(30), [&] {
2✔
4206
        return compensating_writes.size() == 2;
2✔
4207
    });
2✔
4208

4209
    REQUIRE(compensating_writes.size() == 2);
2!
4210
    auto& write_info = compensating_writes[0];
2✔
4211
    CHECK(write_info.primary_key.is_type(type_ObjectId));
2!
4212
    CHECK(write_info.primary_key.get_object_id() == test_obj_id_1);
2!
4213
    CHECK(write_info.object_name == "TopLevel");
2!
4214
    CHECK_THAT(write_info.reason, Catch::Matchers::ContainsSubstring("object is outside of the current query view"));
2✔
4215

4216
    write_info = compensating_writes[1];
2✔
4217
    REQUIRE(write_info.primary_key.is_type(type_ObjectId));
2!
4218
    REQUIRE(write_info.primary_key.get_object_id() == test_obj_id_2);
2!
4219
    REQUIRE(write_info.object_name == "TopLevel");
2!
4220
    REQUIRE(write_info.reason ==
2!
4221
            util::format("write to ObjectID(\"%1\") in table \"TopLevel\" not allowed", test_obj_id_2));
2✔
4222
    auto top_level_table = realm->read_group().get_table("class_TopLevel");
2✔
4223
    REQUIRE(top_level_table->is_empty());
2!
4224
}
2✔
4225

4226
TEST_CASE("flx: bootstrap changesets are applied continuously", "[sync][flx][bootstrap][baas]") {
2✔
4227
    FLXSyncTestHarness harness("flx_bootstrap_ordering", {g_large_array_schema, {"queryable_int_field"}});
2✔
4228
    fill_large_array_schema(harness);
2✔
4229

4230
    std::unique_ptr<std::thread> th;
2✔
4231
    sync::version_type user_commit_version = UINT_FAST64_MAX;
2✔
4232
    sync::version_type bootstrap_version = UINT_FAST64_MAX;
2✔
4233
    SharedRealm realm;
2✔
4234
    std::condition_variable cv;
2✔
4235
    std::mutex mutex;
2✔
4236
    bool allow_to_commit = false;
2✔
4237

4238
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4239
    auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
4240
    auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
4241
    config.sync_config->on_sync_client_event_hook =
2✔
4242
        [promise = std::move(shared_promise), &th, &realm, &user_commit_version, &bootstrap_version, &cv, &mutex,
2✔
4243
         &allow_to_commit](std::weak_ptr<SyncSession> weak_session, const SyncClientHookData& data) {
68✔
4244
            if (data.query_version == 0) {
68✔
4245
                return SyncClientHookAction::NoAction;
18✔
4246
            }
18✔
4247
            if (data.event != SyncClientHookEvent::DownloadMessageIntegrated) {
50✔
4248
                return SyncClientHookAction::NoAction;
38✔
4249
            }
38✔
4250
            auto session = weak_session.lock();
12✔
4251
            if (!session) {
12✔
4252
                return SyncClientHookAction::NoAction;
×
UNCOV
4253
            }
×
4254
            if (data.batch_state != sync::DownloadBatchState::MoreToCome) {
12✔
4255
                // Read version after bootstrap is done.
4256
                auto db = TestHelper::get_db(realm);
2✔
4257
                ReadTransaction rt(db);
2✔
4258
                bootstrap_version = rt.get_version();
2✔
4259
                {
2✔
4260
                    std::lock_guard<std::mutex> lock(mutex);
2✔
4261
                    allow_to_commit = true;
2✔
4262
                }
2✔
4263
                cv.notify_one();
2✔
4264
                session->force_close();
2✔
4265
                promise->emplace_value();
2✔
4266
                return SyncClientHookAction::NoAction;
2✔
4267
            }
2✔
4268

4269
            if (th) {
10✔
4270
                return SyncClientHookAction::NoAction;
8✔
4271
            }
8✔
4272

4273
            auto func = [&] {
2✔
4274
                // Attempt to commit a local change after the first bootstrap batch was committed.
4275
                auto db = TestHelper::get_db(realm);
2✔
4276
                WriteTransaction wt(db);
2✔
4277
                TableRef table = wt.get_table("class_TopLevel");
2✔
4278
                table->create_object_with_primary_key(ObjectId::gen());
2✔
4279
                {
2✔
4280
                    std::unique_lock<std::mutex> lock(mutex);
2✔
4281
                    // Wait to commit until we read the final bootstrap version.
4282
                    cv.wait(lock, [&] {
2✔
4283
                        return allow_to_commit;
2✔
4284
                    });
2✔
4285
                }
2✔
4286
                user_commit_version = wt.commit();
2✔
4287
            };
2✔
4288
            th = std::make_unique<std::thread>(std::move(func));
2✔
4289

4290
            return SyncClientHookAction::NoAction;
2✔
4291
        };
10✔
4292

4293
    realm = Realm::get_shared_realm(config);
2✔
4294
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
4295
    Query query(table);
2✔
4296
    {
2✔
4297
        auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4298
        new_subs.insert_or_assign(query);
2✔
4299
        new_subs.commit();
2✔
4300
    }
2✔
4301
    interrupted.get();
2✔
4302
    th->join();
2✔
4303

4304
    // The user commit is the last one.
4305
    CHECK(user_commit_version == bootstrap_version + 1);
2!
4306
}
2✔
4307

4308
TEST_CASE("flx: open realm + register subscription callback while bootstrapping",
4309
          "[sync][flx][bootstrap][async open][baas]") {
14✔
4310
    FLXSyncTestHarness harness("flx_bootstrap_and_subscribe");
14✔
4311
    auto foo_obj_id = ObjectId::gen();
14✔
4312
    int64_t foo_obj_queryable_int = 5;
14✔
4313
    harness.load_initial_data([&](SharedRealm realm) {
14✔
4314
        CppContext c(realm);
14✔
4315
        Object::create(c, realm, "TopLevel",
14✔
4316
                       std::any(AnyDict{{"_id", foo_obj_id},
14✔
4317
                                        {"queryable_str_field", "foo"s},
14✔
4318
                                        {"queryable_int_field", foo_obj_queryable_int},
14✔
4319
                                        {"non_queryable_field", "created as initial data seed"s}}));
14✔
4320
    });
14✔
4321
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
14✔
4322

4323
    std::atomic<bool> subscription_invoked = false;
14✔
4324
    auto subscription_pf = util::make_promise_future<bool>();
14✔
4325
    // create a subscription to commit when realm is open for the first time or asked to rerun on open
4326
    auto init_subscription_callback_with_promise =
14✔
4327
        [&, promise_holder = util::CopyablePromiseHolder(std::move(subscription_pf.promise))](
14✔
4328
            std::shared_ptr<Realm> realm) mutable {
14✔
4329
            REQUIRE(realm);
8!
4330
            auto table = realm->read_group().get_table("class_TopLevel");
8✔
4331
            Query query(table);
8✔
4332
            auto subscription = realm->get_latest_subscription_set();
8✔
4333
            auto mutable_subscription = subscription.make_mutable_copy();
8✔
4334
            mutable_subscription.insert_or_assign(query);
8✔
4335
            auto promise = promise_holder.get_promise();
8✔
4336
            mutable_subscription.commit();
8✔
4337
            subscription_invoked = true;
8✔
4338
            promise.emplace_value(true);
8✔
4339
        };
8✔
4340
    // verify that the subscription has changed the database
4341
    auto verify_subscription = [](SharedRealm realm) {
14✔
4342
        REQUIRE(realm);
12!
4343
        auto table_ref = realm->read_group().get_table("class_TopLevel");
12✔
4344
        REQUIRE(table_ref);
12!
4345
        REQUIRE(table_ref->get_column_count() == 4);
12!
4346
        REQUIRE(table_ref->get_column_key("_id"));
12!
4347
        REQUIRE(table_ref->get_column_key("queryable_str_field"));
12!
4348
        REQUIRE(table_ref->get_column_key("queryable_int_field"));
12!
4349
        REQUIRE(table_ref->get_column_key("non_queryable_field"));
12!
4350
        REQUIRE(table_ref->size() == 1);
12!
4351
        auto str_col = table_ref->get_column_key("queryable_str_field");
12✔
4352
        REQUIRE(table_ref->get_object(0).get<String>(str_col) == "foo");
12!
4353
        return true;
12✔
4354
    };
12✔
4355

4356
    SECTION("Sync open") {
14✔
4357
        // sync open with subscription callback. Subscription will be run, since this is the first time that realm is
4358
        // opened
4359
        subscription_invoked = false;
2✔
4360
        config.sync_config->subscription_initializer = init_subscription_callback_with_promise;
2✔
4361
        auto realm = Realm::get_shared_realm(config);
2✔
4362
        REQUIRE(subscription_pf.future.get());
2!
4363
        auto sb = realm->get_latest_subscription_set();
2✔
4364
        auto future = sb.get_state_change_notification(realm::sync::SubscriptionSet::State::Complete);
2✔
4365
        auto state = future.get();
2✔
4366
        REQUIRE(state == realm::sync::SubscriptionSet::State::Complete);
2!
4367
        realm->refresh(); // refresh is needed otherwise table_ref->size() would be 0
2✔
4368
        REQUIRE(verify_subscription(realm));
2!
4369
    }
2✔
4370

4371
    SECTION("Sync Open + Async Open") {
14✔
4372
        {
2✔
4373
            subscription_invoked = false;
2✔
4374
            config.sync_config->subscription_initializer = init_subscription_callback_with_promise;
2✔
4375
            auto realm = Realm::get_shared_realm(config);
2✔
4376
            REQUIRE(subscription_pf.future.get());
2!
4377
            auto sb = realm->get_latest_subscription_set();
2✔
4378
            auto future = sb.get_state_change_notification(realm::sync::SubscriptionSet::State::Complete);
2✔
4379
            auto state = future.get();
2✔
4380
            REQUIRE(state == realm::sync::SubscriptionSet::State::Complete);
2!
4381
            realm->refresh(); // refresh is needed otherwise table_ref->size() would be 0
2✔
4382
            REQUIRE(verify_subscription(realm));
2!
4383
        }
2✔
4384
        {
2✔
4385
            auto subscription_pf_async = util::make_promise_future<bool>();
2✔
4386
            auto init_subscription_asyc_callback =
2✔
4387
                [promise_holder_async = util::CopyablePromiseHolder(std::move(subscription_pf_async.promise))](
2✔
4388
                    std::shared_ptr<Realm> realm) mutable {
2✔
4389
                    REQUIRE(realm);
2!
4390
                    auto table = realm->read_group().get_table("class_TopLevel");
2✔
4391
                    Query query(table);
2✔
4392
                    auto subscription = realm->get_latest_subscription_set();
2✔
4393
                    auto mutable_subscription = subscription.make_mutable_copy();
2✔
4394
                    mutable_subscription.insert_or_assign(query);
2✔
4395
                    auto promise = promise_holder_async.get_promise();
2✔
4396
                    mutable_subscription.commit();
2✔
4397
                    promise.emplace_value(true);
2✔
4398
                };
2✔
4399
            auto open_realm_pf = util::make_promise_future<bool>();
2✔
4400
            auto open_realm_completed_callback = [&](ThreadSafeReference ref, std::exception_ptr err) mutable {
2✔
4401
                bool result = false;
2✔
4402
                if (!err) {
2✔
4403
                    result =
2✔
4404
                        verify_subscription(Realm::get_shared_realm(std::move(ref), util::Scheduler::make_dummy()));
2✔
4405
                }
2✔
4406
                open_realm_pf.promise.emplace_value(result);
2✔
4407
            };
2✔
4408

4409
            config.sync_config->subscription_initializer = init_subscription_asyc_callback;
2✔
4410
            config.sync_config->rerun_init_subscription_on_open = true;
2✔
4411
            auto async_open = Realm::get_synchronized_realm(config);
2✔
4412
            async_open->start(open_realm_completed_callback);
2✔
4413
            REQUIRE(open_realm_pf.future.get());
2!
4414
            REQUIRE(subscription_pf_async.future.get());
2!
4415
            config.sync_config->rerun_init_subscription_on_open = false;
2✔
4416
            auto realm = Realm::get_shared_realm(config);
2✔
4417
            REQUIRE(realm->get_latest_subscription_set().version() == 2);
2!
4418
            REQUIRE(realm->get_active_subscription_set().version() == 2);
2!
4419
        }
2✔
4420
    }
2✔
4421

4422
    SECTION("Async open") {
14✔
4423
        SECTION("Initial async open with no rerun on open set") {
10✔
4424
            // subscription will be run since this is the first time we are opening the realm file.
4425
            auto open_realm_pf = util::make_promise_future<bool>();
4✔
4426
            auto open_realm_completed_callback = [&](ThreadSafeReference ref, std::exception_ptr err) mutable {
4✔
4427
                bool result = false;
4✔
4428
                if (!err) {
4✔
4429
                    result =
4✔
4430
                        verify_subscription(Realm::get_shared_realm(std::move(ref), util::Scheduler::make_dummy()));
4✔
4431
                }
4✔
4432
                open_realm_pf.promise.emplace_value(result);
4✔
4433
            };
4✔
4434

4435
            config.sync_config->subscription_initializer = init_subscription_callback_with_promise;
4✔
4436
            auto async_open = Realm::get_synchronized_realm(config);
4✔
4437
            async_open->start(open_realm_completed_callback);
4✔
4438
            REQUIRE(open_realm_pf.future.get());
4!
4439
            REQUIRE(subscription_pf.future.get());
4!
4440

4441
            SECTION("rerun on open = false. Subscription not run") {
4✔
4442
                subscription_invoked = false;
2✔
4443
                auto async_open = Realm::get_synchronized_realm(config);
2✔
4444
                auto open_realm_pf = util::make_promise_future<bool>();
2✔
4445
                auto open_realm_completed_callback = [&](ThreadSafeReference, std::exception_ptr e) mutable {
2✔
4446
                    // no need to verify if the subscription has changed the db, since it has not run as we test
4447
                    // below
4448
                    open_realm_pf.promise.emplace_value(!e);
2✔
4449
                };
2✔
4450
                async_open->start(open_realm_completed_callback);
2✔
4451
                REQUIRE(open_realm_pf.future.get());
2!
4452
                REQUIRE_FALSE(subscription_invoked.load());
2!
4453
            }
2✔
4454

4455
            SECTION("rerun on open = true. Subscription not run cause realm already opened once") {
4✔
4456
                subscription_invoked = false;
2✔
4457
                auto realm = Realm::get_shared_realm(config);
2✔
4458
                auto init_subscription = [&subscription_invoked](std::shared_ptr<Realm> realm) mutable {
2✔
4459
                    REQUIRE(realm);
×
4460
                    auto table = realm->read_group().get_table("class_TopLevel");
×
4461
                    Query query(table);
×
4462
                    auto subscription = realm->get_latest_subscription_set();
×
4463
                    auto mutable_subscription = subscription.make_mutable_copy();
×
4464
                    mutable_subscription.insert_or_assign(query);
×
4465
                    mutable_subscription.commit();
×
4466
                    subscription_invoked.store(true);
×
UNCOV
4467
                };
×
4468
                config.sync_config->rerun_init_subscription_on_open = true;
2✔
4469
                config.sync_config->subscription_initializer = init_subscription;
2✔
4470
                auto async_open = Realm::get_synchronized_realm(config);
2✔
4471
                auto open_realm_pf = util::make_promise_future<bool>();
2✔
4472
                auto open_realm_completed_callback = [&](ThreadSafeReference, std::exception_ptr e) mutable {
2✔
4473
                    // no need to verify if the subscription has changed the db, since it has not run as we test
4474
                    // below
4475
                    open_realm_pf.promise.emplace_value(!e);
2✔
4476
                };
2✔
4477
                async_open->start(open_realm_completed_callback);
2✔
4478
                REQUIRE(open_realm_pf.future.get());
2!
4479
                REQUIRE_FALSE(subscription_invoked.load());
2!
4480
                REQUIRE(realm->get_latest_subscription_set().version() == 1);
2!
4481
                REQUIRE(realm->get_active_subscription_set().version() == 1);
2!
4482
            }
2✔
4483
        }
4✔
4484

4485
        SECTION("rerun on open set for multiple async open tasks (subscription runs only once)") {
10✔
4486
            auto init_subscription = [](std::shared_ptr<Realm> realm) mutable {
8✔
4487
                REQUIRE(realm);
8!
4488
                auto table = realm->read_group().get_table("class_TopLevel");
8✔
4489
                Query query(table);
8✔
4490
                auto subscription = realm->get_latest_subscription_set();
8✔
4491
                auto mutable_subscription = subscription.make_mutable_copy();
8✔
4492
                mutable_subscription.insert_or_assign(query);
8✔
4493
                mutable_subscription.commit();
8✔
4494
            };
8✔
4495

4496
            auto open_task1_pf = util::make_promise_future<SharedRealm>();
4✔
4497
            auto open_task2_pf = util::make_promise_future<SharedRealm>();
4✔
4498
            auto open_callback1 = [&](ThreadSafeReference ref, std::exception_ptr err) mutable {
4✔
4499
                REQUIRE_FALSE(err);
4!
4500
                open_task1_pf.promise.emplace_value(
4✔
4501
                    Realm::get_shared_realm(std::move(ref), util::Scheduler::make_dummy()));
4✔
4502
            };
4✔
4503
            auto open_callback2 = [&](ThreadSafeReference ref, std::exception_ptr err) mutable {
4✔
4504
                REQUIRE_FALSE(err);
4!
4505
                open_task2_pf.promise.emplace_value(
4✔
4506
                    Realm::get_shared_realm(std::move(ref), util::Scheduler::make_dummy()));
4✔
4507
            };
4✔
4508

4509
            config.sync_config->rerun_init_subscription_on_open = true;
4✔
4510
            config.sync_config->subscription_initializer = init_subscription;
4✔
4511

4512
            SECTION("Realm was already created, but we want to rerun on first open using multiple tasks") {
4✔
4513
                {
2✔
4514
                    subscription_invoked = false;
2✔
4515
                    auto realm = Realm::get_shared_realm(config);
2✔
4516
                    auto sb = realm->get_latest_subscription_set();
2✔
4517
                    auto future = sb.get_state_change_notification(realm::sync::SubscriptionSet::State::Complete);
2✔
4518
                    auto state = future.get();
2✔
4519
                    REQUIRE(state == realm::sync::SubscriptionSet::State::Complete);
2!
4520
                    realm->refresh(); // refresh is needed otherwise table_ref->size() would be 0
2✔
4521
                    REQUIRE(verify_subscription(realm));
2!
4522
                    REQUIRE(realm->get_latest_subscription_set().version() == 1);
2!
4523
                    REQUIRE(realm->get_active_subscription_set().version() == 1);
2!
4524
                }
2✔
4525

4526
                auto async_open_task1 = Realm::get_synchronized_realm(config);
2✔
4527
                auto async_open_task2 = Realm::get_synchronized_realm(config);
2✔
4528
                async_open_task1->start(open_callback1);
2✔
4529
                async_open_task2->start(open_callback2);
2✔
4530

4531
                auto realm1 = open_task1_pf.future.get();
2✔
4532
                auto realm2 = open_task2_pf.future.get();
2✔
4533

4534
                const auto version_expected = 2;
2✔
4535
                auto r1_latest = realm1->get_latest_subscription_set().version();
2✔
4536
                auto r1_active = realm1->get_active_subscription_set().version();
2✔
4537
                REQUIRE(realm2->get_latest_subscription_set().version() == r1_latest);
2!
4538
                REQUIRE(realm2->get_active_subscription_set().version() == r1_active);
2!
4539
                REQUIRE(r1_latest == version_expected);
2!
4540
                REQUIRE(r1_active == version_expected);
2!
4541
            }
2✔
4542
            SECTION("First time realm is created but opened via open async. Both tasks could run the subscription") {
4✔
4543
                auto async_open_task1 = Realm::get_synchronized_realm(config);
2✔
4544
                auto async_open_task2 = Realm::get_synchronized_realm(config);
2✔
4545
                async_open_task1->start(open_callback1);
2✔
4546
                async_open_task2->start(open_callback2);
2✔
4547
                auto realm1 = open_task1_pf.future.get();
2✔
4548
                auto realm2 = open_task2_pf.future.get();
2✔
4549

4550
                auto r1_latest = realm1->get_latest_subscription_set().version();
2✔
4551
                auto r1_active = realm1->get_active_subscription_set().version();
2✔
4552
                REQUIRE(realm2->get_latest_subscription_set().version() == r1_latest);
2!
4553
                REQUIRE(realm2->get_active_subscription_set().version() == r1_active);
2!
4554
                // the callback may be run twice, if task1 is the first task to open realm
4555
                // but it is scheduled after tasks2, which have opened realm later but
4556
                // by the time it runs, subscription version is equal to 0 (realm creation).
4557
                // This can only happen the first time that realm is created. All the other times
4558
                // the init_sb callback is guaranteed to run once.
4559
                REQUIRE(r1_latest >= 1);
2!
4560
                REQUIRE(r1_latest <= 2);
2!
4561
                REQUIRE(r1_active >= 1);
2!
4562
                REQUIRE(r1_active <= 2);
2!
4563
            }
2✔
4564
        }
4✔
4565

4566
        SECTION("Wait to bootstrap all pending subscriptions even when subscription_initializer is not used") {
10✔
4567
            // Client 1
4568
            {
2✔
4569
                auto realm = Realm::get_shared_realm(config);
2✔
4570
                // Create subscription (version = 1) and bootstrap data.
4571
                subscribe_to_all_and_bootstrap(*realm);
2✔
4572
                realm->sync_session()->shutdown_and_wait();
2✔
4573

4574
                // Create a new subscription (version = 2) while the session is closed.
4575
                // The new subscription does not match the object bootstrapped at version 1.
4576
                auto mutable_subscription = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4577
                mutable_subscription.clear();
2✔
4578
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
4579
                auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
4580
                mutable_subscription.insert_or_assign(
2✔
4581
                    Query(table).not_equal(queryable_int_field, foo_obj_queryable_int));
2✔
4582
                mutable_subscription.commit();
2✔
4583

4584
                realm->close();
2✔
4585
            }
2✔
4586

4587
            REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(config.path));
2!
4588

4589
            // Client 2 uploads data matching Client 1's subscription at version 1
4590
            harness.load_initial_data([&](SharedRealm realm) {
2✔
4591
                CppContext c(realm);
2✔
4592
                Object::create(c, realm, "TopLevel",
2✔
4593
                               std::any(AnyDict{{"_id", ObjectId::gen()},
2✔
4594
                                                {"queryable_str_field", "bar"s},
2✔
4595
                                                {"queryable_int_field", 2 * foo_obj_queryable_int},
2✔
4596
                                                {"non_queryable_field", "some data"s}}));
2✔
4597
            });
2✔
4598

4599
            // Client 1 opens the realm asynchronously and expects the task to complete
4600
            // when the subscription at version 2 finishes bootstrapping.
4601
            auto realm = successfully_async_open_realm(config);
2✔
4602

4603
            // Check subscription at version 2 is marked Complete.
4604
            CHECK(realm->get_latest_subscription_set().version() == 2);
2!
4605
            CHECK(realm->get_active_subscription_set().version() == 2);
2!
4606
        }
2✔
4607
    }
10✔
4608
}
14✔
4609
TEST_CASE("flx sync: Client reset during async open", "[sync][flx][client reset][async open][baas]") {
2✔
4610
    FLXSyncTestHarness harness("flx_bootstrap_reset");
2✔
4611
    auto foo_obj_id = ObjectId::gen();
2✔
4612
    std::atomic<bool> subscription_invoked = false;
2✔
4613
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4614
        CppContext c(realm);
2✔
4615
        Object::create(c, realm, "TopLevel",
2✔
4616
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
4617
                                        {"queryable_str_field", "foo"s},
2✔
4618
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4619
                                        {"non_queryable_field", "created as initial data seed"s}}));
2✔
4620
    });
2✔
4621
    SyncTestFile realm_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4622

4623
    auto subscription_callback = [&](std::shared_ptr<Realm> realm) {
2✔
4624
        REQUIRE(realm);
2!
4625
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4626
        Query query(table);
2✔
4627
        auto subscription = realm->get_latest_subscription_set();
2✔
4628
        auto mutable_subscription = subscription.make_mutable_copy();
2✔
4629
        mutable_subscription.insert_or_assign(query);
2✔
4630
        subscription_invoked = true;
2✔
4631
        mutable_subscription.commit();
2✔
4632
    };
2✔
4633

4634
    realm_config.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
4635
    realm_config.sync_config->subscription_initializer = subscription_callback;
2✔
4636

4637
    bool client_reset_triggered = false;
2✔
4638
    realm_config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_sess,
2✔
4639
                                                              const SyncClientHookData& event_data) {
56✔
4640
        auto sess = weak_sess.lock();
56✔
4641
        if (!sess) {
56✔
4642
            return SyncClientHookAction::NoAction;
×
UNCOV
4643
        }
×
4644
        if (sess->path() != realm_config.path) {
56✔
4645
            return SyncClientHookAction::NoAction;
24✔
4646
        }
24✔
4647

4648
        if (event_data.event != SyncClientHookEvent::DownloadMessageReceived) {
32✔
4649
            return SyncClientHookAction::NoAction;
26✔
4650
        }
26✔
4651

4652
        if (client_reset_triggered) {
6✔
4653
            return SyncClientHookAction::NoAction;
4✔
4654
        }
4✔
4655

4656
        client_reset_triggered = true;
2✔
4657
        reset_utils::trigger_client_reset(harness.session().app_session(), *sess);
2✔
4658
        return SyncClientHookAction::SuspendWithRetryableError;
2✔
4659
    };
6✔
4660

4661
    auto before_callback_called = util::make_promise_future<void>();
2✔
4662
    realm_config.sync_config->notify_before_client_reset = [&](std::shared_ptr<Realm> realm) {
2✔
4663
        CHECK(realm->schema_version() == 0);
2!
4664
        before_callback_called.promise.emplace_value();
2✔
4665
    };
2✔
4666

4667
    auto after_callback_called = util::make_promise_future<void>();
2✔
4668
    realm_config.sync_config->notify_after_client_reset = [&](std::shared_ptr<Realm> realm, ThreadSafeReference,
2✔
4669
                                                              bool) {
2✔
4670
        CHECK(realm->schema_version() == 0);
2!
4671
        after_callback_called.promise.emplace_value();
2✔
4672
    };
2✔
4673

4674
    auto realm_task = Realm::get_synchronized_realm(realm_config);
2✔
4675
    auto realm_pf = util::make_promise_future<SharedRealm>();
2✔
4676
    realm_task->start([&](ThreadSafeReference ref, std::exception_ptr ex) {
2✔
4677
        auto& promise = realm_pf.promise;
2✔
4678
        try {
2✔
4679
            if (ex) {
2✔
4680
                std::rethrow_exception(ex);
×
UNCOV
4681
            }
×
4682
            promise.emplace_value(Realm::get_shared_realm(std::move(ref), util::Scheduler::make_dummy()));
2✔
4683
        }
2✔
4684
        catch (...) {
2✔
4685
            promise.set_error(exception_to_status());
×
UNCOV
4686
        }
×
4687
    });
2✔
4688
    auto realm = realm_pf.future.get();
2✔
4689
    before_callback_called.future.get();
2✔
4690
    after_callback_called.future.get();
2✔
4691
    REQUIRE(subscription_invoked.load());
2!
4692
}
2✔
4693

4694
// Test that resending pending subscription sets does not cause any inconsistencies in the progress cursors.
4695
TEST_CASE("flx sync: resend pending subscriptions when reconnecting", "[sync][flx][baas]") {
2✔
4696
    FLXSyncTestHarness harness("flx_pending_subscriptions", {g_large_array_schema, {"queryable_int_field"}});
2✔
4697

4698
    std::vector<ObjectId> obj_ids_at_end = fill_large_array_schema(harness);
2✔
4699
    SyncTestFile interrupted_realm_config(harness.app()->current_user(), harness.schema(),
2✔
4700
                                          SyncConfig::FLXSyncEnabled{});
2✔
4701

4702
    {
2✔
4703
        auto pf = util::make_promise_future<void>();
2✔
4704
        Realm::Config config = interrupted_realm_config;
2✔
4705
        config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
4706
        config.sync_config->on_sync_client_event_hook =
2✔
4707
            [promise = util::CopyablePromiseHolder(std::move(pf.promise))](std::weak_ptr<SyncSession> weak_session,
2✔
4708
                                                                           const SyncClientHookData& data) mutable {
68✔
4709
                if (data.event != SyncClientHookEvent::BootstrapMessageProcessed &&
68✔
4710
                    data.event != SyncClientHookEvent::BootstrapProcessed) {
68✔
4711
                    return SyncClientHookAction::NoAction;
50✔
4712
                }
50✔
4713
                auto session = weak_session.lock();
18✔
4714
                if (!session) {
18✔
4715
                    return SyncClientHookAction::NoAction;
×
UNCOV
4716
                }
×
4717
                if (data.query_version != 1) {
18✔
4718
                    return SyncClientHookAction::NoAction;
4✔
4719
                }
4✔
4720

4721
                // Commit a subscriptions set whenever a bootstrap message is received for query version 1.
4722
                if (data.event == SyncClientHookEvent::BootstrapMessageProcessed) {
14✔
4723
                    auto latest_subs = session->get_flx_subscription_store()->get_latest().make_mutable_copy();
12✔
4724
                    latest_subs.commit();
12✔
4725
                    return SyncClientHookAction::NoAction;
12✔
4726
                }
12✔
4727
                // At least one subscription set was created.
4728
                CHECK(session->get_flx_subscription_store()->get_latest().version() > 1);
2!
4729
                promise.get_promise().emplace_value();
2✔
4730
                // Reconnect once query version 1 is bootstrapped.
4731
                return SyncClientHookAction::TriggerReconnect;
2✔
4732
            };
2✔
4733

4734
        auto realm = Realm::get_shared_realm(config);
2✔
4735
        {
2✔
4736
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4737
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
4738
            mut_subs.insert_or_assign(Query(table));
2✔
4739
            mut_subs.commit();
2✔
4740
        }
2✔
4741
        pf.future.get();
2✔
4742
        realm->sync_session()->shutdown_and_wait();
2✔
4743
        realm->close();
2✔
4744
    }
2✔
4745

4746
    REQUIRE_FALSE(_impl::RealmCoordinator::get_existing_coordinator(interrupted_realm_config.path));
2!
4747

4748
    // Check at least one subscription set needs to be resent.
4749
    {
2✔
4750
        DBOptions options;
2✔
4751
        options.encryption_key = test_util::crypt_key();
2✔
4752
        auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
4753
        auto sub_store = sync::SubscriptionStore::create(realm);
2✔
4754
        auto version_info = sub_store->get_version_info();
2✔
4755
        REQUIRE(version_info.latest > version_info.active);
2!
4756
    }
2✔
4757

4758
    // Resend the pending subscriptions.
4759
    auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
4760
    wait_for_upload(*realm);
2✔
4761
    wait_for_download(*realm);
2✔
4762
}
2✔
4763

4764
TEST_CASE("flx: fatal errors and session becoming inactive cancel pending waits", "[sync][flx][baas]") {
2✔
4765
    std::vector<ObjectSchema> schema{
2✔
4766
        {"TopLevel",
2✔
4767
         {
2✔
4768
             {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
4769
             {"queryable_int_field", PropertyType::Int | PropertyType::Nullable},
2✔
4770
         }},
2✔
4771
    };
2✔
4772

4773
    FLXSyncTestHarness harness("flx_cancel_pending_waits", {schema, {"queryable_int_field"}});
2✔
4774
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4775

4776
    auto check_status = [](auto status) {
4✔
4777
        CHECK(!status.is_ok());
4!
4778
        std::string reason = status.get_status().reason();
4✔
4779
        // Subscription notification is cancelled either because the sync session is inactive, or because a fatal
4780
        // error is received from the server.
4781
        if (reason.find("Sync session became inactive") == std::string::npos &&
4✔
4782
            reason.find("Invalid schema change (UPLOAD): non-breaking schema change: adding \"Int\" column at field "
4✔
4783
                        "\"other_col\" in schema \"TopLevel\", schema changes from clients are restricted when "
2✔
4784
                        "developer mode is disabled") == std::string::npos) {
2✔
4785
            FAIL(reason);
×
UNCOV
4786
        }
×
4787
    };
4✔
4788

4789
    auto create_subscription = [](auto realm) -> realm::sync::SubscriptionSet {
4✔
4790
        auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
4✔
4791
        auto table = realm->read_group().get_table("class_TopLevel");
4✔
4792
        mut_subs.insert_or_assign(Query(table));
4✔
4793
        return mut_subs.commit();
4✔
4794
    };
4✔
4795

4796
    auto [error_occured_promise, error_occurred] = util::make_promise_future<void>();
2✔
4797
    config.sync_config->error_handler = [promise = util::CopyablePromiseHolder(std::move(error_occured_promise))](
2✔
4798
                                            std::shared_ptr<SyncSession>, SyncError) mutable {
2✔
4799
        promise.get_promise().emplace_value();
2✔
4800
    };
2✔
4801

4802
    auto realm = Realm::get_shared_realm(config);
2✔
4803
    wait_for_download(*realm);
2✔
4804

4805
    auto subs = create_subscription(realm);
2✔
4806
    auto subs_future = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
4807

4808
    realm->sync_session()->pause();
2✔
4809
    auto state = subs_future.get_no_throw();
2✔
4810
    check_status(state);
2✔
4811

4812
    auto [download_complete_promise, download_complete] = util::make_promise_future<void>();
2✔
4813
    realm->sync_session()->wait_for_upload_completion([promise = std::move(download_complete_promise)](auto) mutable {
2✔
4814
        promise.emplace_value();
2✔
4815
    });
2✔
4816
    schema[0].persisted_properties.push_back({"other_col", PropertyType::Int | PropertyType::Nullable});
2✔
4817
    realm->update_schema(schema);
2✔
4818

4819
    subs = create_subscription(realm);
2✔
4820
    subs_future = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
4821

4822
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4823
        CppContext c(realm);
2✔
4824
        Object::create(c, realm, "TopLevel",
2✔
4825
                       std::any(AnyDict{{"_id", ObjectId::gen()},
2✔
4826
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4827
                                        {"other_col", static_cast<int64_t>(42)}}));
2✔
4828
    });
2✔
4829

4830
    realm->sync_session()->resume();
2✔
4831
    download_complete.get();
2✔
4832
    error_occurred.get();
2✔
4833
    state = subs_future.get_no_throw();
2✔
4834
    check_status(state);
2✔
4835
}
2✔
4836

4837
TEST_CASE("flx: pause and resume bootstrapping at query version 0", "[sync][flx][baas]") {
2✔
4838
    FLXSyncTestHarness harness("flx_pause_resume_bootstrap");
2✔
4839
    SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4840
    auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
4841
    std::mutex download_message_mutex;
2✔
4842
    int download_message_integrated_count = 0;
2✔
4843
    triggered_config.sync_config->on_sync_client_event_hook =
2✔
4844
        [promise = util::CopyablePromiseHolder(std::move(interrupted_promise)), &download_message_integrated_count,
2✔
4845
         &download_message_mutex](std::weak_ptr<SyncSession> weak_sess, const SyncClientHookData& data) mutable {
22✔
4846
            auto sess = weak_sess.lock();
22✔
4847
            if (!sess || data.event != SyncClientHookEvent::DownloadMessageIntegrated) {
22✔
4848
                return SyncClientHookAction::NoAction;
18✔
4849
            }
18✔
4850

4851
            std::lock_guard<std::mutex> lk(download_message_mutex);
4✔
4852
            // Pause and resume the first session after the bootstrap message is integrated.
4853
            if (download_message_integrated_count == 0) {
4✔
4854
                sess->pause();
2✔
4855
                sess->resume();
2✔
4856
            }
2✔
4857
            // Complete the test when the second session integrates the empty download
4858
            // message it receives.
4859
            else {
2✔
4860
                promise.get_promise().emplace_value();
2✔
4861
            }
2✔
4862
            ++download_message_integrated_count;
4✔
4863
            return SyncClientHookAction::NoAction;
4✔
4864
        };
22✔
4865
    auto realm = Realm::get_shared_realm(triggered_config);
2✔
4866
    interrupted.get();
2✔
4867
    std::lock_guard<std::mutex> lk(download_message_mutex);
2✔
4868
    CHECK(download_message_integrated_count == 2);
2!
4869
    auto active_sub_set = realm->sync_session()->get_flx_subscription_store()->get_active();
2✔
4870
    REQUIRE(active_sub_set.version() == 0);
2!
4871
    REQUIRE(active_sub_set.state() == sync::SubscriptionSet::State::Complete);
2!
4872
}
2✔
4873

4874
TEST_CASE("flx: collections in mixed - merge lists", "[sync][flx][baas]") {
2✔
4875
    Schema schema{{"TopLevel",
2✔
4876
                   {{"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
4877
                    {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
4878
                    {"any", PropertyType::Mixed | PropertyType::Nullable}}}};
2✔
4879

4880
    FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field"}};
2✔
4881
    FLXSyncTestHarness harness("flx_collections_in_mixed", server_schema);
2✔
4882
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4883

4884
    auto set_list_and_insert_element = [](Obj& obj, ColKey col_any, Mixed value) {
8✔
4885
        obj.set_collection(col_any, CollectionType::List);
8✔
4886
        auto list = obj.get_list_ptr<Mixed>(col_any);
8✔
4887
        list->add(value);
8✔
4888
    };
8✔
4889

4890
    // Client 1 creates an object and sets property 'any' to an integer value.
4891
    auto foo_obj_id = ObjectId::gen();
2✔
4892
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4893
        CppContext c(realm);
2✔
4894
        Object::create(c, realm, "TopLevel",
2✔
4895
                       std::any(AnyDict{{"_id", foo_obj_id}, {"queryable_str_field", "foo"s}, {"any", 42}}));
2✔
4896
    });
2✔
4897

4898
    // Client 2 opens the realm and downloads schema and object created by Client 1.
4899
    auto realm = Realm::get_shared_realm(config);
2✔
4900
    subscribe_to_all_and_bootstrap(*realm);
2✔
4901
    realm->sync_session()->pause();
2✔
4902

4903
    // Client 3 sets property 'any' to List and inserts two integers in the list.
4904
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4905
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4906
        auto obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
4907
        auto col_any = table->get_column_key("any");
2✔
4908
        set_list_and_insert_element(obj, col_any, 1);
2✔
4909
        set_list_and_insert_element(obj, col_any, 2);
2✔
4910
    });
2✔
4911

4912
    // While its session is paused, Client 2 sets property 'any' to List and inserts two integers in the list.
4913
    CppContext c(realm);
2✔
4914
    realm->begin_transaction();
2✔
4915
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
4916
    auto obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
4917
    auto col_any = table->get_column_key("any");
2✔
4918
    set_list_and_insert_element(obj, col_any, 3);
2✔
4919
    set_list_and_insert_element(obj, col_any, 4);
2✔
4920
    realm->commit_transaction();
2✔
4921

4922
    realm->sync_session()->resume();
2✔
4923
    wait_for_upload(*realm);
2✔
4924
    wait_for_download(*realm);
2✔
4925
    wait_for_advance(*realm);
2✔
4926

4927
    // Client 2 ends up with four integers in the list (in the correct order).
4928
    auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
4929
    CHECK(list->size() == 4);
2!
4930
    CHECK(list->get(0) == 1);
2!
4931
    CHECK(list->get(1) == 2);
2!
4932
    CHECK(list->get(2) == 3);
2!
4933
    CHECK(list->get(3) == 4);
2!
4934
}
2✔
4935

4936
TEST_CASE("flx: nested collections in mixed", "[sync][flx][baas]") {
2✔
4937
    Schema schema{{"TopLevel",
2✔
4938
                   {{"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
4939
                    {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
4940
                    {"any", PropertyType::Mixed | PropertyType::Nullable}}}};
2✔
4941

4942
    FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field"}};
2✔
4943
    FLXSyncTestHarness harness("flx_collections_in_mixed", server_schema);
2✔
4944
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4945

4946
    // Client 1: {_id: 1, any: ["abc", [42]]}
4947
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4948
        CppContext c(realm);
2✔
4949
        auto obj = Object::create(c, realm, "TopLevel",
2✔
4950
                                  std::any(AnyDict{{"_id", INT64_C(1)}, {"queryable_str_field", "foo"s}}));
2✔
4951
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4952
        auto col_any = table->get_column_key("any");
2✔
4953
        obj.get_obj().set_collection(col_any, CollectionType::List);
2✔
4954
        List list(obj, obj.get_object_schema().property_for_name("any"));
2✔
4955
        list.insert_any(0, "abc");
2✔
4956
        list.insert_collection(1, CollectionType::List);
2✔
4957
        auto list2 = list.get_list(1);
2✔
4958
        list2.insert_any(0, 42);
2✔
4959
    });
2✔
4960

4961
    // Client 2 opens the realm and downloads schema and object created by Client 1.
4962
    // {_id: 1, any: ["abc", [42]]}
4963
    auto realm = Realm::get_shared_realm(config);
2✔
4964
    subscribe_to_all_and_bootstrap(*realm);
2✔
4965
    realm->sync_session()->pause();
2✔
4966

4967
    // Client 3 adds a dictionary with an element to list 'any'
4968
    // {_id: 1, any: [{{"key": 6}}, "abc", [42]]}
4969
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4970
        CppContext c(realm);
2✔
4971
        auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(INT64_C(1)));
2✔
4972
        List list(obj, obj.get_object_schema().property_for_name("any"));
2✔
4973
        list.insert_collection(PathElement(0), CollectionType::Dictionary);
2✔
4974
        auto dict = list.get_dictionary(PathElement(0));
2✔
4975
        dict.insert_any("key", INT64_C(6));
2✔
4976
    });
2✔
4977

4978
    // While its session is paused, Client 2 makes a change to a nested list
4979
    // {_id: 1, any: ["abc", [42, "foo"]]}
4980
    CppContext c(realm);
2✔
4981
    realm->begin_transaction();
2✔
4982
    auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(INT64_C(1)));
2✔
4983
    List list(obj, obj.get_object_schema().property_for_name("any"));
2✔
4984
    List list2 = list.get_list(PathElement(1));
2✔
4985
    list2.insert_any(list2.size(), "foo");
2✔
4986
    realm->commit_transaction();
2✔
4987

4988
    realm->sync_session()->resume();
2✔
4989
    wait_for_upload(*realm);
2✔
4990
    wait_for_download(*realm);
2✔
4991
    wait_for_advance(*realm);
2✔
4992

4993
    // Client 2 after the session is resumed
4994
    // {_id: 1, any: [{{"key": 6}}, "abc", [42, "foo"]]}
4995
    CHECK(list.size() == 3);
2!
4996
    auto nested_dict = list.get_dictionary(0);
2✔
4997
    CHECK(nested_dict.size() == 1);
2!
4998
    CHECK(nested_dict.get<Int>("key") == 6);
2!
4999

5000
    CHECK(list.get_any(1) == "abc");
2!
5001

5002
    auto nested_list = list.get_list(2);
2✔
5003
    CHECK(nested_list.size() == 2);
2!
5004
    CHECK(nested_list.get_any(0) == 42);
2!
5005
    CHECK(nested_list.get_any(1) == "foo");
2!
5006
}
2✔
5007

5008
} // namespace realm::app
5009

5010
#endif // REALM_ENABLE_AUTH_TESTS
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