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

realm / realm-core / 2306

10 May 2024 05:50PM UTC coverage: 90.837% (-0.2%) from 91.065%
2306

push

Evergreen

danieltabacaru
Add back ability to format Objective-C code

102110 of 181070 branches covered (56.39%)

214623 of 236272 relevant lines covered (90.84%)

5666944.3 hits per line

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

98.27
/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
                // make sure that the subscription for "foo" survived the reset
734
                size_t count_of_foo = count_queries_with_str(subs, util::format("\"%1\"", str_field_value));
2✔
735
                REQUIRE(subs.state() == sync::SubscriptionSet::State::Complete);
2!
736
                REQUIRE(count_of_foo == 1);
2!
737
                local_realm->refresh();
2✔
738
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
739
                auto str_col = table->get_column_key("queryable_str_field");
2✔
740
                auto int_col = table->get_column_key("queryable_int_field");
2✔
741
                auto tv = table->where().equal(str_col, StringData(str_field_value)).find_all();
2✔
742
                tv.sort(int_col);
2✔
743
                // the object we created while offline was recovered, and the remote object was downloaded
744
                REQUIRE(tv.size() == 2);
2!
745
                CHECK(tv.get_object(0).get<Int>(int_col) == local_added_int);
2!
746
                CHECK(tv.get_object(1).get<Int>(int_col) == remote_added_int);
2!
747
            })
2✔
748
            ->run();
2✔
749
    }
2✔
750

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

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

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

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

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

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

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

951
        VersionID expected_version;
4✔
952

953
        auto store_pre_reset_state = [&](SharedRealm local_realm) {
4✔
954
            expected_version = local_realm->read_transaction_version();
4✔
955
        };
4✔
956

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

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

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

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

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

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

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

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

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

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

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

1153
    SECTION("DiscardLocal: open realm after client reset failure") {
46✔
1154
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1155
        auto&& [error_future, error_handler] = make_error_handler();
2✔
1156
        config_local.sync_config->error_handler = error_handler;
2✔
1157

1158
        std::string fresh_path = realm::_impl::client_reset::get_fresh_path_for(config_local.path);
2✔
1159
        // create a non-empty directory that we'll fail to delete
1160
        util::make_dir(fresh_path);
2✔
1161
        util::File(util::File::resolve("file", fresh_path), util::File::mode_Write);
2✔
1162

1163
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1164
        test_reset->run();
2✔
1165

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

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

1174
        auto realm_post_reset = Realm::get_shared_realm(config_local);
2✔
1175
        sync_error = wait_for_future(std::move(err_future)).get();
2✔
1176
        REQUIRE(sync_error.status == ErrorCodes::AutoClientResetFailed);
2!
1177
    }
2✔
1178

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

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

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

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

1260
    SECTION("Adding a local property matching a server addition is allowed") {
46✔
1261
        auto mode = GENERATE(ClientResyncMode::DiscardLocal, ClientResyncMode::Recover);
4✔
1262
        config_local.sync_config->client_resync_mode = mode;
4✔
1263
        seed_realm(config_local, ResetMode::InitiateClientReset);
4✔
1264
        std::vector<ObjectSchema> changed_schema = schema;
4✔
1265
        changed_schema[0].persisted_properties.push_back(
4✔
1266
            {"queryable_oid_field", PropertyType::ObjectId | PropertyType::Nullable});
4✔
1267
        // In a separate Realm, make the property addition.
1268
        // Since this is dev mode, it will be added to the server's schema.
1269
        config_remote.schema = changed_schema;
4✔
1270
        seed_realm(config_remote, ResetMode::NoReset);
4✔
1271
        std::swap(changed_schema[0].persisted_properties[1], changed_schema[0].persisted_properties[2]);
4✔
1272
        config_local.schema = changed_schema;
4✔
1273
        auto future = setup_reset_handlers_for_schema_validation(config_local, changed_schema);
4✔
1274

1275
        async_open_realm(config_local,
4✔
1276
                         [&, fut = std::move(future)](ThreadSafeReference&& ref, std::exception_ptr error) {
4✔
1277
                             REQUIRE(ref);
4!
1278
                             REQUIRE_FALSE(error);
4!
1279
                             auto realm = Realm::get_shared_realm(std::move(ref));
4✔
1280
                             fut.get();
4✔
1281
                             CHECK(before_reset_count == 1);
4!
1282
                             CHECK(after_reset_count == 1);
4!
1283
                         });
4✔
1284
    }
4✔
1285

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

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

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

1315
        async_open_realm(config_local,
4✔
1316
                         [&, fut = std::move(future)](ThreadSafeReference&& ref, std::exception_ptr error) {
4✔
1317
                             REQUIRE(ref);
4!
1318
                             REQUIRE_FALSE(error);
4!
1319
                             auto realm = Realm::get_shared_realm(std::move(ref));
4✔
1320
                             fut.get();
4✔
1321
                             CHECK(before_reset_count == 1);
4!
1322
                             CHECK(after_reset_count == 1);
4!
1323
                         });
4✔
1324
    }
4✔
1325

1326
    auto make_additive_changes = [](std::vector<ObjectSchema> schema) {
46✔
1327
        schema[0].persisted_properties.push_back(
6✔
1328
            {"added_oid_field", PropertyType::ObjectId | PropertyType::Nullable});
6✔
1329
        std::swap(schema[0].persisted_properties[1], schema[0].persisted_properties[2]);
6✔
1330
        schema.push_back({"AddedClass",
6✔
1331
                          {
6✔
1332
                              {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
6✔
1333
                              {"str_field", PropertyType::String | PropertyType::Nullable},
6✔
1334
                          }});
6✔
1335
        return schema;
6✔
1336
    };
6✔
1337
    SECTION("Recover: additive schema changes are recovered in dev mode") {
46✔
1338
        const AppSession& app_session = harness.session().app_session();
2✔
1339
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, true);
2✔
1340
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1341
        std::vector<ObjectSchema> changed_schema = make_additive_changes(schema);
2✔
1342
        config_local.schema = changed_schema;
2✔
1343
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1344
        ThreadSafeReference ref_async;
2✔
1345
        auto future = setup_reset_handlers_for_schema_validation(config_local, changed_schema);
2✔
1346
        async_open_realm(config_local, [&](ThreadSafeReference&& ref, std::exception_ptr error) {
2✔
1347
            REQUIRE(ref);
2!
1348
            REQUIRE_FALSE(error);
2!
1349
            ref_async = std::move(ref);
2✔
1350
        });
2✔
1351
        future.get();
2✔
1352
        CHECK(before_reset_count == 1);
2!
1353
        CHECK(after_reset_count == 1);
2!
1354
        {
2✔
1355
            auto realm = Realm::get_shared_realm(std::move(ref_async));
2✔
1356
            // make changes to the newly added property
1357
            realm->begin_transaction();
2✔
1358
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
1359
            ColKey new_col = table->get_column_key("added_oid_field");
2✔
1360
            REQUIRE(new_col);
2!
1361
            for (auto it = table->begin(); it != table->end(); ++it) {
4✔
1362
                it->set(new_col, ObjectId::gen());
2✔
1363
            }
2✔
1364
            realm->commit_transaction();
2✔
1365
            // subscribe to the new Class and add an object
1366
            auto new_table = realm->read_group().get_table("class_AddedClass");
2✔
1367
            auto sub_set = realm->get_latest_subscription_set();
2✔
1368
            auto mut_sub = sub_set.make_mutable_copy();
2✔
1369
            mut_sub.insert_or_assign(Query(new_table));
2✔
1370
            mut_sub.commit();
2✔
1371
            realm->begin_transaction();
2✔
1372
            REQUIRE(new_table);
2!
1373
            new_table->create_object_with_primary_key(ObjectId::gen());
2✔
1374
            realm->commit_transaction();
2✔
1375
            auto result = realm->get_latest_subscription_set()
2✔
1376
                              .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
1377
                              .get();
2✔
1378
            CHECK(result == sync::SubscriptionSet::State::Complete);
2!
1379
            wait_for_advance(*realm);
2✔
1380
            realm->close();
2✔
1381
        }
2✔
1382
        {
2✔
1383
            // ensure that an additional schema change after the successful reset is also accepted by the server
1384
            changed_schema[0].persisted_properties.push_back(
2✔
1385
                {"added_oid_field_second", PropertyType::ObjectId | PropertyType::Nullable});
2✔
1386
            changed_schema.push_back({"AddedClassSecond",
2✔
1387
                                      {
2✔
1388
                                          {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
1389
                                          {"str_field_2", PropertyType::String | PropertyType::Nullable},
2✔
1390
                                      }});
2✔
1391
            config_local.schema = changed_schema;
2✔
1392
            async_open_realm(config_local, [&](ThreadSafeReference&& ref, std::exception_ptr error) {
2✔
1393
                REQUIRE(ref);
2!
1394
                REQUIRE_FALSE(error);
2!
1395
                auto realm = Realm::get_shared_realm(std::move(ref));
2✔
1396
                auto table = realm->read_group().get_table("class_AddedClassSecond");
2✔
1397
                ColKey new_col = table->get_column_key("str_field_2");
2✔
1398
                REQUIRE(new_col);
2!
1399
                auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
1400
                new_subs.insert_or_assign(Query(table).equal(new_col, "hello"));
2✔
1401
                auto subs = new_subs.commit();
2✔
1402
                realm->begin_transaction();
2✔
1403
                table->create_object_with_primary_key(Mixed{ObjectId::gen()}, {{new_col, "hello"}});
2✔
1404
                realm->commit_transaction();
2✔
1405
                subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1406
                wait_for_advance(*realm);
2✔
1407
                REQUIRE(table->size() == 1);
2!
1408
            });
2✔
1409
        }
2✔
1410
    }
2✔
1411

1412
    SECTION("DiscardLocal: additive schema changes not allowed") {
46✔
1413
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1414
        std::vector<ObjectSchema> changed_schema = make_additive_changes(schema);
2✔
1415
        config_local.schema = changed_schema;
2✔
1416
        config_local.sync_config->client_resync_mode = ClientResyncMode::DiscardLocal;
2✔
1417
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1418
        config_local.sync_config->error_handler = err_handler;
2✔
1419
        async_open_realm(config_local, [&](ThreadSafeReference&& ref, std::exception_ptr error) {
2✔
1420
            REQUIRE(!ref);
2!
1421
            REQUIRE(error);
2!
1422
            REQUIRE_THROWS_CONTAINING(std::rethrow_exception(error),
2✔
1423
                                      "A fatal error occurred during client reset: 'Client reset cannot recover when "
2✔
1424
                                      "classes have been removed: {AddedClass}'");
2✔
1425
        });
2✔
1426
        error_future.get();
2✔
1427
        CHECK(before_reset_count == 1);
2!
1428
        CHECK(after_reset_count == 0);
2!
1429
    }
2✔
1430

1431
    SECTION("Recover: incompatible schema changes on async open are an error") {
46✔
1432
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1433
        std::vector<ObjectSchema> changed_schema = schema;
2✔
1434
        changed_schema[0].persisted_properties[0].type = PropertyType::UUID; // incompatible type change
2✔
1435
        config_local.schema = changed_schema;
2✔
1436
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1437
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1438
        config_local.sync_config->error_handler = err_handler;
2✔
1439
        async_open_realm(config_local, [&](ThreadSafeReference&& ref, std::exception_ptr error) {
2✔
1440
            REQUIRE(!ref);
2!
1441
            REQUIRE(error);
2!
1442
            REQUIRE_THROWS_CONTAINING(
2✔
1443
                std::rethrow_exception(error),
2✔
1444
                "A fatal error occurred during client reset: 'The following changes cannot be "
2✔
1445
                "made in additive-only schema mode:\n"
2✔
1446
                "- Property 'TopLevel._id' has been changed from 'object id' to 'uuid'.\nIf your app is running in "
2✔
1447
                "development mode, you can delete the realm and restart the app to update your schema.'");
2✔
1448
        });
2✔
1449
        error_future.get();
2✔
1450
        CHECK(before_reset_count == 0); // we didn't even get this far because opening the frozen realm fails
2!
1451
        CHECK(after_reset_count == 0);
2!
1452
    }
2✔
1453

1454
    SECTION("Recover: additive schema changes without dev mode produce an error after client reset") {
46✔
1455
        const AppSession& app_session = harness.session().app_session();
2✔
1456
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, true);
2✔
1457
        seed_realm(config_local, ResetMode::InitiateClientReset);
2✔
1458
        // Disable dev mode so that schema changes are not allowed
1459
        app_session.admin_api.set_development_mode_to(app_session.server_app_id, false);
2✔
1460
        auto cleanup = util::make_scope_exit([&]() noexcept {
2✔
1461
            const AppSession& app_session = harness.session().app_session();
2✔
1462
            app_session.admin_api.set_development_mode_to(app_session.server_app_id, true);
2✔
1463
        });
2✔
1464

1465
        std::vector<ObjectSchema> changed_schema = make_additive_changes(schema);
2✔
1466
        config_local.schema = changed_schema;
2✔
1467
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1468
        (void)setup_reset_handlers_for_schema_validation(config_local, changed_schema);
2✔
1469
        auto&& [error_future, err_handler] = make_error_handler();
2✔
1470
        config_local.sync_config->error_handler = err_handler;
2✔
1471
        async_open_realm(config_local, [&](ThreadSafeReference&& ref, std::exception_ptr error) {
2✔
1472
            REQUIRE(ref);
2!
1473
            REQUIRE_FALSE(error);
2!
1474
            auto realm = Realm::get_shared_realm(std::move(ref));
2✔
1475
            // make changes to the new property
1476
            realm->begin_transaction();
2✔
1477
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
1478
            ColKey new_col = table->get_column_key("added_oid_field");
2✔
1479
            REQUIRE(new_col);
2!
1480
            for (auto it = table->begin(); it != table->end(); ++it) {
4✔
1481
                it->set(new_col, ObjectId::gen());
2✔
1482
            }
2✔
1483
            realm->commit_transaction();
2✔
1484
        });
2✔
1485
        auto realm = Realm::get_shared_realm(config_local);
2✔
1486
        auto err = error_future.get();
2✔
1487
        std::string property_err = "Invalid schema change (UPLOAD): non-breaking schema change: adding "
2✔
1488
                                   "\"ObjectID\" column at field \"added_oid_field\" in schema \"TopLevel\", "
2✔
1489
                                   "schema changes from clients are restricted when developer mode is disabled";
2✔
1490
        std::string class_err = "Invalid schema change (UPLOAD): non-breaking schema change: adding schema "
2✔
1491
                                "for Realm table \"AddedClass\", schema changes from clients are restricted when "
2✔
1492
                                "developer mode is disabled";
2✔
1493
        REQUIRE_THAT(err.status.reason(), Catch::Matchers::ContainsSubstring(property_err) ||
2✔
1494
                                              Catch::Matchers::ContainsSubstring(class_err));
2✔
1495
        CHECK(before_reset_count == 1);
2!
1496
        CHECK(after_reset_count == 1);
2!
1497
    }
2✔
1498

1499
    SECTION("Recover: inserts in collections in mixed - collections cleared remotely") {
46✔
1500
        config_local.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
1501
        auto&& [reset_future, reset_handler] = make_client_reset_handler();
2✔
1502
        config_local.sync_config->notify_after_client_reset = reset_handler;
2✔
1503
        auto test_reset = reset_utils::make_baas_flx_client_reset(config_local, config_remote, harness.session());
2✔
1504
        test_reset
2✔
1505
            ->populate_initial_object([&](SharedRealm realm) {
2✔
1506
                subscribe_to_all_and_bootstrap(*realm);
2✔
1507
                auto pk_of_added_object = ObjectId::gen();
2✔
1508
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
1509

1510
                realm->begin_transaction();
2✔
1511
                CppContext c(realm);
2✔
1512
                auto obj = Object::create(c, realm, "TopLevel",
2✔
1513
                                          std::any(AnyDict{{"_id"s, pk_of_added_object},
2✔
1514
                                                           {"queryable_str_field"s, "initial value"s},
2✔
1515
                                                           {"sum_of_list_field"s, int64_t(42)}}));
2✔
1516
                auto col_any = table->get_column_key("any_mixed");
2✔
1517
                obj.get_obj().set_collection(col_any, CollectionType::List);
2✔
1518
                auto list = obj.get_obj().get_list_ptr<Mixed>(col_any);
2✔
1519
                list->add(1);
2✔
1520
                auto dict = obj.get_obj().get_dictionary("dictionary_mixed");
2✔
1521
                dict.insert("key", 42);
2✔
1522
                realm->commit_transaction();
2✔
1523
                wait_for_upload(*realm);
2✔
1524
                return pk_of_added_object;
2✔
1525
            })
2✔
1526
            ->make_local_changes([&](SharedRealm local_realm) {
2✔
1527
                local_realm->begin_transaction();
2✔
1528
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
1529
                auto col_any = table->get_column_key("any_mixed");
2✔
1530
                auto obj = table->get_object(0);
2✔
1531
                auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
1532
                list->add(2);
2✔
1533
                auto dict = obj.get_dictionary("dictionary_mixed");
2✔
1534
                dict.insert("key2", "value");
2✔
1535
                local_realm->commit_transaction();
2✔
1536
            })
2✔
1537
            ->make_remote_changes([&](SharedRealm remote_realm) {
2✔
1538
                remote_realm->begin_transaction();
2✔
1539
                auto table = remote_realm->read_group().get_table("class_TopLevel");
2✔
1540
                auto col_any = table->get_column_key("any_mixed");
2✔
1541
                auto obj = table->get_object(0);
2✔
1542
                auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
1543
                list->clear();
2✔
1544
                auto dict = obj.get_dictionary("dictionary_mixed");
2✔
1545
                dict.clear();
2✔
1546
                remote_realm->commit_transaction();
2✔
1547
            })
2✔
1548
            ->on_post_reset([&, client_reset_future = std::move(reset_future)](SharedRealm local_realm) {
2✔
1549
                wait_for_advance(*local_realm);
2✔
1550
                ClientResyncMode mode = client_reset_future.get();
2✔
1551
                REQUIRE(mode == ClientResyncMode::Recover);
2!
1552
                auto table = local_realm->read_group().get_table("class_TopLevel");
2✔
1553
                auto obj = table->get_object(0);
2✔
1554
                auto col_any = table->get_column_key("any_mixed");
2✔
1555
                auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
1556
                CHECK(list->size() == 1);
2!
1557
                CHECK(list->get_any(0).get_int() == 2);
2!
1558
                auto dict = obj.get_dictionary("dictionary_mixed");
2✔
1559
                CHECK(dict.size() == 1);
2!
1560
                CHECK(dict.get("key2").get_string() == "value");
2!
1561
            })
2✔
1562
            ->run();
2✔
1563
    }
2✔
1564
}
46✔
1565

1566
TEST_CASE("flx: creating an object on a class with no subscription throws", "[sync][flx][subscription][baas]") {
2✔
1567
    FLXSyncTestHarness harness("flx_bad_query", {g_simple_embedded_obj_schema, {"queryable_str_field"}});
2✔
1568
    harness.do_with_new_user([&](auto user) {
2✔
1569
        SyncTestFile config(user, harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
1570
        auto [error_promise, error_future] = util::make_promise_future<SyncError>();
2✔
1571
        auto shared_promise = std::make_shared<decltype(error_promise)>(std::move(error_promise));
2✔
1572
        config.sync_config->error_handler = [error_promise = std::move(shared_promise)](std::shared_ptr<SyncSession>,
2✔
1573
                                                                                        SyncError err) {
2✔
1574
            CHECK(err.server_requests_action == sync::ProtocolErrorInfo::Action::Transient);
×
1575
            error_promise->emplace_value(std::move(err));
×
1576
        };
×
1577

1578
        auto realm = Realm::get_shared_realm(config);
2✔
1579
        CppContext c(realm);
2✔
1580
        realm->begin_transaction();
2✔
1581
        REQUIRE_THROWS_AS(
2✔
1582
            Object::create(c, realm, "TopLevel",
2✔
1583
                           std::any(AnyDict{{"_id", ObjectId::gen()}, {"queryable_str_field", "foo"s}})),
2✔
1584
            NoSubscriptionForWrite);
2✔
1585
        realm->cancel_transaction();
2✔
1586

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

1589
        REQUIRE(table->is_empty());
2!
1590
        auto col_key = table->get_column_key("queryable_str_field");
2✔
1591
        {
2✔
1592
            auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
1593
            new_subs.insert_or_assign(Query(table).equal(col_key, "foo"));
2✔
1594
            auto subs = new_subs.commit();
2✔
1595
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1596
        }
2✔
1597

1598
        realm->begin_transaction();
2✔
1599
        auto obj = Object::create(c, realm, "TopLevel",
2✔
1600
                                  std::any(AnyDict{{"_id", ObjectId::gen()},
2✔
1601
                                                   {"queryable_str_field", "foo"s},
2✔
1602
                                                   {"embedded_obj", AnyDict{{"str_field", "bar"s}}}}));
2✔
1603
        realm->commit_transaction();
2✔
1604

1605
        realm->begin_transaction();
2✔
1606
        auto embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1607
        embedded_obj.set_property_value(c, "str_field", std::any{"baz"s});
2✔
1608
        realm->commit_transaction();
2✔
1609

1610
        wait_for_upload(*realm);
2✔
1611
        wait_for_download(*realm);
2✔
1612
    });
2✔
1613
}
2✔
1614

1615
TEST_CASE("flx: uploading an object that is out-of-view results in compensating write",
1616
          "[sync][flx][compensating write][baas]") {
16✔
1617
    static std::optional<FLXSyncTestHarness> harness;
16✔
1618
    if (!harness) {
16✔
1619
        Schema schema{{"TopLevel",
2✔
1620
                       {{"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
1621
                        {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1622
                        {"embedded_obj", PropertyType::Object | PropertyType::Nullable, "TopLevel_embedded_obj"}}},
2✔
1623
                      {"TopLevel_embedded_obj",
2✔
1624
                       ObjectSchema::ObjectType::Embedded,
2✔
1625
                       {{"str_field", PropertyType::String | PropertyType::Nullable}}},
2✔
1626
                      {"Int PK",
2✔
1627
                       {
2✔
1628
                           {"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
1629
                           {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1630
                       }},
2✔
1631
                      {"String PK",
2✔
1632
                       {
2✔
1633
                           {"_id", PropertyType::String, Property::IsPrimary{true}},
2✔
1634
                           {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1635
                       }},
2✔
1636
                      {"UUID PK",
2✔
1637
                       {
2✔
1638
                           {"_id", PropertyType::UUID, Property::IsPrimary{true}},
2✔
1639
                           {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
1640
                       }}};
2✔
1641

1642
        AppCreateConfig::ServiceRole role;
2✔
1643
        role.name = "compensating_write_perms";
2✔
1644

1645
        AppCreateConfig::ServiceRoleDocumentFilters doc_filters;
2✔
1646
        doc_filters.read = true;
2✔
1647
        doc_filters.write = {{"queryable_str_field", {{"$in", nlohmann::json::array({"foo", "bar"})}}}};
2✔
1648
        role.document_filters = doc_filters;
2✔
1649

1650
        role.insert_filter = true;
2✔
1651
        role.delete_filter = true;
2✔
1652
        role.read = true;
2✔
1653
        role.write = true;
2✔
1654
        FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field"}, {role}};
2✔
1655
        harness.emplace("flx_bad_query", server_schema);
2✔
1656
    }
2✔
1657

1658
    create_user_and_log_in(harness->app());
16✔
1659
    auto user = harness->app()->current_user();
16✔
1660

1661
    auto make_error_handler = [] {
16✔
1662
        auto [error_promise, error_future] = util::make_promise_future<SyncError>();
16✔
1663
        auto shared_promise = std::make_shared<decltype(error_promise)>(std::move(error_promise));
16✔
1664
        auto fn = [error_promise = std::move(shared_promise)](std::shared_ptr<SyncSession>, SyncError err) mutable {
16✔
1665
            if (!error_promise) {
14✔
1666
                util::format(std::cerr,
×
1667
                             "An unexpected sync error was caught by the default SyncTestFile handler: '%1'\n",
×
1668
                             err.status);
×
1669
                abort();
×
1670
            }
×
1671
            error_promise->emplace_value(std::move(err));
14✔
1672
            error_promise.reset();
14✔
1673
        };
14✔
1674

1675
        return std::make_pair(std::move(error_future), std::move(fn));
16✔
1676
    };
16✔
1677

1678
    auto validate_sync_error = [&](const SyncError& sync_error, Mixed expected_pk, const char* expected_object_name,
16✔
1679
                                   const std::string& error_msg_fragment) {
16✔
1680
        CHECK(sync_error.status == ErrorCodes::SyncCompensatingWrite);
14!
1681
        CHECK(!sync_error.is_client_reset_requested());
14!
1682
        CHECK(sync_error.compensating_writes_info.size() == 1);
14!
1683
        CHECK(sync_error.server_requests_action == sync::ProtocolErrorInfo::Action::Warning);
14!
1684
        auto write_info = sync_error.compensating_writes_info[0];
14✔
1685
        CHECK(write_info.primary_key == expected_pk);
14!
1686
        CHECK(write_info.object_name == expected_object_name);
14!
1687
        CHECK_THAT(write_info.reason, Catch::Matchers::ContainsSubstring(error_msg_fragment));
14✔
1688
    };
14✔
1689

1690
    SyncTestFile config(user, harness->schema(), SyncConfig::FLXSyncEnabled{});
16✔
1691
    auto&& [error_future, err_handler] = make_error_handler();
16✔
1692
    config.sync_config->error_handler = err_handler;
16✔
1693
    auto realm = Realm::get_shared_realm(config);
16✔
1694
    auto table = realm->read_group().get_table("class_TopLevel");
16✔
1695

1696
    auto create_subscription = [&](StringData table_name, auto make_query) {
16✔
1697
        auto table = realm->read_group().get_table(table_name);
14✔
1698
        auto queryable_str_field = table->get_column_key("queryable_str_field");
14✔
1699
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
14✔
1700
        new_query.insert_or_assign(make_query(Query(table), queryable_str_field));
14✔
1701
        new_query.commit();
14✔
1702
    };
14✔
1703

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

1709
        CppContext c(realm);
2✔
1710
        realm->begin_transaction();
2✔
1711
        auto invalid_obj = ObjectId::gen();
2✔
1712
        Object::create(c, realm, "TopLevel",
2✔
1713
                       std::any(AnyDict{{"_id", invalid_obj}, {"queryable_str_field", "bizz"s}}));
2✔
1714
        realm->commit_transaction();
2✔
1715

1716
        validate_sync_error(
2✔
1717
            std::move(error_future).get(), invalid_obj, "TopLevel",
2✔
1718
            util::format("write to ObjectID(\"%1\") in table \"TopLevel\" not allowed", invalid_obj.to_string()));
2✔
1719

1720
        wait_for_advance(*realm);
2✔
1721

1722
        auto top_level_table = realm->read_group().get_table("class_TopLevel");
2✔
1723
        REQUIRE(top_level_table->is_empty());
2!
1724
    }
2✔
1725

1726
    SECTION("compensating write because of permission violation with write on embedded object") {
16✔
1727
        create_subscription("class_TopLevel", [](auto q, auto col) {
2✔
1728
            return q.equal(col, "bizz").Or().equal(col, "foo");
2✔
1729
        });
2✔
1730

1731
        CppContext c(realm);
2✔
1732
        realm->begin_transaction();
2✔
1733
        auto invalid_obj = ObjectId::gen();
2✔
1734
        auto obj = Object::create(c, realm, "TopLevel",
2✔
1735
                                  std::any(AnyDict{{"_id", invalid_obj},
2✔
1736
                                                   {"queryable_str_field", "foo"s},
2✔
1737
                                                   {"embedded_obj", AnyDict{{"str_field", "bar"s}}}}));
2✔
1738
        realm->commit_transaction();
2✔
1739
        realm->begin_transaction();
2✔
1740
        obj.set_property_value(c, "queryable_str_field", std::any{"bizz"s});
2✔
1741
        realm->commit_transaction();
2✔
1742
        realm->begin_transaction();
2✔
1743
        auto embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1744
        embedded_obj.set_property_value(c, "str_field", std::any{"baz"s});
2✔
1745
        realm->commit_transaction();
2✔
1746

1747
        validate_sync_error(
2✔
1748
            std::move(error_future).get(), invalid_obj, "TopLevel",
2✔
1749
            util::format("write to ObjectID(\"%1\") in table \"TopLevel\" not allowed", invalid_obj.to_string()));
2✔
1750

1751
        wait_for_advance(*realm);
2✔
1752

1753
        obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(invalid_obj));
2✔
1754
        embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1755
        REQUIRE(util::any_cast<std::string&&>(obj.get_property_value<std::any>(c, "queryable_str_field")) == "foo");
2!
1756
        REQUIRE(util::any_cast<std::string&&>(embedded_obj.get_property_value<std::any>(c, "str_field")) == "bar");
2!
1757

1758
        realm->begin_transaction();
2✔
1759
        embedded_obj.set_property_value(c, "str_field", std::any{"baz"s});
2✔
1760
        realm->commit_transaction();
2✔
1761

1762
        wait_for_upload(*realm);
2✔
1763
        wait_for_download(*realm);
2✔
1764

1765
        wait_for_advance(*realm);
2✔
1766
        obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(invalid_obj));
2✔
1767
        embedded_obj = util::any_cast<Object&&>(obj.get_property_value<std::any>(c, "embedded_obj"));
2✔
1768
        REQUIRE(embedded_obj.get_column_value<StringData>("str_field") == "baz");
2!
1769
    }
2✔
1770

1771
    SECTION("compensating write for writing a top-level object that is out-of-view") {
16✔
1772
        create_subscription("class_TopLevel", [](auto q, auto col) {
2✔
1773
            return q.equal(col, "foo");
2✔
1774
        });
2✔
1775

1776
        CppContext c(realm);
2✔
1777
        realm->begin_transaction();
2✔
1778
        auto valid_obj = ObjectId::gen();
2✔
1779
        auto invalid_obj = ObjectId::gen();
2✔
1780
        Object::create(c, realm, "TopLevel",
2✔
1781
                       std::any(AnyDict{
2✔
1782
                           {"_id", valid_obj},
2✔
1783
                           {"queryable_str_field", "foo"s},
2✔
1784
                       }));
2✔
1785
        Object::create(c, realm, "TopLevel",
2✔
1786
                       std::any(AnyDict{
2✔
1787
                           {"_id", invalid_obj},
2✔
1788
                           {"queryable_str_field", "bar"s},
2✔
1789
                       }));
2✔
1790
        realm->commit_transaction();
2✔
1791

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

1795
        wait_for_advance(*realm);
2✔
1796

1797
        auto top_level_table = realm->read_group().get_table("class_TopLevel");
2✔
1798
        REQUIRE(top_level_table->size() == 1);
2!
1799
        REQUIRE(top_level_table->get_object_with_primary_key(valid_obj));
2!
1800

1801
        // Verify that a valid object afterwards does not produce an error
1802
        realm->begin_transaction();
2✔
1803
        Object::create(c, realm, "TopLevel",
2✔
1804
                       std::any(AnyDict{
2✔
1805
                           {"_id", ObjectId::gen()},
2✔
1806
                           {"queryable_str_field", "foo"s},
2✔
1807
                       }));
2✔
1808
        realm->commit_transaction();
2✔
1809

1810
        wait_for_upload(*realm);
2✔
1811
        wait_for_download(*realm);
2✔
1812
    }
2✔
1813

1814
    SECTION("compensating writes for each primary key type") {
16✔
1815
        SECTION("int") {
8✔
1816
            create_subscription("class_Int PK", [](auto q, auto col) {
2✔
1817
                return q.equal(col, "foo");
2✔
1818
            });
2✔
1819
            realm->begin_transaction();
2✔
1820
            realm->read_group().get_table("class_Int PK")->create_object_with_primary_key(123456);
2✔
1821
            realm->commit_transaction();
2✔
1822

1823
            validate_sync_error(std::move(error_future).get(), 123456, "Int PK",
2✔
1824
                                "write to 123456 in table \"Int PK\" not allowed");
2✔
1825
        }
2✔
1826

1827
        SECTION("short string") {
8✔
1828
            create_subscription("class_String PK", [](auto q, auto col) {
2✔
1829
                return q.equal(col, "foo");
2✔
1830
            });
2✔
1831
            realm->begin_transaction();
2✔
1832
            realm->read_group().get_table("class_String PK")->create_object_with_primary_key("short");
2✔
1833
            realm->commit_transaction();
2✔
1834

1835
            validate_sync_error(std::move(error_future).get(), "short", "String PK",
2✔
1836
                                "write to \"short\" in table \"String PK\" not allowed");
2✔
1837
        }
2✔
1838

1839
        SECTION("long string") {
8✔
1840
            create_subscription("class_String PK", [](auto q, auto col) {
2✔
1841
                return q.equal(col, "foo");
2✔
1842
            });
2✔
1843
            realm->begin_transaction();
2✔
1844
            const char* pk = "long string which won't fit in the SSO buffer";
2✔
1845
            realm->read_group().get_table("class_String PK")->create_object_with_primary_key(pk);
2✔
1846
            realm->commit_transaction();
2✔
1847

1848
            validate_sync_error(std::move(error_future).get(), pk, "String PK",
2✔
1849
                                util::format("write to \"%1\" in table \"String PK\" not allowed", pk));
2✔
1850
        }
2✔
1851

1852
        SECTION("uuid") {
8✔
1853
            create_subscription("class_UUID PK", [](auto q, auto col) {
2✔
1854
                return q.equal(col, "foo");
2✔
1855
            });
2✔
1856
            realm->begin_transaction();
2✔
1857
            UUID pk("01234567-9abc-4def-9012-3456789abcde");
2✔
1858
            realm->read_group().get_table("class_UUID PK")->create_object_with_primary_key(pk);
2✔
1859
            realm->commit_transaction();
2✔
1860

1861
            validate_sync_error(std::move(error_future).get(), pk, "UUID PK",
2✔
1862
                                util::format("write to UUID(%1) in table \"UUID PK\" not allowed", pk));
2✔
1863
        }
2✔
1864
    }
8✔
1865

1866
    // Clear the Realm afterwards as we're reusing an app
1867
    realm->begin_transaction();
16✔
1868
    table->clear();
16✔
1869
    realm->commit_transaction();
16✔
1870
    wait_for_upload(*realm);
16✔
1871
    realm.reset();
16✔
1872

1873
    // Add new sections before this
1874
    SECTION("teardown") {
16✔
1875
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
1876
        harness.reset();
2✔
1877
    }
2✔
1878
}
16✔
1879

1880
TEST_CASE("flx: query on non-queryable field results in query error message", "[sync][flx][query][baas]") {
8✔
1881
    static std::optional<FLXSyncTestHarness> harness;
8✔
1882
    if (!harness) {
8✔
1883
        harness.emplace("flx_bad_query");
2✔
1884
    }
2✔
1885

1886
    auto create_subscription = [](SharedRealm realm, StringData table_name, StringData column_name, auto make_query) {
10✔
1887
        auto table = realm->read_group().get_table(table_name);
10✔
1888
        auto queryable_field = table->get_column_key(column_name);
10✔
1889
        auto new_query = realm->get_active_subscription_set().make_mutable_copy();
10✔
1890
        new_query.insert_or_assign(make_query(Query(table), queryable_field));
10✔
1891
        return new_query.commit();
10✔
1892
    };
10✔
1893

1894
    auto check_status = [](auto status) {
8✔
1895
        CHECK(!status.is_ok());
8!
1896
        std::string reason = status.get_status().reason();
8✔
1897
        // Depending on the version of baas used, it may return 'Invalid query:' or
1898
        // 'Client provided query with bad syntax:'
1899
        if ((reason.find("Invalid query:") == std::string::npos &&
8✔
1900
             reason.find("Client provided query with bad syntax:") == std::string::npos) ||
8!
1901
            reason.find("\"TopLevel\": key \"non_queryable_field\" is not a queryable field") == std::string::npos) {
8✔
1902
            FAIL(util::format("Error reason did not match expected: `%1`", reason));
×
1903
        }
×
1904
    };
8✔
1905

1906
    SECTION("Good query after bad query") {
8✔
1907
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1908
            auto subs = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1909
                return q.equal(c, "bar");
2✔
1910
            });
2✔
1911
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1912
            check_status(sub_res);
2✔
1913

1914
            CHECK(realm->get_active_subscription_set().version() == 0);
2!
1915
            CHECK(realm->get_latest_subscription_set().version() == 1);
2!
1916

1917
            subs = create_subscription(realm, "class_TopLevel", "queryable_str_field", [](auto q, auto c) {
2✔
1918
                return q.equal(c, "foo");
2✔
1919
            });
2✔
1920
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
1921

1922
            CHECK(realm->get_active_subscription_set().version() == 2);
2!
1923
            CHECK(realm->get_latest_subscription_set().version() == 2);
2!
1924
        });
2✔
1925
    }
2✔
1926

1927
    SECTION("Bad query after bad query") {
8✔
1928
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1929
            auto sync_session = realm->sync_session();
2✔
1930
            sync_session->pause();
2✔
1931

1932
            auto subs = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1933
                return q.equal(c, "bar");
2✔
1934
            });
2✔
1935
            auto subs2 = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1936
                return q.equal(c, "bar");
2✔
1937
            });
2✔
1938

1939
            sync_session->resume();
2✔
1940

1941
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1942
            auto sub_res2 =
2✔
1943
                subs2.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1944

1945
            check_status(sub_res);
2✔
1946
            check_status(sub_res2);
2✔
1947

1948
            CHECK(realm->get_active_subscription_set().version() == 0);
2!
1949
            CHECK(realm->get_latest_subscription_set().version() == 2);
2!
1950
        });
2✔
1951
    }
2✔
1952

1953
    // Test for issue #6839, where wait for download after committing a new subscription and then
1954
    // wait for the subscription complete notification was leading to a garbage reason value in the
1955
    // status provided to the subscription complete callback.
1956
    SECTION("Download during bad query") {
8✔
1957
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
1958
            // Wait for steady state before committing the new subscription
1959
            REQUIRE(!wait_for_download(*realm));
2!
1960

1961
            auto subs = create_subscription(realm, "class_TopLevel", "non_queryable_field", [](auto q, auto c) {
2✔
1962
                return q.equal(c, "bar");
2✔
1963
            });
2✔
1964
            // Wait for download is actually waiting for the subscription to be applied after it was committed
1965
            REQUIRE(!wait_for_download(*realm));
2!
1966
            // After subscription is complete or fails during wait for download, this function completes
1967
            // without blocking
1968
            auto result = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
1969
            // Verify error occurred
1970
            check_status(result);
2✔
1971
        });
2✔
1972
    }
2✔
1973

1974
    // Add new sections before this
1975
    SECTION("teardown") {
8✔
1976
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
1977
        harness.reset();
2✔
1978
    }
2✔
1979
}
8✔
1980

1981
#if REALM_ENABLE_GEOSPATIAL
1982
TEST_CASE("flx: geospatial", "[sync][flx][geospatial][baas]") {
6✔
1983
    static std::optional<FLXSyncTestHarness> harness;
6✔
1984
    if (!harness) {
6✔
1985
        Schema schema{
2✔
1986
            {"restaurant",
2✔
1987
             {
2✔
1988
                 {"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
1989
                 {"queryable_str_field", PropertyType::String},
2✔
1990
                 {"location", PropertyType::Object | PropertyType::Nullable, "geoPointType"},
2✔
1991
                 {"array", PropertyType::Object | PropertyType::Array, "geoPointType"},
2✔
1992
             }},
2✔
1993
            {"geoPointType",
2✔
1994
             ObjectSchema::ObjectType::Embedded,
2✔
1995
             {
2✔
1996
                 {"type", PropertyType::String},
2✔
1997
                 {"coordinates", PropertyType::Double | PropertyType::Array},
2✔
1998
             }},
2✔
1999
        };
2✔
2000
        FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field", "location"}};
2✔
2001
        harness.emplace("flx_geospatial", server_schema);
2✔
2002
    }
2✔
2003

2004
    auto create_subscription = [](SharedRealm realm, StringData table_name, StringData column_name, auto make_query) {
18✔
2005
        auto table = realm->read_group().get_table(table_name);
18✔
2006
        auto queryable_field = table->get_column_key(column_name);
18✔
2007
        auto new_query = realm->get_active_subscription_set().make_mutable_copy();
18✔
2008
        new_query.insert_or_assign(make_query(Query(table), queryable_field));
18✔
2009
        return new_query.commit();
18✔
2010
    };
18✔
2011

2012
    SECTION("Server supports a basic geowithin FLX query") {
6✔
2013
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
2014
            const realm::AppSession& app_session = harness->session().app_session();
2✔
2015
            auto sync_service = app_session.admin_api.get_sync_service(app_session.server_app_id);
2✔
2016

2017
            AdminAPISession::ServiceConfig config =
2✔
2018
                app_session.admin_api.get_config(app_session.server_app_id, sync_service);
2✔
2019
            auto subs = create_subscription(realm, "class_restaurant", "location", [](Query q, ColKey c) {
2✔
2020
                GeoBox area{GeoPoint{0.2, 0.2}, GeoPoint{0.7, 0.7}};
2✔
2021
                Query query = q.get_table()->column<Link>(c).geo_within(area);
2✔
2022
                std::string ser = query.get_description();
2✔
2023
                return query;
2✔
2024
            });
2✔
2025
            auto sub_res = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
2✔
2026
            CHECK(sub_res.is_ok());
2!
2027
            CHECK(realm->get_active_subscription_set().version() == 1);
2!
2028
            CHECK(realm->get_latest_subscription_set().version() == 1);
2!
2029
        });
2✔
2030
    }
2✔
2031

2032
    SECTION("geospatial query consistency: local/server/FLX") {
6✔
2033
        harness->do_with_new_user([&](std::shared_ptr<SyncUser> user) {
2✔
2034
            SyncTestFile config(user, harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
2035
            auto error_pf = util::make_promise_future<SyncError>();
2✔
2036
            config.sync_config->error_handler =
2✔
2037
                [promise = std::make_shared<util::Promise<SyncError>>(std::move(error_pf.promise))](
2✔
2038
                    std::shared_ptr<SyncSession>, SyncError error) {
2✔
2039
                    promise->emplace_value(std::move(error));
2✔
2040
                };
2✔
2041

2042
            auto realm = Realm::get_shared_realm(config);
2✔
2043

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

2106
            CppContext c(realm);
2✔
2107
            int64_t pk = 0;
2✔
2108
            auto add_point = [&](GeoPoint p) {
16✔
2109
                Object::create(
16✔
2110
                    c, realm, "restaurant",
16✔
2111
                    std::any(AnyDict{
16✔
2112
                        {"_id", ++pk},
16✔
2113
                        {"queryable_str_field", "synced"s},
16✔
2114
                        {"location", AnyDict{{"type", "Point"s},
16✔
2115
                                             {"coordinates", std::vector<std::any>{p.longitude, p.latitude}}}}}));
16✔
2116
            };
16✔
2117
            std::vector<GeoPoint> points = {
2✔
2118
                GeoPoint{-74.006, 40.712800000000001},            // New York city
2✔
2119
                GeoPoint{12.568300000000001, 55.676099999999998}, // Copenhagen
2✔
2120
                GeoPoint{12.082599999999999, 55.628},             // ragnarok, Roskilde
2✔
2121
                GeoPoint{-180.1, -90.1},                          // invalid
2✔
2122
                GeoPoint{0, 90},                                  // north pole
2✔
2123
                GeoPoint{-82.68193, 84.74653},                    // northern point that falls within a box later
2✔
2124
                GeoPoint{82.55243, 84.54981}, // another northern point, but on the other side of the pole
2✔
2125
                GeoPoint{2129, 89},           // invalid
2✔
2126
            };
2✔
2127
            constexpr size_t invalids_to_be_compensated = 2; // 4, 8
2✔
2128
            realm->begin_transaction();
2✔
2129
            for (auto& point : points) {
16✔
2130
                add_point(point);
16✔
2131
            }
16✔
2132
            realm->commit_transaction();
2✔
2133
            const auto& error = error_pf.future.get();
2✔
2134
            REQUIRE(!error.is_fatal);
2!
2135
            REQUIRE(error.status == ErrorCodes::SyncCompensatingWrite);
2!
2136
            REQUIRE(error.compensating_writes_info.size() == invalids_to_be_compensated);
2!
2137
            REQUIRE_THAT(error.compensating_writes_info[0].reason,
2✔
2138
                         Catch::Matchers::ContainsSubstring("in table \"restaurant\" will corrupt geojson data"));
2✔
2139
            REQUIRE_THAT(error.compensating_writes_info[1].reason,
2✔
2140
                         Catch::Matchers::ContainsSubstring("in table \"restaurant\" will corrupt geojson data"));
2✔
2141

2142
            {
2✔
2143
                auto table = realm->read_group().get_table("class_restaurant");
2✔
2144
                CHECK(table->size() == points.size());
2!
2145
                Obj obj = table->get_object_with_primary_key(Mixed{1});
2✔
2146
                REQUIRE(obj);
2!
2147
                Geospatial geo = obj.get<Geospatial>("location");
2✔
2148
                REQUIRE(geo.get_type_string() == "Point");
2!
2149
                REQUIRE(geo.get_type() == Geospatial::Type::Point);
2!
2150
                GeoPoint point = geo.get<GeoPoint>();
2✔
2151
                REQUIRE(point.longitude == points[0].longitude);
2!
2152
                REQUIRE(point.latitude == points[0].latitude);
2!
2153
                REQUIRE(!point.get_altitude());
2!
2154
                ColKey location_col = table->get_column_key("location");
2✔
2155
                auto run_query_locally = [&table, &location_col](Geospatial bounds) -> size_t {
26✔
2156
                    Query query = table->column<Link>(location_col).geo_within(Geospatial(bounds));
26✔
2157
                    return query.find_all().size();
26✔
2158
                };
26✔
2159
                auto run_query_as_flx = [&](Geospatial bounds) -> size_t {
14✔
2160
                    size_t num_objects = 0;
14✔
2161
                    harness->do_with_new_realm([&](SharedRealm realm) {
14✔
2162
                        auto subs =
14✔
2163
                            create_subscription(realm, "class_restaurant", "location", [&](Query q, ColKey c) {
14✔
2164
                                return q.get_table()->column<Link>(c).geo_within(Geospatial(bounds));
14✔
2165
                            });
14✔
2166
                        auto sub_res =
14✔
2167
                            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get_no_throw();
14✔
2168
                        CHECK(sub_res.is_ok());
14!
2169
                        CHECK(realm->get_active_subscription_set().version() == 1);
14!
2170
                        realm->refresh();
14✔
2171
                        num_objects = realm->get_class("restaurant").num_objects();
14✔
2172
                    });
14✔
2173
                    return num_objects;
14✔
2174
                };
14✔
2175

2176
                reset_utils::wait_for_num_objects_in_atlas(harness->app()->current_user(),
2✔
2177
                                                           harness->session().app_session(), "restaurant",
2✔
2178
                                                           points.size() - invalids_to_be_compensated);
2✔
2179

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

2275
    // Add new sections before this
2276
    SECTION("teardown") {
6✔
2277
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
2278
        harness.reset();
2✔
2279
    }
2✔
2280
}
6✔
2281
#endif // REALM_ENABLE_GEOSPATIAL
2282

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

2286
    std::vector<ObjectId> obj_ids_at_end = fill_large_array_schema(harness);
2✔
2287
    SyncTestFile interrupted_realm_config(harness.app()->current_user(), harness.schema(),
2✔
2288
                                          SyncConfig::FLXSyncEnabled{});
2✔
2289

2290
    {
2✔
2291
        auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2292
        Realm::Config config = interrupted_realm_config;
2✔
2293
        config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2294
        auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
2295
        config.sync_config->on_sync_client_event_hook =
2✔
2296
            [promise = std::move(shared_promise), seen_version_one = false](std::weak_ptr<SyncSession> weak_session,
2✔
2297
                                                                            const SyncClientHookData& data) mutable {
24✔
2298
                if (data.event != SyncClientHookEvent::DownloadMessageReceived) {
24✔
2299
                    return SyncClientHookAction::NoAction;
16✔
2300
                }
16✔
2301

2302
                auto session = weak_session.lock();
8✔
2303
                if (!session) {
8✔
2304
                    return SyncClientHookAction::NoAction;
×
2305
                }
×
2306

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

2312
                REQUIRE(data.query_version == 1);
2!
2313
                REQUIRE(data.batch_state == sync::DownloadBatchState::MoreToCome);
2!
2314
                auto latest_subs = session->get_flx_subscription_store()->get_latest();
2✔
2315
                REQUIRE(latest_subs.version() == 1);
2!
2316
                REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::Bootstrapping);
2!
2317

2318
                session->close();
2✔
2319
                promise->emplace_value();
2✔
2320

2321
                return SyncClientHookAction::TriggerReconnect;
2✔
2322
            };
2✔
2323

2324
        auto realm = Realm::get_shared_realm(config);
2✔
2325
        {
2✔
2326
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2327
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
2328
            mut_subs.insert_or_assign(Query(table));
2✔
2329
            mut_subs.commit();
2✔
2330
        }
2✔
2331

2332
        interrupted.get();
2✔
2333
        realm->sync_session()->shutdown_and_wait();
2✔
2334
    }
2✔
2335

2336
    _impl::RealmCoordinator::assert_no_open_realms();
2✔
2337

2338
    {
2✔
2339
        DBOptions options;
2✔
2340
        options.encryption_key = test_util::crypt_key();
2✔
2341
        auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
2342
        auto sub_store = sync::SubscriptionStore::create(realm);
2✔
2343
        auto version_info = sub_store->get_version_info();
2✔
2344
        REQUIRE(version_info.active == 0);
2!
2345
        REQUIRE(version_info.latest == 1);
2!
2346
        auto latest_subs = sub_store->get_latest();
2✔
2347
        REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::Bootstrapping);
2!
2348
        REQUIRE(latest_subs.size() == 1);
2!
2349
        REQUIRE(latest_subs.at(0).object_class_name == "TopLevel");
2!
2350
    }
2✔
2351

2352
    auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
2353
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
2354
    realm->get_latest_subscription_set().get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2355
    wait_for_advance(*realm);
2✔
2356
    REQUIRE(table->size() == obj_ids_at_end.size());
2!
2357
    for (auto& id : obj_ids_at_end) {
10✔
2358
        REQUIRE(table->find_primary_key(Mixed{id}));
10!
2359
    }
10✔
2360

2361
    auto active_subs = realm->get_active_subscription_set();
2✔
2362
    auto latest_subs = realm->get_latest_subscription_set();
2✔
2363
    REQUIRE(active_subs.version() == latest_subs.version());
2!
2364
    REQUIRE(active_subs.version() == int64_t(1));
2!
2365
}
2✔
2366

2367
TEST_CASE("flx: dev mode uploads schema before query change", "[sync][flx][query][baas]") {
2✔
2368
    FLXSyncTestHarness::ServerSchema server_schema;
2✔
2369
    auto default_schema = FLXSyncTestHarness::default_server_schema();
2✔
2370
    server_schema.queryable_fields = default_schema.queryable_fields;
2✔
2371
    server_schema.dev_mode_enabled = true;
2✔
2372
    server_schema.schema = Schema{};
2✔
2373

2374
    FLXSyncTestHarness harness("flx_dev_mode", server_schema);
2✔
2375
    auto foo_obj_id = ObjectId::gen();
2✔
2376
    auto bar_obj_id = ObjectId::gen();
2✔
2377
    harness.do_with_new_realm(
2✔
2378
        [&](SharedRealm realm) {
2✔
2379
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
2380
            // auto queryable_str_field = table->get_column_key("queryable_str_field");
2381
            // auto queryable_int_field = table->get_column_key("queryable_int_field");
2382
            auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2383
            new_query.insert_or_assign(Query(table));
2✔
2384
            new_query.commit();
2✔
2385

2386
            CppContext c(realm);
2✔
2387
            realm->begin_transaction();
2✔
2388
            Object::create(c, realm, "TopLevel",
2✔
2389
                           std::any(AnyDict{{"_id", foo_obj_id},
2✔
2390
                                            {"queryable_str_field", "foo"s},
2✔
2391
                                            {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2392
                                            {"non_queryable_field", "non queryable 1"s}}));
2✔
2393
            Object::create(c, realm, "TopLevel",
2✔
2394
                           std::any(AnyDict{{"_id", bar_obj_id},
2✔
2395
                                            {"queryable_str_field", "bar"s},
2✔
2396
                                            {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2397
                                            {"non_queryable_field", "non queryable 2"s}}));
2✔
2398
            realm->commit_transaction();
2✔
2399

2400
            wait_for_upload(*realm);
2✔
2401
        },
2✔
2402
        default_schema.schema);
2✔
2403

2404
    harness.do_with_new_realm(
2✔
2405
        [&](SharedRealm realm) {
2✔
2406
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
2407
            auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
2408
            auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2409
            new_query.insert_or_assign(Query(table).greater_equal(queryable_int_field, int64_t(5)));
2✔
2410
            auto subs = new_query.commit();
2✔
2411
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2412
            wait_for_download(*realm);
2✔
2413
            Results results(realm, table);
2✔
2414

2415
            realm->refresh();
2✔
2416
            CHECK(results.size() == 2);
2!
2417
            CHECK(table->get_object_with_primary_key({foo_obj_id}).is_valid());
2!
2418
            CHECK(table->get_object_with_primary_key({bar_obj_id}).is_valid());
2!
2419
        },
2✔
2420
        default_schema.schema);
2✔
2421
}
2✔
2422

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

2427
    // first we create an object on the server and upload it.
2428
    auto foo_obj_id = ObjectId::gen();
2✔
2429
    harness.load_initial_data([&](SharedRealm realm) {
2✔
2430
        CppContext c(realm);
2✔
2431
        Object::create(c, realm, "TopLevel",
2✔
2432
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
2433
                                        {"queryable_str_field", "foo"s},
2✔
2434
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2435
                                        {"non_queryable_field", "created as initial data seed"s}}));
2✔
2436
    });
2✔
2437

2438
    // Now create another realm and wait for it to be fully synchronized with bootstrap version zero. i.e.
2439
    // our progress counters should be past the history entry containing the object created above.
2440
    auto test_file_config = harness.make_test_file();
2✔
2441
    auto realm = Realm::get_shared_realm(test_file_config);
2✔
2442
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
2443
    auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
2444

2445
    realm->get_latest_subscription_set().get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2446
    wait_for_upload(*realm);
2✔
2447
    wait_for_download(*realm);
2✔
2448

2449
    // Now disconnect the sync session
2450
    realm->sync_session()->pause();
2✔
2451

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

2457
    realm->begin_transaction();
2✔
2458
    CppContext c(realm);
2✔
2459
    Object::create(c, realm, "TopLevel",
2✔
2460
                   std::any(AnyDict{{"_id", foo_obj_id},
2✔
2461
                                    {"queryable_str_field", "foo"s},
2✔
2462
                                    {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2463
                                    {"non_queryable_field", "created locally"s}}));
2✔
2464
    realm->commit_transaction();
2✔
2465

2466
    // Reconnect the sync session and wait for the subscription that moved "foo" into view to be fully synchronized.
2467
    realm->sync_session()->resume();
2✔
2468
    wait_for_upload(*realm);
2✔
2469
    wait_for_download(*realm);
2✔
2470
    subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2471

2472
    wait_for_advance(*realm);
2✔
2473

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

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

2485
        auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any{foo_obj_id});
2✔
2486
        REQUIRE(obj.get_obj().get<int64_t>("queryable_int_field") == 5);
2!
2487
        REQUIRE(obj.get_obj().get<StringData>("non_queryable_field") == "created as initial data seed");
2!
2488
    });
2✔
2489
}
2✔
2490

2491
TEST_CASE("flx: writes work offline", "[sync][flx][baas]") {
2✔
2492
    FLXSyncTestHarness harness("flx_offline_writes");
2✔
2493

2494
    harness.do_with_new_realm([&](SharedRealm realm) {
2✔
2495
        auto sync_session = realm->sync_session();
2✔
2496
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
2497
        auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
2498
        auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
2499
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2500
        new_query.insert_or_assign(Query(table));
2✔
2501
        new_query.commit();
2✔
2502

2503
        auto foo_obj_id = ObjectId::gen();
2✔
2504
        auto bar_obj_id = ObjectId::gen();
2✔
2505

2506
        CppContext c(realm);
2✔
2507
        realm->begin_transaction();
2✔
2508
        Object::create(c, realm, "TopLevel",
2✔
2509
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
2510
                                        {"queryable_str_field", "foo"s},
2✔
2511
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2512
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
2513
        Object::create(c, realm, "TopLevel",
2✔
2514
                       std::any(AnyDict{{"_id", bar_obj_id},
2✔
2515
                                        {"queryable_str_field", "bar"s},
2✔
2516
                                        {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2517
                                        {"non_queryable_field", "non queryable 2"s}}));
2✔
2518
        realm->commit_transaction();
2✔
2519

2520
        wait_for_upload(*realm);
2✔
2521
        wait_for_download(*realm);
2✔
2522
        sync_session->pause();
2✔
2523

2524
        // Make it so the subscriptions only match the "foo" object
2525
        {
2✔
2526
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2527
            mut_subs.clear();
2✔
2528
            mut_subs.insert_or_assign(Query(table).equal(queryable_str_field, "foo"));
2✔
2529
            mut_subs.commit();
2✔
2530
        }
2✔
2531

2532
        // Make foo so that it will match the next subscription update. This checks whether you can do
2533
        // multiple subscription set updates offline and that the last one eventually takes effect when
2534
        // you come back online and fully synchronize.
2535
        {
2✔
2536
            Results results(realm, table);
2✔
2537
            realm->begin_transaction();
2✔
2538
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2539
            foo_obj.set<int64_t>(queryable_int_field, 15);
2✔
2540
            realm->commit_transaction();
2✔
2541
        }
2✔
2542

2543
        // Update our subscriptions so that both foo/bar will be included
2544
        {
2✔
2545
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2546
            mut_subs.clear();
2✔
2547
            mut_subs.insert_or_assign(Query(table).greater_equal(queryable_int_field, static_cast<int64_t>(10)));
2✔
2548
            mut_subs.commit();
2✔
2549
        }
2✔
2550

2551
        // Make foo out of view for the current subscription.
2552
        {
2✔
2553
            Results results(realm, table);
2✔
2554
            realm->begin_transaction();
2✔
2555
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2556
            foo_obj.set<int64_t>(queryable_int_field, 0);
2✔
2557
            realm->commit_transaction();
2✔
2558
        }
2✔
2559

2560
        sync_session->resume();
2✔
2561
        wait_for_upload(*realm);
2✔
2562
        wait_for_download(*realm);
2✔
2563

2564
        realm->refresh();
2✔
2565
        Results results(realm, table);
2✔
2566
        CHECK(results.size() == 1);
2!
2567
        CHECK(table->get_object_with_primary_key({bar_obj_id}).is_valid());
2!
2568
    });
2✔
2569
}
2✔
2570

2571
TEST_CASE("flx: writes work without waiting for sync", "[sync][flx][baas]") {
2✔
2572
    FLXSyncTestHarness harness("flx_offline_writes");
2✔
2573

2574
    harness.do_with_new_realm([&](SharedRealm realm) {
2✔
2575
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
2576
        auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
2577
        auto queryable_int_field = table->get_column_key("queryable_int_field");
2✔
2578
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2579
        new_query.insert_or_assign(Query(table));
2✔
2580
        new_query.commit();
2✔
2581

2582
        auto foo_obj_id = ObjectId::gen();
2✔
2583
        auto bar_obj_id = ObjectId::gen();
2✔
2584

2585
        CppContext c(realm);
2✔
2586
        realm->begin_transaction();
2✔
2587
        Object::create(c, realm, "TopLevel",
2✔
2588
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
2589
                                        {"queryable_str_field", "foo"s},
2✔
2590
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
2591
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
2592
        Object::create(c, realm, "TopLevel",
2✔
2593
                       std::any(AnyDict{{"_id", bar_obj_id},
2✔
2594
                                        {"queryable_str_field", "bar"s},
2✔
2595
                                        {"queryable_int_field", static_cast<int64_t>(10)},
2✔
2596
                                        {"non_queryable_field", "non queryable 2"s}}));
2✔
2597
        realm->commit_transaction();
2✔
2598

2599
        wait_for_upload(*realm);
2✔
2600

2601
        // Make it so the subscriptions only match the "foo" object
2602
        {
2✔
2603
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2604
            mut_subs.clear();
2✔
2605
            mut_subs.insert_or_assign(Query(table).equal(queryable_str_field, "foo"));
2✔
2606
            mut_subs.commit();
2✔
2607
        }
2✔
2608

2609
        // Make foo so that it will match the next subscription update. This checks whether you can do
2610
        // multiple subscription set updates without waiting and that the last one eventually takes effect when
2611
        // you fully synchronize.
2612
        {
2✔
2613
            Results results(realm, table);
2✔
2614
            realm->begin_transaction();
2✔
2615
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2616
            foo_obj.set<int64_t>(queryable_int_field, 15);
2✔
2617
            realm->commit_transaction();
2✔
2618
        }
2✔
2619

2620
        // Update our subscriptions so that both foo/bar will be included
2621
        {
2✔
2622
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2623
            mut_subs.clear();
2✔
2624
            mut_subs.insert_or_assign(Query(table).greater_equal(queryable_int_field, static_cast<int64_t>(10)));
2✔
2625
            mut_subs.commit();
2✔
2626
        }
2✔
2627

2628
        // Make foo out-of-view for the current subscription.
2629
        {
2✔
2630
            Results results(realm, table);
2✔
2631
            realm->begin_transaction();
2✔
2632
            auto foo_obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
2633
            foo_obj.set<int64_t>(queryable_int_field, 0);
2✔
2634
            realm->commit_transaction();
2✔
2635
        }
2✔
2636

2637
        wait_for_upload(*realm);
2✔
2638
        wait_for_download(*realm);
2✔
2639

2640
        realm->refresh();
2✔
2641
        Results results(realm, table);
2✔
2642
        CHECK(results.size() == 1);
2!
2643
        Obj obj = results.get(0);
2✔
2644
        CHECK(obj.get_primary_key().get_object_id() == bar_obj_id);
2!
2645
        CHECK(table->get_object_with_primary_key({bar_obj_id}).is_valid());
2!
2646
    });
2✔
2647
}
2✔
2648

2649
TEST_CASE("flx: verify websocket protocol number and prefixes", "[sync][protocol]") {
2✔
2650
    // Update the expected value whenever the protocol version is updated - this ensures
2651
    // that the current protocol version does not change unexpectedly.
2652
    REQUIRE(12 == sync::get_current_protocol_version());
2✔
2653
    // This was updated in Protocol V8 to use '#' instead of '/' to support the Web SDK
2654
    REQUIRE("com.mongodb.realm-sync#" == sync::get_pbs_websocket_protocol_prefix());
2✔
2655
    REQUIRE("com.mongodb.realm-query-sync#" == sync::get_flx_websocket_protocol_prefix());
2✔
2656
}
2✔
2657

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

2664
    {
2✔
2665
        auto orig_realm = Realm::get_shared_realm(config);
2✔
2666
        auto mut_subs = orig_realm->get_latest_subscription_set().make_mutable_copy();
2✔
2667
        mut_subs.insert_or_assign(Query(orig_realm->read_group().get_table("class_TopLevel")));
2✔
2668
        mut_subs.commit();
2✔
2669
        orig_realm->close();
2✔
2670
    }
2✔
2671

2672
    {
2✔
2673
        auto new_realm = Realm::get_shared_realm(config);
2✔
2674
        auto latest_subs = new_realm->get_latest_subscription_set();
2✔
2675
        CHECK(latest_subs.size() == 1);
2!
2676
        latest_subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
2677
    }
2✔
2678
}
2✔
2679
#endif
2680

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

2686
    auto realm = Realm::get_shared_realm(config);
2✔
2687
    CHECK(!wait_for_download(*realm));
2!
2688
    CHECK(!wait_for_upload(*realm));
2!
2689

2690
    CHECK(!realm->sync_session()->get_flx_subscription_store());
2!
2691

2692
    CHECK_THROWS_AS(realm->get_active_subscription_set(), IllegalOperation);
2✔
2693
    CHECK_THROWS_AS(realm->get_latest_subscription_set(), IllegalOperation);
2✔
2694
}
2✔
2695

2696
TEST_CASE("flx: connect to FLX as PBS returns an error", "[sync][flx][baas]") {
2✔
2697
    FLXSyncTestHarness harness("connect_to_flx_as_pbs");
2✔
2698
    SyncTestFile config(harness.app()->current_user(), bson::Bson{}, harness.schema());
2✔
2699
    std::mutex sync_error_mutex;
2✔
2700
    util::Optional<SyncError> sync_error;
2✔
2701
    config.sync_config->error_handler = [&](std::shared_ptr<SyncSession>, SyncError error) mutable {
2✔
2702
        std::lock_guard<std::mutex> lk(sync_error_mutex);
2✔
2703
        sync_error = std::move(error);
2✔
2704
    };
2✔
2705
    auto realm = Realm::get_shared_realm(config);
2✔
2706
    timed_wait_for([&] {
4,733✔
2707
        std::lock_guard<std::mutex> lk(sync_error_mutex);
4,733✔
2708
        return static_cast<bool>(sync_error);
4,733✔
2709
    });
4,733✔
2710

2711
    CHECK(sync_error->status == ErrorCodes::WrongSyncType);
2!
2712
    CHECK(sync_error->server_requests_action == sync::ProtocolErrorInfo::Action::ApplicationBug);
2!
2713
}
2✔
2714

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

2720
    REQUIRE_EXCEPTION(Realm::get_shared_realm(config), IllegalCombination,
2✔
2721
                      "Cannot specify a partition value when flexible sync is enabled");
2✔
2722
}
2✔
2723

2724
TEST_CASE("flx: connect to PBS as FLX returns an error", "[sync][flx][protocol][baas]") {
2✔
2725
    auto server_app_config = minimal_app_config("flx_connect_as_pbs", g_minimal_schema);
2✔
2726
    TestAppSession session(create_app(server_app_config));
2✔
2727
    auto app = session.app();
2✔
2728
    auto user = app->current_user();
2✔
2729

2730
    SyncTestFile config(user, g_minimal_schema, SyncConfig::FLXSyncEnabled{});
2✔
2731

2732
    std::mutex sync_error_mutex;
2✔
2733
    util::Optional<SyncError> sync_error;
2✔
2734
    config.sync_config->error_handler = [&](std::shared_ptr<SyncSession>, SyncError error) mutable {
2✔
2735
        std::lock_guard lk(sync_error_mutex);
2✔
2736
        sync_error = std::move(error);
2✔
2737
    };
2✔
2738
    auto realm = Realm::get_shared_realm(config);
2✔
2739
    timed_wait_for([&] {
21,056✔
2740
        std::lock_guard lk(sync_error_mutex);
21,056✔
2741
        return static_cast<bool>(sync_error);
21,056✔
2742
    });
21,056✔
2743

2744
    CHECK(sync_error->status == ErrorCodes::WrongSyncType);
2!
2745
    CHECK(sync_error->server_requests_action == sync::ProtocolErrorInfo::Action::ApplicationBug);
2!
2746
}
2✔
2747

2748
TEST_CASE("flx: commit subscription while refreshing the access token", "[sync][flx][token][baas]") {
2✔
2749
    auto transport = std::make_shared<HookedTransport<>>();
2✔
2750
    FLXSyncTestHarness harness("flx_wait_access_token2", FLXSyncTestHarness::default_server_schema(), transport);
2✔
2751
    auto app = harness.app();
2✔
2752
    std::shared_ptr<User> user = app->current_user();
2✔
2753
    REQUIRE(user);
2!
2754
    REQUIRE(!user->access_token_refresh_required());
2!
2755
    // Set a bad access token, with an expired time. This will trigger a refresh initiated by the client.
2756
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2✔
2757
    using namespace std::chrono_literals;
2✔
2758
    auto expires = std::chrono::system_clock::to_time_t(now - 30s);
2✔
2759
    user->update_data_for_testing([&](UserData& data) {
2✔
2760
        data.access_token = RealmJWT(encode_fake_jwt("fake_access_token", expires));
2✔
2761
    });
2✔
2762
    REQUIRE(user->access_token_refresh_required());
2!
2763

2764
    bool seen_waiting_for_access_token = false;
2✔
2765
    // Commit a subcription set while there is no sync session.
2766
    // A session is created when the access token is refreshed.
2767
    transport->request_hook = [&](const Request&) {
2✔
2768
        auto user = app->current_user();
2✔
2769
        REQUIRE(user);
2!
2770
        for (auto& session : app->sync_manager()->get_all_sessions_for(*user)) {
2✔
2771
            if (session->state() == SyncSession::State::WaitingForAccessToken) {
2✔
2772
                REQUIRE(!seen_waiting_for_access_token);
2!
2773
                seen_waiting_for_access_token = true;
2✔
2774

2775
                auto store = session->get_flx_subscription_store();
2✔
2776
                REQUIRE(store);
2!
2777
                auto mut_subs = store->get_latest().make_mutable_copy();
2✔
2778
                mut_subs.commit();
2✔
2779
            }
2✔
2780
        }
2✔
2781
        return std::nullopt;
2✔
2782
    };
2✔
2783
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
2784
    // This triggers the token refresh.
2785
    auto r = Realm::get_shared_realm(config);
2✔
2786
    REQUIRE(seen_waiting_for_access_token);
2!
2787
}
2✔
2788

2789
TEST_CASE("flx: bootstrap batching prevents orphan documents", "[sync][flx][bootstrap][baas]") {
8✔
2790
    struct NovelException : public std::exception {
8✔
2791
        const char* what() const noexcept override
8✔
2792
        {
8✔
2793
            return "Oh no, a really weird exception happened!";
2✔
2794
        }
2✔
2795
    };
8✔
2796

2797
    FLXSyncTestHarness harness("flx_bootstrap_batching", {g_large_array_schema, {"queryable_int_field"}});
8✔
2798

2799
    std::vector<ObjectId> obj_ids_at_end = fill_large_array_schema(harness);
8✔
2800
    SyncTestFile interrupted_realm_config(harness.app()->current_user(), harness.schema(),
8✔
2801
                                          SyncConfig::FLXSyncEnabled{});
8✔
2802

2803
    auto check_interrupted_state = [&](const DBRef& realm) {
8✔
2804
        auto tr = realm->start_read();
8✔
2805
        auto top_level = tr->get_table("class_TopLevel");
8✔
2806
        REQUIRE(top_level);
8!
2807
        REQUIRE(top_level->is_empty());
8!
2808

2809
        auto sub_store = sync::SubscriptionStore::create(realm);
8✔
2810
        auto version_info = sub_store->get_version_info();
8✔
2811
        REQUIRE(version_info.latest == 1);
8!
2812
        REQUIRE(version_info.active == 0);
8!
2813
        auto latest_subs = sub_store->get_latest();
8✔
2814
        REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::Bootstrapping);
8!
2815
        REQUIRE(latest_subs.size() == 1);
8!
2816
        REQUIRE(latest_subs.at(0).object_class_name == "TopLevel");
8!
2817
    };
8✔
2818

2819
    auto mutate_realm = [&] {
8✔
2820
        harness.load_initial_data([&](SharedRealm realm) {
4✔
2821
            auto table = realm->read_group().get_table("class_TopLevel");
4✔
2822
            Results res(realm, Query(table).greater(table->get_column_key("queryable_int_field"), int64_t(10)));
4✔
2823
            REQUIRE(res.size() == 2);
4!
2824
            res.clear();
4✔
2825
        });
4✔
2826
    };
4✔
2827

2828
    SECTION("unknown exception occurs during bootstrap application on session startup") {
8✔
2829
        {
2✔
2830
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2831
            Realm::Config config = interrupted_realm_config;
2✔
2832
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2833
            auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
2834
            config.sync_config->on_sync_client_event_hook =
2✔
2835
                [promise = std::move(shared_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
2836
                                                      const SyncClientHookData& data) mutable {
42✔
2837
                    if (data.event != SyncClientHookEvent::BootstrapMessageProcessed) {
42✔
2838
                        return SyncClientHookAction::NoAction;
28✔
2839
                    }
28✔
2840
                    auto session = weak_session.lock();
14✔
2841
                    if (!session) {
14✔
2842
                        return SyncClientHookAction::NoAction;
×
2843
                    }
×
2844

2845
                    if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::LastInBatch) {
14✔
2846
                        session->close();
2✔
2847
                        promise->emplace_value();
2✔
2848
                        return SyncClientHookAction::EarlyReturn;
2✔
2849
                    }
2✔
2850
                    return SyncClientHookAction::NoAction;
12✔
2851
                };
14✔
2852
            auto realm = Realm::get_shared_realm(config);
2✔
2853
            {
2✔
2854
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2855
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
2856
                mut_subs.insert_or_assign(Query(table));
2✔
2857
                mut_subs.commit();
2✔
2858
            }
2✔
2859

2860
            interrupted.get();
2✔
2861
            realm->sync_session()->shutdown_and_wait();
2✔
2862
            realm->close();
2✔
2863
        }
2✔
2864

2865
        _impl::RealmCoordinator::assert_no_open_realms();
2✔
2866

2867
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
2868
        // we expected it to be in.
2869
        {
2✔
2870
            DBOptions options;
2✔
2871
            options.encryption_key = test_util::crypt_key();
2✔
2872
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
2873
            auto logger = util::Logger::get_default_logger();
2✔
2874
            sync::PendingBootstrapStore bootstrap_store(realm, *logger);
2✔
2875
            REQUIRE(bootstrap_store.has_pending());
2!
2876
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
2877
            REQUIRE(pending_batch.query_version == 1);
2!
2878
            REQUIRE(pending_batch.progress);
2!
2879

2880
            check_interrupted_state(realm);
2✔
2881
        }
2✔
2882

2883
        auto error_pf = util::make_promise_future<SyncError>();
2✔
2884
        interrupted_realm_config.sync_config->error_handler =
2✔
2885
            [promise = std::make_shared<util::Promise<SyncError>>(std::move(error_pf.promise))](
2✔
2886
                std::shared_ptr<SyncSession>, SyncError error) {
2✔
2887
                promise->emplace_value(std::move(error));
2✔
2888
            };
2✔
2889

2890
        interrupted_realm_config.sync_config->on_sync_client_event_hook =
2✔
2891
            [&, download_message_received = false](std::weak_ptr<SyncSession>,
2✔
2892
                                                   const SyncClientHookData& data) mutable {
6✔
2893
                if (data.event == SyncClientHookEvent::DownloadMessageReceived) {
6✔
2894
                    download_message_received = true;
×
2895
                }
×
2896
                if (data.event != SyncClientHookEvent::BootstrapBatchAboutToProcess) {
6✔
2897
                    return SyncClientHookAction::NoAction;
4✔
2898
                }
4✔
2899

2900
                REQUIRE(!download_message_received);
2!
2901
                throw NovelException{};
2✔
2902
                return SyncClientHookAction::NoAction;
×
2903
            };
2✔
2904

2905
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
2906
        const auto& error = error_pf.future.get();
2✔
2907
        REQUIRE(!error.is_fatal);
2!
2908
        REQUIRE(error.server_requests_action == sync::ProtocolErrorInfo::Action::Warning);
2!
2909
        REQUIRE(error.status == ErrorCodes::UnknownError);
2!
2910
        REQUIRE_THAT(error.status.reason(),
2✔
2911
                     Catch::Matchers::ContainsSubstring("Oh no, a really weird exception happened!"));
2✔
2912
    }
2✔
2913

2914
    SECTION("exception occurs during bootstrap application") {
8✔
2915
        Status error_status(ErrorCodes::OutOfMemory, "no more memory!");
2✔
2916
        {
2✔
2917
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2918
            Realm::Config config = interrupted_realm_config;
2✔
2919
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2920
            config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_session,
2✔
2921
                                                                const SyncClientHookData& data) mutable {
44✔
2922
                if (data.event != SyncClientHookEvent::BootstrapBatchAboutToProcess) {
44✔
2923
                    return SyncClientHookAction::NoAction;
40✔
2924
                }
40✔
2925
                auto session = weak_session.lock();
4✔
2926
                if (!session) {
4✔
2927
                    return SyncClientHookAction::NoAction;
×
2928
                }
×
2929

2930
                if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::MoreToCome) {
4✔
2931
                    throw sync::IntegrationException(error_status);
2✔
2932
                }
2✔
2933
                return SyncClientHookAction::NoAction;
2✔
2934
            };
4✔
2935
            auto error_pf = util::make_promise_future<SyncError>();
2✔
2936
            config.sync_config->error_handler =
2✔
2937
                [promise = std::make_shared<util::Promise<SyncError>>(std::move(error_pf.promise))](
2✔
2938
                    std::shared_ptr<SyncSession>, SyncError error) {
2✔
2939
                    promise->emplace_value(std::move(error));
2✔
2940
                };
2✔
2941

2942

2943
            auto realm = Realm::get_shared_realm(config);
2✔
2944
            {
2✔
2945
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
2946
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
2947
                mut_subs.insert_or_assign(Query(table));
2✔
2948
                mut_subs.commit();
2✔
2949
            }
2✔
2950

2951
            auto error = error_pf.future.get();
2✔
2952
            REQUIRE(error.status.reason() == error_status.reason());
2!
2953
            REQUIRE(error.status == error_status);
2!
2954
            realm->sync_session()->shutdown_and_wait();
2✔
2955
            realm->close();
2✔
2956
        }
2✔
2957

2958
        _impl::RealmCoordinator::assert_no_open_realms();
2✔
2959

2960
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
2961
        // we expected it to be in.
2962
        {
2✔
2963
            DBOptions options;
2✔
2964
            options.encryption_key = test_util::crypt_key();
2✔
2965
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
2966
            util::StderrLogger logger;
2✔
2967
            sync::PendingBootstrapStore bootstrap_store(realm, logger);
2✔
2968
            REQUIRE(bootstrap_store.has_pending());
2!
2969
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
2970
            REQUIRE(pending_batch.query_version == 1);
2!
2971
            REQUIRE(pending_batch.progress);
2!
2972

2973
            check_interrupted_state(realm);
2✔
2974
        }
2✔
2975

2976
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
2977
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
2978
        realm->get_latest_subscription_set()
2✔
2979
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
2980
            .get();
2✔
2981

2982
        wait_for_advance(*realm);
2✔
2983

2984
        REQUIRE(table->size() == obj_ids_at_end.size());
2!
2985
        for (auto& id : obj_ids_at_end) {
10✔
2986
            REQUIRE(table->find_primary_key(Mixed{id}));
10!
2987
        }
10✔
2988
    }
2✔
2989

2990
    SECTION("interrupted before final bootstrap message") {
8✔
2991
        {
2✔
2992
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
2993
            Realm::Config config = interrupted_realm_config;
2✔
2994
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
2995
            auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
2996
            config.sync_config->on_sync_client_event_hook =
2✔
2997
                [promise = std::move(shared_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
2998
                                                      const SyncClientHookData& data) mutable {
22✔
2999
                    if (data.event != SyncClientHookEvent::BootstrapMessageProcessed) {
22✔
3000
                        return SyncClientHookAction::NoAction;
18✔
3001
                    }
18✔
3002
                    auto session = weak_session.lock();
4✔
3003
                    if (!session) {
4✔
3004
                        return SyncClientHookAction::NoAction;
×
3005
                    }
×
3006

3007
                    if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::MoreToCome) {
4✔
3008
                        session->force_close();
2✔
3009
                        promise->emplace_value();
2✔
3010
                        return SyncClientHookAction::TriggerReconnect;
2✔
3011
                    }
2✔
3012
                    return SyncClientHookAction::NoAction;
2✔
3013
                };
4✔
3014
            auto realm = Realm::get_shared_realm(config);
2✔
3015
            {
2✔
3016
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3017
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
3018
                mut_subs.insert_or_assign(Query(table));
2✔
3019
                mut_subs.commit();
2✔
3020
            }
2✔
3021

3022
            interrupted.get();
2✔
3023
            realm->sync_session()->shutdown_and_wait();
2✔
3024
            realm->close();
2✔
3025
        }
2✔
3026

3027
        _impl::RealmCoordinator::assert_no_open_realms();
2✔
3028

3029
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
3030
        // we expected it to be in.
3031
        {
2✔
3032
            DBOptions options;
2✔
3033
            options.encryption_key = test_util::crypt_key();
2✔
3034
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
3035
            auto logger = util::Logger::get_default_logger();
2✔
3036
            sync::PendingBootstrapStore bootstrap_store(realm, *logger);
2✔
3037
            REQUIRE(bootstrap_store.has_pending());
2!
3038
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
3039
            REQUIRE(pending_batch.query_version == 1);
2!
3040
            REQUIRE(!pending_batch.progress);
2!
3041
            REQUIRE(pending_batch.remaining_changesets == 0);
2!
3042
            REQUIRE(pending_batch.changesets.size() == 1);
2!
3043

3044
            check_interrupted_state(realm);
2✔
3045
        }
2✔
3046

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

3051
        // Finally re-open the realm whose bootstrap we interrupted and just wait for it to finish downloading.
3052
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
3053
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
3054
        realm->get_latest_subscription_set()
2✔
3055
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
3056
            .get();
2✔
3057

3058
        wait_for_advance(*realm);
2✔
3059
        auto expected_obj_ids = util::Span<ObjectId>(obj_ids_at_end).sub_span(0, 3);
2✔
3060

3061
        REQUIRE(table->size() == expected_obj_ids.size());
2!
3062
        for (auto& id : expected_obj_ids) {
6✔
3063
            REQUIRE(table->find_primary_key(Mixed{id}));
6!
3064
        }
6✔
3065
    }
2✔
3066

3067
    SECTION("interrupted after final bootstrap message before processing") {
8✔
3068
        {
2✔
3069
            auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
3070
            Realm::Config config = interrupted_realm_config;
2✔
3071
            config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
3072
            auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
3073
            config.sync_config->on_sync_client_event_hook =
2✔
3074
                [promise = std::move(shared_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
3075
                                                      const SyncClientHookData& data) mutable {
42✔
3076
                    if (data.event != SyncClientHookEvent::BootstrapMessageProcessed) {
42✔
3077
                        return SyncClientHookAction::NoAction;
28✔
3078
                    }
28✔
3079
                    auto session = weak_session.lock();
14✔
3080
                    if (!session) {
14✔
3081
                        return SyncClientHookAction::NoAction;
×
3082
                    }
×
3083

3084
                    if (data.query_version == 1 && data.batch_state == sync::DownloadBatchState::LastInBatch) {
14✔
3085
                        session->force_close();
2✔
3086
                        promise->emplace_value();
2✔
3087
                        return SyncClientHookAction::TriggerReconnect;
2✔
3088
                    }
2✔
3089
                    return SyncClientHookAction::NoAction;
12✔
3090
                };
14✔
3091
            auto realm = Realm::get_shared_realm(config);
2✔
3092
            {
2✔
3093
                auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3094
                auto table = realm->read_group().get_table("class_TopLevel");
2✔
3095
                mut_subs.insert_or_assign(Query(table));
2✔
3096
                mut_subs.commit();
2✔
3097
            }
2✔
3098

3099
            interrupted.get();
2✔
3100
            realm->sync_session()->shutdown_and_wait();
2✔
3101
            realm->close();
2✔
3102
        }
2✔
3103

3104
        _impl::RealmCoordinator::assert_no_open_realms();
2✔
3105

3106
        // Open up the realm without the sync client attached and verify that the realm got interrupted in the state
3107
        // we expected it to be in.
3108
        {
2✔
3109
            DBOptions options;
2✔
3110
            options.encryption_key = test_util::crypt_key();
2✔
3111
            auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
3112
            auto logger = util::Logger::get_default_logger();
2✔
3113
            sync::PendingBootstrapStore bootstrap_store(realm, *logger);
2✔
3114
            REQUIRE(bootstrap_store.has_pending());
2!
3115
            auto pending_batch = bootstrap_store.peek_pending(1024 * 1024 * 16);
2✔
3116
            REQUIRE(pending_batch.query_version == 1);
2!
3117
            REQUIRE(static_cast<bool>(pending_batch.progress));
2!
3118
            REQUIRE(pending_batch.remaining_changesets == 0);
2!
3119
            REQUIRE(pending_batch.changesets.size() == 6);
2!
3120

3121
            check_interrupted_state(realm);
2✔
3122
        }
2✔
3123

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

3128
        auto [saw_valid_state_promise, saw_valid_state_future] = util::make_promise_future<void>();
2✔
3129
        auto shared_saw_valid_state_promise =
2✔
3130
            std::make_shared<decltype(saw_valid_state_promise)>(std::move(saw_valid_state_promise));
2✔
3131
        // This hook will let us check what the state of the realm is before it's integrated any new download
3132
        // messages from the server. This should be the full 5 object bootstrap that was received before we
3133
        // called mutate_realm().
3134
        interrupted_realm_config.sync_config->on_sync_client_event_hook =
2✔
3135
            [&, promise = std::move(shared_saw_valid_state_promise)](std::weak_ptr<SyncSession> weak_session,
2✔
3136
                                                                     const SyncClientHookData& data) {
34✔
3137
                if (data.event != SyncClientHookEvent::DownloadMessageReceived) {
34✔
3138
                    return SyncClientHookAction::NoAction;
32✔
3139
                }
32✔
3140
                auto session = weak_session.lock();
2✔
3141
                if (!session) {
2✔
3142
                    return SyncClientHookAction::NoAction;
×
3143
                }
×
3144

3145
                if (data.query_version != 1 || data.batch_state == sync::DownloadBatchState::MoreToCome) {
2✔
3146
                    return SyncClientHookAction::NoAction;
×
3147
                }
×
3148

3149
                auto latest_sub_set = session->get_flx_subscription_store()->get_latest();
2✔
3150
                auto active_sub_set = session->get_flx_subscription_store()->get_active();
2✔
3151
                auto version_info = session->get_flx_subscription_store()->get_version_info();
2✔
3152
                REQUIRE(version_info.pending_mark == active_sub_set.version());
2!
3153
                REQUIRE(version_info.active == active_sub_set.version());
2!
3154
                REQUIRE(version_info.latest == latest_sub_set.version());
2!
3155
                REQUIRE(latest_sub_set.version() == active_sub_set.version());
2!
3156
                REQUIRE(active_sub_set.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3157

3158
                auto db = SyncSession::OnlyForTesting::get_db(*session);
2✔
3159
                auto tr = db->start_read();
2✔
3160

3161
                auto table = tr->get_table("class_TopLevel");
2✔
3162
                REQUIRE(table->size() == obj_ids_at_end.size());
2!
3163
                for (auto& id : obj_ids_at_end) {
10✔
3164
                    REQUIRE(table->find_primary_key(Mixed{id}));
10!
3165
                }
10✔
3166

3167
                promise->emplace_value();
2✔
3168
                return SyncClientHookAction::NoAction;
2✔
3169
            };
2✔
3170

3171
        // Finally re-open the realm whose bootstrap we interrupted and just wait for it to finish downloading.
3172
        auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
3173
        saw_valid_state_future.get();
2✔
3174
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
3175
        realm->get_latest_subscription_set()
2✔
3176
            .get_state_change_notification(sync::SubscriptionSet::State::Complete)
2✔
3177
            .get();
2✔
3178

3179
        wait_for_advance(*realm);
2✔
3180
        auto expected_obj_ids = util::Span<ObjectId>(obj_ids_at_end).sub_span(0, 3);
2✔
3181

3182
        // After we've downloaded all the mutations there should only by 3 objects left.
3183
        REQUIRE(table->size() == expected_obj_ids.size());
2!
3184
        for (auto& id : expected_obj_ids) {
6✔
3185
            REQUIRE(table->find_primary_key(Mixed{id}));
6!
3186
        }
6✔
3187
    }
2✔
3188
}
8✔
3189

3190
// Check that a document with the given id is present and has the expected fields
3191
static void check_document(const std::vector<bson::BsonDocument>& documents, ObjectId id,
3192
                           std::initializer_list<std::pair<const char*, bson::Bson>> fields)
3193
{
428✔
3194
    auto it = std::find_if(documents.begin(), documents.end(), [&](auto&& doc) {
43,096✔
3195
        auto val = doc.find("_id");
43,096✔
3196
        REQUIRE(val);
43,096!
3197
        return *val == id;
43,096✔
3198
    });
43,096✔
3199
    REQUIRE(it != documents.end());
428!
3200
    auto& doc = *it;
428✔
3201
    for (auto& [name, expected_value] : fields) {
434✔
3202
        auto val = doc.find(name);
434✔
3203
        REQUIRE(val);
434!
3204

3205
        // bson documents are ordered  but Realm dictionaries aren't, so the
3206
        // document might validly be in a different order than we expected and
3207
        // we need to do a comparison that doesn't check order.
3208
        if (expected_value.type() == bson::Bson::Type::Document) {
434✔
3209
            REQUIRE(static_cast<const bson::BsonDocument&>(*val) ==
8!
3210
                    static_cast<const bson::BsonDocument&>(expected_value));
8✔
3211
        }
8✔
3212
        else {
426✔
3213
            REQUIRE(*val == expected_value);
426!
3214
        }
426✔
3215
    }
434✔
3216
}
428✔
3217

3218
TEST_CASE("flx: data ingest", "[sync][flx][data ingest][baas]") {
22✔
3219
    using namespace ::realm::bson;
22✔
3220

3221
    static auto server_schema = [] {
22✔
3222
        FLXSyncTestHarness::ServerSchema server_schema;
2✔
3223
        server_schema.queryable_fields = {"queryable_str_field"};
2✔
3224
        server_schema.schema = {
2✔
3225
            {"Asymmetric",
2✔
3226
             ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3227
             {
2✔
3228
                 {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3229
                 {"location", PropertyType::String | PropertyType::Nullable},
2✔
3230
                 {"embedded obj", PropertyType::Object | PropertyType::Nullable, "Embedded"},
2✔
3231
                 {"embedded list", PropertyType::Object | PropertyType::Array, "Embedded"},
2✔
3232
                 {"embedded dictionary", PropertyType::Object | PropertyType::Nullable | PropertyType::Dictionary,
2✔
3233
                  "Embedded"},
2✔
3234
                 {"link obj", PropertyType::Object | PropertyType::Nullable, "TopLevel"},
2✔
3235
                 {"link list", PropertyType::Object | PropertyType::Array, "TopLevel"},
2✔
3236
                 {"link dictionary", PropertyType::Object | PropertyType::Nullable | PropertyType::Dictionary,
2✔
3237
                  "TopLevel"},
2✔
3238
             }},
2✔
3239
            {"Embedded", ObjectSchema::ObjectType::Embedded, {{"value", PropertyType::String}}},
2✔
3240
            {"TopLevel",
2✔
3241
             {
2✔
3242
                 {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3243
                 {"value", PropertyType::Int},
2✔
3244
             }},
2✔
3245
        };
2✔
3246
        return server_schema;
2✔
3247
    }();
2✔
3248
    static auto harness = std::make_unique<FLXSyncTestHarness>("asymmetric_sync", server_schema);
22✔
3249

3250
    // We reuse a single app for each section, so tests will see the documents
3251
    // created by previous tests and we need to add those documents to the count
3252
    // we're waiting for
3253
    static std::unordered_map<std::string, size_t> previous_count;
22✔
3254
    auto get_documents = [&](const char* name, size_t expected_count) {
22✔
3255
        auto& count = previous_count[name];
18✔
3256
        auto documents =
18✔
3257
            harness->session().get_documents(*harness->app()->current_user(), name, count + expected_count);
18✔
3258
        count = documents.size();
18✔
3259
        return documents;
18✔
3260
    };
18✔
3261

3262
    SECTION("basic object construction") {
22✔
3263
        auto foo_obj_id = ObjectId::gen();
2✔
3264
        auto bar_obj_id = ObjectId::gen();
2✔
3265
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3266
            realm->begin_transaction();
2✔
3267
            CppContext c(realm);
2✔
3268
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "foo"s}}));
2✔
3269
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", bar_obj_id}, {"location", "bar"s}}));
2✔
3270
            realm->commit_transaction();
2✔
3271

3272
            auto documents = get_documents("Asymmetric", 2);
2✔
3273
            check_document(documents, foo_obj_id, {{"location", "foo"}});
2✔
3274
            check_document(documents, bar_obj_id, {{"location", "bar"}});
2✔
3275
        });
2✔
3276

3277
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3278
            wait_for_download(*realm);
2✔
3279

3280
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3281
            REQUIRE(table->size() == 0);
2!
3282
            // Cannot query asymmetric tables.
3283
            CHECK_THROWS_AS(Query(table), LogicError);
2✔
3284
        });
2✔
3285
    }
2✔
3286

3287
    SECTION("do not allow objects with same key within the same transaction") {
22✔
3288
        auto foo_obj_id = ObjectId::gen();
2✔
3289
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3290
            realm->begin_transaction();
2✔
3291
            CppContext c(realm);
2✔
3292
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "foo"s}}));
2✔
3293
            CHECK_THROWS_WITH(
2✔
3294
                Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "bar"s}})),
2✔
3295
                "Attempting to create an object of type 'Asymmetric' with an existing primary key value 'not "
2✔
3296
                "implemented'");
2✔
3297
            realm->commit_transaction();
2✔
3298

3299
            auto documents = get_documents("Asymmetric", 1);
2✔
3300
            check_document(documents, foo_obj_id, {{"location", "foo"}});
2✔
3301
        });
2✔
3302
    }
2✔
3303

3304
    SECTION("create multiple objects - separate commits") {
22✔
3305
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3306
            CppContext c(realm);
2✔
3307
            std::vector<ObjectId> obj_ids;
2✔
3308
            for (int i = 0; i < 100; ++i) {
202✔
3309
                realm->begin_transaction();
200✔
3310
                obj_ids.push_back(ObjectId::gen());
200✔
3311
                Object::create(c, realm, "Asymmetric",
200✔
3312
                               std::any(AnyDict{
200✔
3313
                                   {"_id", obj_ids.back()},
200✔
3314
                                   {"location", util::format("foo_%1", i)},
200✔
3315
                               }));
200✔
3316
                realm->commit_transaction();
200✔
3317
            }
200✔
3318

3319
            wait_for_upload(*realm);
2✔
3320
            wait_for_download(*realm);
2✔
3321

3322
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3323
            REQUIRE(table->size() == 0);
2!
3324

3325
            auto documents = get_documents("Asymmetric", 100);
2✔
3326
            for (int i = 0; i < 100; ++i) {
202✔
3327
                check_document(documents, obj_ids[i], {{"location", util::format("foo_%1", i)}});
200✔
3328
            }
200✔
3329
        });
2✔
3330
    }
2✔
3331

3332
    SECTION("create multiple objects - same commit") {
22✔
3333
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3334
            CppContext c(realm);
2✔
3335
            realm->begin_transaction();
2✔
3336
            std::vector<ObjectId> obj_ids;
2✔
3337
            for (int i = 0; i < 100; ++i) {
202✔
3338
                obj_ids.push_back(ObjectId::gen());
200✔
3339
                Object::create(c, realm, "Asymmetric",
200✔
3340
                               std::any(AnyDict{
200✔
3341
                                   {"_id", obj_ids.back()},
200✔
3342
                                   {"location", util::format("bar_%1", i)},
200✔
3343
                               }));
200✔
3344
            }
200✔
3345
            realm->commit_transaction();
2✔
3346

3347
            wait_for_upload(*realm);
2✔
3348
            wait_for_download(*realm);
2✔
3349

3350
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3351
            REQUIRE(table->size() == 0);
2!
3352

3353
            auto documents = get_documents("Asymmetric", 100);
2✔
3354
            for (int i = 0; i < 100; ++i) {
202✔
3355
                check_document(documents, obj_ids[i], {{"location", util::format("bar_%1", i)}});
200✔
3356
            }
200✔
3357
        });
2✔
3358
    }
2✔
3359

3360
    SECTION("open with schema mismatch on IsAsymmetric") {
22✔
3361
        auto schema = server_schema.schema;
2✔
3362
        schema.find("Asymmetric")->table_type = ObjectSchema::ObjectType::TopLevel;
2✔
3363

3364
        harness->do_with_new_user([&](std::shared_ptr<SyncUser> user) {
2✔
3365
            SyncTestFile config(user, schema, SyncConfig::FLXSyncEnabled{});
2✔
3366
            auto [error_promise, error_future] = util::make_promise_future<SyncError>();
2✔
3367
            auto error_count = 0;
2✔
3368
            auto err_handler = [promise = util::CopyablePromiseHolder(std::move(error_promise)),
2✔
3369
                                &error_count](std::shared_ptr<SyncSession>, SyncError err) mutable {
4✔
3370
                ++error_count;
4✔
3371
                if (error_count == 1) {
4✔
3372
                    // Bad changeset detected by the client.
3373
                    CHECK(err.status == ErrorCodes::BadChangeset);
2!
3374
                }
2✔
3375
                else if (error_count == 2) {
2✔
3376
                    // Server asking for a client reset.
3377
                    CHECK(err.status == ErrorCodes::SyncClientResetRequired);
2!
3378
                    CHECK(err.is_client_reset_requested());
2!
3379
                    promise.get_promise().emplace_value(std::move(err));
2✔
3380
                }
2✔
3381
            };
4✔
3382

3383
            config.sync_config->error_handler = err_handler;
2✔
3384
            auto realm = Realm::get_shared_realm(config);
2✔
3385

3386
            auto err = error_future.get();
2✔
3387
            CHECK(error_count == 2);
2!
3388
        });
2✔
3389
    }
2✔
3390

3391
    SECTION("basic embedded object construction") {
22✔
3392
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3393
            auto obj_id = ObjectId::gen();
2✔
3394
            realm->begin_transaction();
2✔
3395
            CppContext c(realm);
2✔
3396
            Object::create(c, realm, "Asymmetric",
2✔
3397
                           std::any(AnyDict{
2✔
3398
                               {"_id", obj_id},
2✔
3399
                               {"embedded obj", AnyDict{{"value", "foo"s}}},
2✔
3400
                           }));
2✔
3401
            realm->commit_transaction();
2✔
3402
            wait_for_upload(*realm);
2✔
3403

3404
            auto documents = get_documents("Asymmetric", 1);
2✔
3405
            check_document(documents, obj_id, {{"embedded obj", BsonDocument{{"value", "foo"}}}});
2✔
3406
        });
2✔
3407

3408
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3409
            wait_for_download(*realm);
2✔
3410

3411
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3412
            REQUIRE(table->size() == 0);
2!
3413
        });
2✔
3414
    }
2✔
3415

3416
    SECTION("replace embedded object") {
22✔
3417
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3418
            CppContext c(realm);
2✔
3419
            auto foo_obj_id = ObjectId::gen();
2✔
3420

3421
            realm->begin_transaction();
2✔
3422
            Object::create(c, realm, "Asymmetric",
2✔
3423
                           std::any(AnyDict{
2✔
3424
                               {"_id", foo_obj_id},
2✔
3425
                               {"embedded obj", AnyDict{{"value", "foo"s}}},
2✔
3426
                           }));
2✔
3427
            realm->commit_transaction();
2✔
3428

3429
            // Update embedded field to `null`. The server discards this write
3430
            // as asymmetric sync can only create new objects.
3431
            realm->begin_transaction();
2✔
3432
            Object::create(c, realm, "Asymmetric",
2✔
3433
                           std::any(AnyDict{
2✔
3434
                               {"_id", foo_obj_id},
2✔
3435
                               {"embedded obj", std::any()},
2✔
3436
                           }));
2✔
3437
            realm->commit_transaction();
2✔
3438

3439
            // create a second object so that we can know when the translator
3440
            // has processed everything
3441
            realm->begin_transaction();
2✔
3442
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", ObjectId::gen()}, {}}));
2✔
3443
            realm->commit_transaction();
2✔
3444

3445
            wait_for_upload(*realm);
2✔
3446
            wait_for_download(*realm);
2✔
3447

3448
            auto table = realm->read_group().get_table("class_Asymmetric");
2✔
3449
            REQUIRE(table->size() == 0);
2!
3450

3451
            auto documents = get_documents("Asymmetric", 2);
2✔
3452
            check_document(documents, foo_obj_id, {{"embedded obj", BsonDocument{{"value", "foo"}}}});
2✔
3453
        });
2✔
3454
    }
2✔
3455

3456
    SECTION("embedded collections") {
22✔
3457
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3458
            CppContext c(realm);
2✔
3459
            auto obj_id = ObjectId::gen();
2✔
3460

3461
            realm->begin_transaction();
2✔
3462
            Object::create(c, realm, "Asymmetric",
2✔
3463
                           std::any(AnyDict{
2✔
3464
                               {"_id", obj_id},
2✔
3465
                               {"embedded list", AnyVector{AnyDict{{"value", "foo"s}}, AnyDict{{"value", "bar"s}}}},
2✔
3466
                               {"embedded dictionary",
2✔
3467
                                AnyDict{
2✔
3468
                                    {"key1", AnyDict{{"value", "foo"s}}},
2✔
3469
                                    {"key2", AnyDict{{"value", "bar"s}}},
2✔
3470
                                }},
2✔
3471
                           }));
2✔
3472
            realm->commit_transaction();
2✔
3473

3474
            auto documents = get_documents("Asymmetric", 1);
2✔
3475
            check_document(
2✔
3476
                documents, obj_id,
2✔
3477
                {
2✔
3478
                    {"embedded list", BsonArray{BsonDocument{{"value", "foo"}}, BsonDocument{{"value", "bar"}}}},
2✔
3479
                    {"embedded dictionary",
2✔
3480
                     BsonDocument{
2✔
3481
                         {"key1", BsonDocument{{"value", "foo"}}},
2✔
3482
                         {"key2", BsonDocument{{"value", "bar"}}},
2✔
3483
                     }},
2✔
3484
                });
2✔
3485
        });
2✔
3486
    }
2✔
3487

3488
    SECTION("asymmetric table not allowed in PBS") {
22✔
3489
        Schema schema{
2✔
3490
            {"Asymmetric2",
2✔
3491
             ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3492
             {
2✔
3493
                 {"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
3494
                 {"location", PropertyType::Int},
2✔
3495
                 {"reading", PropertyType::Int},
2✔
3496
             }},
2✔
3497
        };
2✔
3498

3499
        SyncTestFile config(harness->app()->current_user(), Bson{}, schema);
2✔
3500
        REQUIRE_EXCEPTION(
2✔
3501
            Realm::get_shared_realm(config), SchemaValidationFailed,
2✔
3502
            Catch::Matchers::ContainsSubstring("Asymmetric table 'Asymmetric2' not allowed in partition based sync"));
2✔
3503
    }
2✔
3504

3505
    SECTION("links to top-level objects") {
22✔
3506
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3507
            subscribe_to_all_and_bootstrap(*realm);
2✔
3508

3509
            ObjectId obj_id = ObjectId::gen();
2✔
3510
            std::array<ObjectId, 5> target_obj_ids;
2✔
3511
            for (auto& id : target_obj_ids) {
10✔
3512
                id = ObjectId::gen();
10✔
3513
            }
10✔
3514

3515
            realm->begin_transaction();
2✔
3516
            CppContext c(realm);
2✔
3517
            Object::create(c, realm, "Asymmetric",
2✔
3518
                           std::any(AnyDict{
2✔
3519
                               {"_id", obj_id},
2✔
3520
                               {"link obj", AnyDict{{"_id", target_obj_ids[0]}, {"value", INT64_C(10)}}},
2✔
3521
                               {"link list",
2✔
3522
                                AnyVector{
2✔
3523
                                    AnyDict{{"_id", target_obj_ids[1]}, {"value", INT64_C(11)}},
2✔
3524
                                    AnyDict{{"_id", target_obj_ids[2]}, {"value", INT64_C(12)}},
2✔
3525
                                }},
2✔
3526
                               {"link dictionary",
2✔
3527
                                AnyDict{
2✔
3528
                                    {"key1", AnyDict{{"_id", target_obj_ids[3]}, {"value", INT64_C(13)}}},
2✔
3529
                                    {"key2", AnyDict{{"_id", target_obj_ids[4]}, {"value", INT64_C(14)}}},
2✔
3530
                                }},
2✔
3531
                           }));
2✔
3532
            realm->commit_transaction();
2✔
3533
            wait_for_upload(*realm);
2✔
3534

3535
            auto docs1 = get_documents("Asymmetric", 1);
2✔
3536
            check_document(docs1, obj_id,
2✔
3537
                           {{"link obj", target_obj_ids[0]},
2✔
3538
                            {"link list", BsonArray{{target_obj_ids[1], target_obj_ids[2]}}},
2✔
3539
                            {
2✔
3540
                                "link dictionary",
2✔
3541
                                BsonDocument{
2✔
3542
                                    {"key1", target_obj_ids[3]},
2✔
3543
                                    {"key2", target_obj_ids[4]},
2✔
3544
                                },
2✔
3545
                            }});
2✔
3546

3547
            auto docs2 = get_documents("TopLevel", 5);
2✔
3548
            for (int64_t i = 0; i < 5; ++i) {
12✔
3549
                check_document(docs2, target_obj_ids[i], {{"value", 10 + i}});
10✔
3550
            }
10✔
3551
        });
2✔
3552
    }
2✔
3553

3554
    // Add any new test sections above this point
3555

3556
    SECTION("teardown") {
22✔
3557
        harness.reset();
2✔
3558
    }
2✔
3559
}
22✔
3560

3561
TEST_CASE("flx: data ingest - dev mode", "[sync][flx][data ingest][baas]") {
2✔
3562
    FLXSyncTestHarness::ServerSchema server_schema;
2✔
3563
    server_schema.dev_mode_enabled = true;
2✔
3564
    server_schema.schema = Schema{};
2✔
3565

3566
    auto schema = Schema{{"Asymmetric",
2✔
3567
                          ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3568
                          {
2✔
3569
                              {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3570
                              {"location", PropertyType::String | PropertyType::Nullable},
2✔
3571
                          }},
2✔
3572
                         {"TopLevel",
2✔
3573
                          {
2✔
3574
                              {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3575
                              {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
3576
                          }}};
2✔
3577

3578
    FLXSyncTestHarness harness("asymmetric_sync", server_schema);
2✔
3579

3580
    auto foo_obj_id = ObjectId::gen();
2✔
3581
    auto bar_obj_id = ObjectId::gen();
2✔
3582

3583
    harness.do_with_new_realm(
2✔
3584
        [&](SharedRealm realm) {
2✔
3585
            CppContext c(realm);
2✔
3586
            realm->begin_transaction();
2✔
3587
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", foo_obj_id}, {"location", "foo"s}}));
2✔
3588
            Object::create(c, realm, "Asymmetric", std::any(AnyDict{{"_id", bar_obj_id}, {"location", "bar"s}}));
2✔
3589
            realm->commit_transaction();
2✔
3590
            User* user = dynamic_cast<User*>(realm->config().sync_config->user.get());
2✔
3591
            REALM_ASSERT(user);
2✔
3592
            auto docs = harness.session().get_documents(*user, "Asymmetric", 2);
2✔
3593
            check_document(docs, foo_obj_id, {{"location", "foo"}});
2✔
3594
            check_document(docs, bar_obj_id, {{"location", "bar"}});
2✔
3595
        },
2✔
3596
        schema);
2✔
3597
}
2✔
3598

3599
TEST_CASE("flx: data ingest - write not allowed", "[sync][flx][data ingest][baas]") {
2✔
3600
    AppCreateConfig::ServiceRole role;
2✔
3601
    role.name = "asymmetric_write_perms";
2✔
3602

3603
    AppCreateConfig::ServiceRoleDocumentFilters doc_filters;
2✔
3604
    doc_filters.read = true;
2✔
3605
    doc_filters.write = false;
2✔
3606
    role.document_filters = doc_filters;
2✔
3607

3608
    role.insert_filter = true;
2✔
3609
    role.delete_filter = true;
2✔
3610
    role.read = true;
2✔
3611
    role.write = true;
2✔
3612

3613
    Schema schema({
2✔
3614
        {"Asymmetric",
2✔
3615
         ObjectSchema::ObjectType::TopLevelAsymmetric,
2✔
3616
         {
2✔
3617
             {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
3618
             {"location", PropertyType::String | PropertyType::Nullable},
2✔
3619
             {"embedded_obj", PropertyType::Object | PropertyType::Nullable, "Embedded"},
2✔
3620
         }},
2✔
3621
        {"Embedded",
2✔
3622
         ObjectSchema::ObjectType::Embedded,
2✔
3623
         {
2✔
3624
             {"value", PropertyType::String | PropertyType::Nullable},
2✔
3625
         }},
2✔
3626
    });
2✔
3627
    FLXSyncTestHarness::ServerSchema server_schema{schema, {}, {role}};
2✔
3628
    FLXSyncTestHarness harness("asymmetric_sync", server_schema);
2✔
3629

3630
    auto error_received_pf = util::make_promise_future<void>();
2✔
3631
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3632
    config.sync_config->on_sync_client_event_hook =
2✔
3633
        [promise = util::CopyablePromiseHolder(std::move(error_received_pf.promise))](
2✔
3634
            std::weak_ptr<SyncSession> weak_session, const SyncClientHookData& data) mutable {
22✔
3635
            if (data.event != SyncClientHookEvent::ErrorMessageReceived) {
22✔
3636
                return SyncClientHookAction::NoAction;
18✔
3637
            }
18✔
3638
            auto session = weak_session.lock();
4✔
3639
            REQUIRE(session);
4!
3640

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

3643
            if (error_code == sync::ProtocolError::initial_sync_not_completed) {
4✔
3644
                return SyncClientHookAction::NoAction;
2✔
3645
            }
2✔
3646

3647
            REQUIRE(error_code == sync::ProtocolError::write_not_allowed);
2!
3648
            REQUIRE_FALSE(data.error_info->compensating_write_server_version.has_value());
2!
3649
            REQUIRE_FALSE(data.error_info->compensating_writes.empty());
2!
3650
            promise.get_promise().emplace_value();
2✔
3651

3652
            return SyncClientHookAction::EarlyReturn;
2✔
3653
        };
2✔
3654

3655
    auto realm = Realm::get_shared_realm(config);
2✔
3656

3657
    // Create an asymmetric object and upload it to the server.
3658
    {
2✔
3659
        realm->begin_transaction();
2✔
3660
        CppContext c(realm);
2✔
3661
        Object::create(c, realm, "Asymmetric",
2✔
3662
                       std::any(AnyDict{{"_id", ObjectId::gen()}, {"embedded_obj", AnyDict{{"value", "foo"s}}}}));
2✔
3663
        realm->commit_transaction();
2✔
3664
    }
2✔
3665

3666
    error_received_pf.future.get();
2✔
3667
    realm->close();
2✔
3668
}
2✔
3669

3670
TEST_CASE("flx: send client error", "[sync][flx][baas]") {
2✔
3671
    FLXSyncTestHarness harness("flx_client_error");
2✔
3672

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

3678
    auto [error_promise, error_future] = util::make_promise_future<SyncError>();
2✔
3679
    auto error_count = 0;
2✔
3680
    auto err_handler = [promise = util::CopyablePromiseHolder(std::move(error_promise)),
2✔
3681
                        &error_count](std::shared_ptr<SyncSession>, SyncError err) mutable {
4✔
3682
        ++error_count;
4✔
3683
        if (error_count == 1) {
4✔
3684
            // Bad changeset detected by the client.
3685
            CHECK(err.status == ErrorCodes::BadChangeset);
2!
3686
        }
2✔
3687
        else if (error_count == 2) {
2✔
3688
            // Server asking for a client reset.
3689
            CHECK(err.status == ErrorCodes::SyncClientResetRequired);
2!
3690
            CHECK(err.is_client_reset_requested());
2!
3691
            promise.get_promise().emplace_value(std::move(err));
2✔
3692
        }
2✔
3693
    };
4✔
3694

3695
    config.sync_config->error_handler = err_handler;
2✔
3696
    auto realm = Realm::get_shared_realm(config);
2✔
3697
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
3698
    auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3699
    new_query.insert_or_assign(Query(table));
2✔
3700
    new_query.commit();
2✔
3701

3702
    auto err = error_future.get();
2✔
3703
    CHECK(error_count == 2);
2!
3704
}
2✔
3705

3706
TEST_CASE("flx: bootstraps contain all changes", "[sync][flx][bootstrap][baas]") {
6✔
3707
    FLXSyncTestHarness harness("bootstrap_full_sync");
6✔
3708

3709
    auto setup_subs = [](SharedRealm& realm) {
12✔
3710
        auto table = realm->read_group().get_table("class_TopLevel");
12✔
3711
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
12✔
3712
        new_query.clear();
12✔
3713
        auto col = table->get_column_key("queryable_str_field");
12✔
3714
        new_query.insert_or_assign(Query(table).equal(col, StringData("bar")).Or().equal(col, StringData("bizz")));
12✔
3715
        return new_query.commit();
12✔
3716
    };
12✔
3717

3718
    auto bar_obj_id = ObjectId::gen();
6✔
3719
    auto bizz_obj_id = ObjectId::gen();
6✔
3720
    auto setup_and_poison_cache = [&] {
6✔
3721
        harness.load_initial_data([&](SharedRealm realm) {
6✔
3722
            CppContext c(realm);
6✔
3723
            Object::create(c, realm, "TopLevel",
6✔
3724
                           std::any(AnyDict{{"_id", bar_obj_id},
6✔
3725
                                            {"queryable_str_field", std::string{"bar"}},
6✔
3726
                                            {"queryable_int_field", static_cast<int64_t>(10)},
6✔
3727
                                            {"non_queryable_field", std::string{"non queryable 2"}}}));
6✔
3728
        });
6✔
3729

3730
        harness.do_with_new_realm([&](SharedRealm realm) {
6✔
3731
            // first set a subscription to force the creation/caching of a broker snapshot on the server.
3732
            setup_subs(realm).get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
6✔
3733
            wait_for_advance(*realm);
6✔
3734
            auto table = realm->read_group().get_table("class_TopLevel");
6✔
3735
            REQUIRE(table->find_primary_key(bar_obj_id));
6!
3736

3737
            // Then create an object that won't be in the cached snapshot - this is the object that if we didn't
3738
            // wait for a MARK message to come back, we'd miss it in our results.
3739
            CppContext c(realm);
6✔
3740
            realm->begin_transaction();
6✔
3741
            Object::create(c, realm, "TopLevel",
6✔
3742
                           std::any(AnyDict{{"_id", bizz_obj_id},
6✔
3743
                                            {"queryable_str_field", std::string{"bizz"}},
6✔
3744
                                            {"queryable_int_field", static_cast<int64_t>(15)},
6✔
3745
                                            {"non_queryable_field", std::string{"non queryable 3"}}}));
6✔
3746
            realm->commit_transaction();
6✔
3747
            wait_for_upload(*realm);
6✔
3748
        });
6✔
3749
    };
6✔
3750

3751
    SECTION("regular subscription change") {
6✔
3752
        SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3753
        std::atomic<bool> saw_truncated_bootstrap{false};
2✔
3754
        triggered_config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_sess,
2✔
3755
                                                                      const SyncClientHookData& data) {
32✔
3756
            auto sess = weak_sess.lock();
32✔
3757
            if (!sess || data.event != SyncClientHookEvent::BootstrapProcessed || data.query_version != 1) {
32✔
3758
                return SyncClientHookAction::NoAction;
30✔
3759
            }
30✔
3760

3761
            auto latest_subs = sess->get_flx_subscription_store()->get_latest();
2✔
3762
            REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3763
            REQUIRE(data.num_changesets == 1);
2!
3764
            auto db = SyncSession::OnlyForTesting::get_db(*sess);
2✔
3765
            auto read_tr = db->start_read();
2✔
3766
            auto table = read_tr->get_table("class_TopLevel");
2✔
3767
            REQUIRE(table->find_primary_key(bar_obj_id));
2!
3768
            REQUIRE_FALSE(table->find_primary_key(bizz_obj_id));
2!
3769
            saw_truncated_bootstrap.store(true);
2✔
3770

3771
            return SyncClientHookAction::NoAction;
2✔
3772
        };
2✔
3773
        auto problem_realm = Realm::get_shared_realm(triggered_config);
2✔
3774

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

3781
        nlohmann::json command_request = {
2✔
3782
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
3783
        };
2✔
3784
        auto resp_body =
2✔
3785
            SyncSession::OnlyForTesting::send_test_command(*problem_realm->sync_session(), command_request.dump())
2✔
3786
                .get();
2✔
3787
        REQUIRE(resp_body == "{}");
2!
3788

3789
        // Put some data into the server, this will be the data that will be in the broker cache.
3790
        setup_and_poison_cache();
2✔
3791

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

3798
        REQUIRE(saw_truncated_bootstrap.load());
2!
3799
        auto table = problem_realm->read_group().get_table("class_TopLevel");
2✔
3800
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3801
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3802
    }
2✔
3803

3804
// TODO: remote-baas: This test fails intermittently with Windows remote baas server - to be fixed in RCORE-1674
3805
#ifndef _WIN32
6✔
3806
    SECTION("disconnect between bootstrap and mark") {
6✔
3807
        SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3808
        auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
3809
        triggered_config.sync_config->on_sync_client_event_hook =
2✔
3810
            [promise = util::CopyablePromiseHolder(std::move(interrupted_promise)), &bizz_obj_id,
2✔
3811
             &bar_obj_id](std::weak_ptr<SyncSession> weak_sess, const SyncClientHookData& data) mutable {
36✔
3812
                auto sess = weak_sess.lock();
36✔
3813
                if (!sess || data.event != SyncClientHookEvent::BootstrapProcessed || data.query_version != 1) {
36✔
3814
                    return SyncClientHookAction::NoAction;
34✔
3815
                }
34✔
3816

3817
                auto latest_subs = sess->get_flx_subscription_store()->get_latest();
2✔
3818
                REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3819
                REQUIRE(data.num_changesets == 1);
2!
3820
                auto db = SyncSession::OnlyForTesting::get_db(*sess);
2✔
3821
                auto read_tr = db->start_read();
2✔
3822
                auto table = read_tr->get_table("class_TopLevel");
2✔
3823
                REQUIRE(table->find_primary_key(bar_obj_id));
2!
3824
                REQUIRE_FALSE(table->find_primary_key(bizz_obj_id));
2!
3825

3826
                sess->pause();
2✔
3827
                promise.get_promise().emplace_value();
2✔
3828
                return SyncClientHookAction::NoAction;
2✔
3829
            };
2✔
3830
        auto problem_realm = Realm::get_shared_realm(triggered_config);
2✔
3831

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

3838
        nlohmann::json command_request = {
2✔
3839
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
3840
        };
2✔
3841
        auto resp_body =
2✔
3842
            SyncSession::OnlyForTesting::send_test_command(*problem_realm->sync_session(), command_request.dump())
2✔
3843
                .get();
2✔
3844
        REQUIRE(resp_body == "{}");
2!
3845

3846
        // Put some data into the server, this will be the data that will be in the broker cache.
3847
        setup_and_poison_cache();
2✔
3848

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

3855
        interrupted.get();
2✔
3856
        problem_realm->sync_session()->shutdown_and_wait();
2✔
3857
        REQUIRE(sub_complete_future.is_ready());
2!
3858
        sub_set.refresh();
2✔
3859
        REQUIRE(sub_set.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3860

3861
        sub_complete_future = sub_set.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
3862
        problem_realm->sync_session()->resume();
2✔
3863
        sub_complete_future.get();
2✔
3864
        wait_for_advance(*problem_realm);
2✔
3865

3866
        sub_set.refresh();
2✔
3867
        REQUIRE(sub_set.state() == sync::SubscriptionSet::State::Complete);
2!
3868
        auto table = problem_realm->read_group().get_table("class_TopLevel");
2✔
3869
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3870
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3871
    }
2✔
3872
#endif
6✔
3873
    SECTION("error/suspend between bootstrap and mark") {
6✔
3874
        SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
3875
        triggered_config.sync_config->on_sync_client_event_hook =
2✔
3876
            [&bizz_obj_id, &bar_obj_id](std::weak_ptr<SyncSession> weak_sess, const SyncClientHookData& data) {
34✔
3877
                auto sess = weak_sess.lock();
34✔
3878
                if (!sess || data.event != SyncClientHookEvent::BootstrapProcessed || data.query_version != 1) {
34✔
3879
                    return SyncClientHookAction::NoAction;
32✔
3880
                }
32✔
3881

3882
                auto latest_subs = sess->get_flx_subscription_store()->get_latest();
2✔
3883
                REQUIRE(latest_subs.state() == sync::SubscriptionSet::State::AwaitingMark);
2!
3884
                REQUIRE(data.num_changesets == 1);
2!
3885
                auto db = SyncSession::OnlyForTesting::get_db(*sess);
2✔
3886
                auto read_tr = db->start_read();
2✔
3887
                auto table = read_tr->get_table("class_TopLevel");
2✔
3888
                REQUIRE(table->find_primary_key(bar_obj_id));
2!
3889
                REQUIRE_FALSE(table->find_primary_key(bizz_obj_id));
2!
3890

3891
                return SyncClientHookAction::TriggerReconnect;
2✔
3892
            };
2✔
3893
        auto problem_realm = Realm::get_shared_realm(triggered_config);
2✔
3894

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

3901
        nlohmann::json command_request = {
2✔
3902
            {"command", "PAUSE_ROUTER_SESSION"},
2✔
3903
        };
2✔
3904
        auto resp_body =
2✔
3905
            SyncSession::OnlyForTesting::send_test_command(*problem_realm->sync_session(), command_request.dump())
2✔
3906
                .get();
2✔
3907
        REQUIRE(resp_body == "{}");
2!
3908

3909
        // Put some data into the server, this will be the data that will be in the broker cache.
3910
        setup_and_poison_cache();
2✔
3911

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

3918
        sub_complete_future.get();
2✔
3919
        wait_for_advance(*problem_realm);
2✔
3920

3921
        sub_set.refresh();
2✔
3922
        REQUIRE(sub_set.state() == sync::SubscriptionSet::State::Complete);
2!
3923
        auto table = problem_realm->read_group().get_table("class_TopLevel");
2✔
3924
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3925
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3926
    }
2✔
3927
}
6✔
3928

3929
TEST_CASE("flx: convert flx sync realm to bundled realm", "[app][flx][baas]") {
12✔
3930
    static auto foo_obj_id = ObjectId::gen();
12✔
3931
    static auto bar_obj_id = ObjectId::gen();
12✔
3932
    static auto bizz_obj_id = ObjectId::gen();
12✔
3933
    static std::optional<FLXSyncTestHarness> harness;
12✔
3934
    if (!harness) {
12✔
3935
        harness.emplace("bundled_flx_realms");
2✔
3936
        harness->load_initial_data([&](SharedRealm realm) {
2✔
3937
            CppContext c(realm);
2✔
3938
            Object::create(c, realm, "TopLevel",
2✔
3939
                           std::any(AnyDict{{"_id", foo_obj_id},
2✔
3940
                                            {"queryable_str_field", "foo"s},
2✔
3941
                                            {"queryable_int_field", static_cast<int64_t>(5)},
2✔
3942
                                            {"non_queryable_field", "non queryable 1"s}}));
2✔
3943
            Object::create(c, realm, "TopLevel",
2✔
3944
                           std::any(AnyDict{{"_id", bar_obj_id},
2✔
3945
                                            {"queryable_str_field", "bar"s},
2✔
3946
                                            {"queryable_int_field", static_cast<int64_t>(10)},
2✔
3947
                                            {"non_queryable_field", "non queryable 2"s}}));
2✔
3948
        });
2✔
3949
    }
2✔
3950

3951
    SECTION("flx to flx (should succeed)") {
12✔
3952
        create_user_and_log_in(harness->app());
2✔
3953
        SyncTestFile target_config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
3954
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3955
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
3956
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3957
            mut_subs.insert_or_assign(Query(table).greater(table->get_column_key("queryable_int_field"), 5));
2✔
3958
            auto subs = std::move(mut_subs).commit();
2✔
3959

3960
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
3961
            wait_for_advance(*realm);
2✔
3962

3963
            realm->convert(target_config);
2✔
3964
        });
2✔
3965

3966
        auto target_realm = Realm::get_shared_realm(target_config);
2✔
3967

3968
        target_realm->begin_transaction();
2✔
3969
        CppContext c(target_realm);
2✔
3970
        Object::create(c, target_realm, "TopLevel",
2✔
3971
                       std::any(AnyDict{{"_id", bizz_obj_id},
2✔
3972
                                        {"queryable_str_field", "bizz"s},
2✔
3973
                                        {"queryable_int_field", static_cast<int64_t>(15)},
2✔
3974
                                        {"non_queryable_field", "non queryable 3"s}}));
2✔
3975
        target_realm->commit_transaction();
2✔
3976

3977
        wait_for_upload(*target_realm);
2✔
3978
        wait_for_download(*target_realm);
2✔
3979

3980
        auto latest_subs = target_realm->get_active_subscription_set();
2✔
3981
        auto table = target_realm->read_group().get_table("class_TopLevel");
2✔
3982
        REQUIRE(latest_subs.size() == 1);
2!
3983
        REQUIRE(latest_subs.at(0).object_class_name == "TopLevel");
2!
3984
        REQUIRE(latest_subs.at(0).query_string ==
2!
3985
                Query(table).greater(table->get_column_key("queryable_int_field"), 5).get_description());
2✔
3986

3987
        REQUIRE(table->size() == 2);
2!
3988
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
3989
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
3990
        REQUIRE_FALSE(table->find_primary_key(foo_obj_id));
2!
3991
    }
2✔
3992

3993
    SECTION("flx to local (should succeed)") {
12✔
3994
        TestFile target_config;
2✔
3995

3996
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
3997
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
3998
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
3999
            mut_subs.insert_or_assign(Query(table).greater(table->get_column_key("queryable_int_field"), 5));
2✔
4000
            auto subs = std::move(mut_subs).commit();
2✔
4001

4002
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
4003
            wait_for_advance(*realm);
2✔
4004

4005
            target_config.schema = realm->schema();
2✔
4006
            target_config.schema_version = realm->schema_version();
2✔
4007
            realm->convert(target_config);
2✔
4008
        });
2✔
4009

4010
        auto target_realm = Realm::get_shared_realm(target_config);
2✔
4011
        REQUIRE_THROWS(target_realm->get_active_subscription_set());
2✔
4012

4013
        auto table = target_realm->read_group().get_table("class_TopLevel");
2✔
4014
        REQUIRE(table->size() == 2);
2!
4015
        REQUIRE(table->find_primary_key(bar_obj_id));
2!
4016
        REQUIRE(table->find_primary_key(bizz_obj_id));
2!
4017
        REQUIRE_FALSE(table->find_primary_key(foo_obj_id));
2!
4018
    }
2✔
4019

4020
    SECTION("flx to pbs (should fail to convert)") {
12✔
4021
        create_user_and_log_in(harness->app());
2✔
4022
        SyncTestFile target_config(harness->app()->current_user(), "12345"s, harness->schema());
2✔
4023
        harness->do_with_new_realm([&](SharedRealm realm) {
2✔
4024
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
4025
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4026
            mut_subs.insert_or_assign(Query(table).greater(table->get_column_key("queryable_int_field"), 5));
2✔
4027
            auto subs = std::move(mut_subs).commit();
2✔
4028

4029
            subs.get_state_change_notification(sync::SubscriptionSet::State::Complete).get();
2✔
4030
            wait_for_advance(*realm);
2✔
4031

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

4036
    SECTION("pbs to flx (should fail to convert)") {
12✔
4037
        create_user_and_log_in(harness->app());
2✔
4038
        SyncTestFile target_config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
4039

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

4042
        TestAppSession pbs_app_session(create_app(pbs_app_config));
2✔
4043
        SyncTestFile source_config(pbs_app_session.app()->current_user(), "54321"s, pbs_app_config.schema);
2✔
4044
        auto realm = Realm::get_shared_realm(source_config);
2✔
4045

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

4055
        REQUIRE_THROWS(realm->convert(target_config));
2✔
4056
    }
2✔
4057

4058
    SECTION("local to flx (should fail to convert)") {
12✔
4059
        TestFile source_config;
2✔
4060
        source_config.schema = harness->schema();
2✔
4061
        source_config.schema_version = 1;
2✔
4062

4063
        auto realm = Realm::get_shared_realm(source_config);
2✔
4064
        auto foo_obj_id = ObjectId::gen();
2✔
4065

4066
        realm->begin_transaction();
2✔
4067
        CppContext c(realm);
2✔
4068
        Object::create(c, realm, "TopLevel",
2✔
4069
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
4070
                                        {"queryable_str_field", "foo"s},
2✔
4071
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4072
                                        {"non_queryable_field", "non queryable 1"s}}));
2✔
4073
        realm->commit_transaction();
2✔
4074

4075
        create_user_and_log_in(harness->app());
2✔
4076
        SyncTestFile target_config(harness->app()->current_user(), harness->schema(), SyncConfig::FLXSyncEnabled{});
2✔
4077

4078
        REQUIRE_THROWS(realm->convert(target_config));
2✔
4079
    }
2✔
4080

4081
    // Add new sections before this
4082
    SECTION("teardown") {
12✔
4083
        harness->app()->sync_manager()->wait_for_sessions_to_terminate();
2✔
4084
        harness.reset();
2✔
4085
    }
2✔
4086
}
12✔
4087

4088
TEST_CASE("flx: compensating write errors get re-sent across sessions", "[sync][flx][compensating write][baas]") {
2✔
4089
    AppCreateConfig::ServiceRole role;
2✔
4090
    role.name = "compensating_write_perms";
2✔
4091

4092
    AppCreateConfig::ServiceRoleDocumentFilters doc_filters;
2✔
4093
    doc_filters.read = true;
2✔
4094
    doc_filters.write =
2✔
4095
        nlohmann::json{{"queryable_str_field", nlohmann::json{{"$in", nlohmann::json::array({"foo", "bar"})}}}};
2✔
4096
    role.document_filters = doc_filters;
2✔
4097

4098
    role.insert_filter = true;
2✔
4099
    role.delete_filter = true;
2✔
4100
    role.read = true;
2✔
4101
    role.write = true;
2✔
4102
    FLXSyncTestHarness::ServerSchema server_schema{
2✔
4103
        g_simple_embedded_obj_schema, {"queryable_str_field", "queryable_int_field"}, {role}};
2✔
4104
    FLXSyncTestHarness::Config harness_config("flx_bad_query", server_schema);
2✔
4105
    harness_config.reconnect_mode = ReconnectMode::testing;
2✔
4106
    FLXSyncTestHarness harness(std::move(harness_config));
2✔
4107

4108
    auto test_obj_id_1 = ObjectId::gen();
2✔
4109
    auto test_obj_id_2 = ObjectId::gen();
2✔
4110

4111
    create_user_and_log_in(harness.app());
2✔
4112
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4113

4114
    {
2✔
4115
        auto error_received_pf = util::make_promise_future<void>();
2✔
4116
        config.sync_config->on_sync_client_event_hook =
2✔
4117
            [promise = util::CopyablePromiseHolder(std::move(error_received_pf.promise))](
2✔
4118
                std::weak_ptr<SyncSession> weak_session, const SyncClientHookData& data) mutable {
30✔
4119
                if (data.event != SyncClientHookEvent::ErrorMessageReceived) {
30✔
4120
                    return SyncClientHookAction::NoAction;
28✔
4121
                }
28✔
4122
                auto session = weak_session.lock();
2✔
4123
                REQUIRE(session);
2!
4124

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

4127
                if (error_code == sync::ProtocolError::initial_sync_not_completed) {
2✔
4128
                    return SyncClientHookAction::NoAction;
×
4129
                }
×
4130

4131
                REQUIRE(error_code == sync::ProtocolError::compensating_write);
2!
4132
                REQUIRE_FALSE(data.error_info->compensating_writes.empty());
2!
4133
                promise.get_promise().emplace_value();
2✔
4134

4135
                return SyncClientHookAction::TriggerReconnect;
2✔
4136
            };
2✔
4137

4138
        auto realm = Realm::get_shared_realm(config);
2✔
4139
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4140
        auto queryable_str_field = table->get_column_key("queryable_str_field");
2✔
4141
        auto new_query = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4142
        new_query.insert_or_assign(Query(table).equal(queryable_str_field, "bizz"));
2✔
4143
        std::move(new_query).commit();
2✔
4144

4145
        wait_for_upload(*realm);
2✔
4146
        wait_for_download(*realm);
2✔
4147

4148
        CppContext c(realm);
2✔
4149
        realm->begin_transaction();
2✔
4150
        Object::create(c, realm, "TopLevel",
2✔
4151
                       util::Any(AnyDict{
2✔
4152
                           {"_id", test_obj_id_1},
2✔
4153
                           {"queryable_str_field", std::string{"foo"}},
2✔
4154
                       }));
2✔
4155
        realm->commit_transaction();
2✔
4156

4157
        realm->begin_transaction();
2✔
4158
        Object::create(c, realm, "TopLevel",
2✔
4159
                       util::Any(AnyDict{
2✔
4160
                           {"_id", test_obj_id_2},
2✔
4161
                           {"queryable_str_field", std::string{"baz"}},
2✔
4162
                       }));
2✔
4163
        realm->commit_transaction();
2✔
4164

4165
        error_received_pf.future.get();
2✔
4166
        realm->sync_session()->shutdown_and_wait();
2✔
4167
        config.sync_config->on_sync_client_event_hook = {};
2✔
4168
    }
2✔
4169

4170
    _impl::RealmCoordinator::clear_all_caches();
2✔
4171

4172
    std::mutex errors_mutex;
2✔
4173
    std::condition_variable new_compensating_write;
2✔
4174
    std::vector<std::pair<ObjectId, sync::version_type>> error_to_download_version;
2✔
4175
    std::vector<sync::CompensatingWriteErrorInfo> compensating_writes;
2✔
4176
    sync::version_type download_version;
2✔
4177

4178
    config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_session,
2✔
4179
                                                        const SyncClientHookData& data) mutable {
16✔
4180
        auto session = weak_session.lock();
16✔
4181
        if (!session) {
16✔
4182
            return SyncClientHookAction::NoAction;
×
4183
        }
×
4184

4185
        if (data.event != SyncClientHookEvent::ErrorMessageReceived) {
16✔
4186
            if (data.event == SyncClientHookEvent::DownloadMessageReceived) {
12✔
4187
                download_version = data.progress.download.server_version;
4✔
4188
            }
4✔
4189

4190
            return SyncClientHookAction::NoAction;
12✔
4191
        }
12✔
4192

4193
        auto error_code = sync::ProtocolError(data.error_info->raw_error_code);
4✔
4194
        REQUIRE(error_code == sync::ProtocolError::compensating_write);
4!
4195
        REQUIRE(!data.error_info->compensating_writes.empty());
4!
4196
        std::lock_guard<std::mutex> lk(errors_mutex);
4✔
4197
        for (const auto& compensating_write : data.error_info->compensating_writes) {
4✔
4198
            error_to_download_version.emplace_back(compensating_write.primary_key.get_object_id(),
4✔
4199
                                                   *data.error_info->compensating_write_server_version);
4✔
4200
        }
4✔
4201

4202
        return SyncClientHookAction::NoAction;
4✔
4203
    };
4✔
4204

4205
    config.sync_config->error_handler = [&](std::shared_ptr<SyncSession>, SyncError error) {
4✔
4206
        std::unique_lock<std::mutex> lk(errors_mutex);
4✔
4207
        REQUIRE(error.status == ErrorCodes::SyncCompensatingWrite);
4!
4208
        for (const auto& compensating_write : error.compensating_writes_info) {
4✔
4209
            auto tracked_error = std::find_if(error_to_download_version.begin(), error_to_download_version.end(),
4✔
4210
                                              [&](const auto& pair) {
6✔
4211
                                                  return pair.first == compensating_write.primary_key.get_object_id();
6✔
4212
                                              });
6✔
4213
            REQUIRE(tracked_error != error_to_download_version.end());
4!
4214
            CHECK(tracked_error->second <= download_version);
4!
4215
            compensating_writes.push_back(compensating_write);
4✔
4216
        }
4✔
4217
        new_compensating_write.notify_one();
4✔
4218
    };
4✔
4219

4220
    auto realm = Realm::get_shared_realm(config);
2✔
4221

4222
    wait_for_upload(*realm);
2✔
4223
    wait_for_download(*realm);
2✔
4224

4225
    std::unique_lock<std::mutex> lk(errors_mutex);
2✔
4226
    new_compensating_write.wait_for(lk, std::chrono::seconds(30), [&] {
2✔
4227
        return compensating_writes.size() == 2;
2✔
4228
    });
2✔
4229

4230
    REQUIRE(compensating_writes.size() == 2);
2!
4231
    auto& write_info = compensating_writes[0];
2✔
4232
    CHECK(write_info.primary_key.is_type(type_ObjectId));
2!
4233
    CHECK(write_info.primary_key.get_object_id() == test_obj_id_1);
2!
4234
    CHECK(write_info.object_name == "TopLevel");
2!
4235
    CHECK_THAT(write_info.reason, Catch::Matchers::ContainsSubstring("object is outside of the current query view"));
2✔
4236

4237
    write_info = compensating_writes[1];
2✔
4238
    REQUIRE(write_info.primary_key.is_type(type_ObjectId));
2!
4239
    REQUIRE(write_info.primary_key.get_object_id() == test_obj_id_2);
2!
4240
    REQUIRE(write_info.object_name == "TopLevel");
2!
4241
    REQUIRE(write_info.reason ==
2!
4242
            util::format("write to ObjectID(\"%1\") in table \"TopLevel\" not allowed", test_obj_id_2));
2✔
4243
    auto top_level_table = realm->read_group().get_table("class_TopLevel");
2✔
4244
    REQUIRE(top_level_table->is_empty());
2!
4245
}
2✔
4246

4247
TEST_CASE("flx: bootstrap changesets are applied continuously", "[sync][flx][bootstrap][baas]") {
2✔
4248
    FLXSyncTestHarness harness("flx_bootstrap_ordering", {g_large_array_schema, {"queryable_int_field"}});
2✔
4249
    fill_large_array_schema(harness);
2✔
4250

4251
    std::unique_ptr<std::thread> th;
2✔
4252
    sync::version_type user_commit_version = UINT_FAST64_MAX;
2✔
4253
    sync::version_type bootstrap_version = UINT_FAST64_MAX;
2✔
4254
    SharedRealm realm;
2✔
4255
    std::condition_variable cv;
2✔
4256
    std::mutex mutex;
2✔
4257
    bool allow_to_commit = false;
2✔
4258

4259
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4260
    auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
4261
    auto shared_promise = std::make_shared<util::Promise<void>>(std::move(interrupted_promise));
2✔
4262
    config.sync_config->on_sync_client_event_hook =
2✔
4263
        [promise = std::move(shared_promise), &th, &realm, &user_commit_version, &bootstrap_version, &cv, &mutex,
2✔
4264
         &allow_to_commit](std::weak_ptr<SyncSession> weak_session, const SyncClientHookData& data) {
68✔
4265
            if (data.query_version == 0) {
68✔
4266
                return SyncClientHookAction::NoAction;
18✔
4267
            }
18✔
4268
            if (data.event != SyncClientHookEvent::DownloadMessageIntegrated) {
50✔
4269
                return SyncClientHookAction::NoAction;
38✔
4270
            }
38✔
4271
            auto session = weak_session.lock();
12✔
4272
            if (!session) {
12✔
4273
                return SyncClientHookAction::NoAction;
×
4274
            }
×
4275
            if (data.batch_state != sync::DownloadBatchState::MoreToCome) {
12✔
4276
                // Read version after bootstrap is done.
4277
                auto db = TestHelper::get_db(realm);
2✔
4278
                ReadTransaction rt(db);
2✔
4279
                bootstrap_version = rt.get_version();
2✔
4280
                {
2✔
4281
                    std::lock_guard<std::mutex> lock(mutex);
2✔
4282
                    allow_to_commit = true;
2✔
4283
                }
2✔
4284
                cv.notify_one();
2✔
4285
                session->force_close();
2✔
4286
                promise->emplace_value();
2✔
4287
                return SyncClientHookAction::NoAction;
2✔
4288
            }
2✔
4289

4290
            if (th) {
10✔
4291
                return SyncClientHookAction::NoAction;
8✔
4292
            }
8✔
4293

4294
            auto func = [&] {
2✔
4295
                // Attempt to commit a local change after the first bootstrap batch was committed.
4296
                auto db = TestHelper::get_db(realm);
2✔
4297
                WriteTransaction wt(db);
2✔
4298
                TableRef table = wt.get_table("class_TopLevel");
2✔
4299
                table->create_object_with_primary_key(ObjectId::gen());
2✔
4300
                {
2✔
4301
                    std::unique_lock<std::mutex> lock(mutex);
2✔
4302
                    // Wait to commit until we read the final bootstrap version.
4303
                    cv.wait(lock, [&] {
2✔
4304
                        return allow_to_commit;
2✔
4305
                    });
2✔
4306
                }
2✔
4307
                user_commit_version = wt.commit();
2✔
4308
            };
2✔
4309
            th = std::make_unique<std::thread>(std::move(func));
2✔
4310

4311
            return SyncClientHookAction::NoAction;
2✔
4312
        };
10✔
4313

4314
    realm = Realm::get_shared_realm(config);
2✔
4315
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
4316
    Query query(table);
2✔
4317
    {
2✔
4318
        auto new_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4319
        new_subs.insert_or_assign(query);
2✔
4320
        new_subs.commit();
2✔
4321
    }
2✔
4322
    interrupted.get();
2✔
4323
    th->join();
2✔
4324

4325
    // The user commit is the last one.
4326
    CHECK(user_commit_version == bootstrap_version + 1);
2!
4327
}
2✔
4328

4329
TEST_CASE("flx: open realm + register subscription callback while bootstrapping",
4330
          "[sync][flx][bootstrap][async open][baas]") {
12✔
4331
    FLXSyncTestHarness harness("flx_bootstrap_and_subscribe");
12✔
4332
    auto foo_obj_id = ObjectId::gen();
12✔
4333
    harness.load_initial_data([&](SharedRealm realm) {
12✔
4334
        CppContext c(realm);
12✔
4335
        Object::create(c, realm, "TopLevel",
12✔
4336
                       std::any(AnyDict{{"_id", foo_obj_id},
12✔
4337
                                        {"queryable_str_field", "foo"s},
12✔
4338
                                        {"queryable_int_field", static_cast<int64_t>(5)},
12✔
4339
                                        {"non_queryable_field", "created as initial data seed"s}}));
12✔
4340
    });
12✔
4341
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
12✔
4342

4343
    std::atomic<bool> subscription_invoked = false;
12✔
4344
    auto subscription_pf = util::make_promise_future<bool>();
12✔
4345
    // create a subscription to commit when realm is open for the first time or asked to rerun on open
4346
    auto init_subscription_callback_with_promise =
12✔
4347
        [&, promise_holder = util::CopyablePromiseHolder(std::move(subscription_pf.promise))](
12✔
4348
            std::shared_ptr<Realm> realm) mutable {
12✔
4349
            REQUIRE(realm);
8!
4350
            auto table = realm->read_group().get_table("class_TopLevel");
8✔
4351
            Query query(table);
8✔
4352
            auto subscription = realm->get_latest_subscription_set();
8✔
4353
            auto mutable_subscription = subscription.make_mutable_copy();
8✔
4354
            mutable_subscription.insert_or_assign(query);
8✔
4355
            auto promise = promise_holder.get_promise();
8✔
4356
            mutable_subscription.commit();
8✔
4357
            subscription_invoked = true;
8✔
4358
            promise.emplace_value(true);
8✔
4359
        };
8✔
4360
    // verify that the subscription has changed the database
4361
    auto verify_subscription = [](SharedRealm realm) {
12✔
4362
        REQUIRE(realm);
12!
4363
        auto table_ref = realm->read_group().get_table("class_TopLevel");
12✔
4364
        REQUIRE(table_ref);
12!
4365
        REQUIRE(table_ref->get_column_count() == 4);
12!
4366
        REQUIRE(table_ref->get_column_key("_id"));
12!
4367
        REQUIRE(table_ref->get_column_key("queryable_str_field"));
12!
4368
        REQUIRE(table_ref->get_column_key("queryable_int_field"));
12!
4369
        REQUIRE(table_ref->get_column_key("non_queryable_field"));
12!
4370
        REQUIRE(table_ref->size() == 1);
12!
4371
        auto str_col = table_ref->get_column_key("queryable_str_field");
12✔
4372
        REQUIRE(table_ref->get_object(0).get<String>(str_col) == "foo");
12!
4373
        return true;
12✔
4374
    };
12✔
4375

4376
    SECTION("Sync open") {
12✔
4377
        // sync open with subscription callback. Subscription will be run, since this is the first time that realm is
4378
        // opened
4379
        subscription_invoked = false;
2✔
4380
        config.sync_config->subscription_initializer = init_subscription_callback_with_promise;
2✔
4381
        auto realm = Realm::get_shared_realm(config);
2✔
4382
        REQUIRE(subscription_pf.future.get());
2!
4383
        auto sb = realm->get_latest_subscription_set();
2✔
4384
        auto future = sb.get_state_change_notification(realm::sync::SubscriptionSet::State::Complete);
2✔
4385
        auto state = future.get();
2✔
4386
        REQUIRE(state == realm::sync::SubscriptionSet::State::Complete);
2!
4387
        realm->refresh(); // refresh is needed otherwise table_ref->size() would be 0
2✔
4388
        REQUIRE(verify_subscription(realm));
2!
4389
    }
2✔
4390

4391
    SECTION("Sync Open + Async Open") {
12✔
4392
        {
2✔
4393
            subscription_invoked = false;
2✔
4394
            config.sync_config->subscription_initializer = init_subscription_callback_with_promise;
2✔
4395
            auto realm = Realm::get_shared_realm(config);
2✔
4396
            REQUIRE(subscription_pf.future.get());
2!
4397
            auto sb = realm->get_latest_subscription_set();
2✔
4398
            auto future = sb.get_state_change_notification(realm::sync::SubscriptionSet::State::Complete);
2✔
4399
            auto state = future.get();
2✔
4400
            REQUIRE(state == realm::sync::SubscriptionSet::State::Complete);
2!
4401
            realm->refresh(); // refresh is needed otherwise table_ref->size() would be 0
2✔
4402
            REQUIRE(verify_subscription(realm));
2!
4403
        }
2✔
4404
        {
2✔
4405
            auto subscription_pf_async = util::make_promise_future<bool>();
2✔
4406
            auto init_subscription_asyc_callback =
2✔
4407
                [promise_holder_async = util::CopyablePromiseHolder(std::move(subscription_pf_async.promise))](
2✔
4408
                    std::shared_ptr<Realm> realm) mutable {
2✔
4409
                    REQUIRE(realm);
2!
4410
                    auto table = realm->read_group().get_table("class_TopLevel");
2✔
4411
                    Query query(table);
2✔
4412
                    auto subscription = realm->get_latest_subscription_set();
2✔
4413
                    auto mutable_subscription = subscription.make_mutable_copy();
2✔
4414
                    mutable_subscription.insert_or_assign(query);
2✔
4415
                    auto promise = promise_holder_async.get_promise();
2✔
4416
                    mutable_subscription.commit();
2✔
4417
                    promise.emplace_value(true);
2✔
4418
                };
2✔
4419
            auto open_realm_pf = util::make_promise_future<bool>();
2✔
4420
            auto open_realm_completed_callback =
2✔
4421
                [&, promise_holder = util::CopyablePromiseHolder(std::move(open_realm_pf.promise))](
2✔
4422
                    ThreadSafeReference ref, std::exception_ptr err) mutable {
2✔
4423
                    auto promise = promise_holder.get_promise();
2✔
4424
                    if (err)
2✔
4425
                        promise.emplace_value(false);
×
4426
                    else
2✔
4427
                        promise.emplace_value(verify_subscription(Realm::get_shared_realm(std::move(ref))));
2✔
4428
                };
2✔
4429

4430
            config.sync_config->subscription_initializer = init_subscription_asyc_callback;
2✔
4431
            config.sync_config->rerun_init_subscription_on_open = true;
2✔
4432
            auto async_open = Realm::get_synchronized_realm(config);
2✔
4433
            async_open->start(open_realm_completed_callback);
2✔
4434
            REQUIRE(open_realm_pf.future.get());
2!
4435
            REQUIRE(subscription_pf_async.future.get());
2!
4436
            config.sync_config->rerun_init_subscription_on_open = false;
2✔
4437
            auto realm = Realm::get_shared_realm(config);
2✔
4438
            REQUIRE(realm->get_latest_subscription_set().version() == 2);
2!
4439
            REQUIRE(realm->get_active_subscription_set().version() == 2);
2!
4440
        }
2✔
4441
    }
2✔
4442

4443
    SECTION("Async open") {
12✔
4444
        SECTION("Initial async open with no rerun on open set") {
8✔
4445
            // subscription will be run since this is the first time we are opening the realm file.
4446
            auto open_realm_pf = util::make_promise_future<bool>();
4✔
4447
            auto open_realm_completed_callback =
4✔
4448
                [&, promise_holder = util::CopyablePromiseHolder(std::move(open_realm_pf.promise))](
4✔
4449
                    ThreadSafeReference ref, std::exception_ptr err) mutable {
4✔
4450
                    auto promise = promise_holder.get_promise();
4✔
4451
                    if (err)
4✔
4452
                        promise.emplace_value(false);
×
4453
                    else
4✔
4454
                        promise.emplace_value(verify_subscription(Realm::get_shared_realm(std::move(ref))));
4✔
4455
                };
4✔
4456

4457
            config.sync_config->subscription_initializer = init_subscription_callback_with_promise;
4✔
4458
            auto async_open = Realm::get_synchronized_realm(config);
4✔
4459
            async_open->start(open_realm_completed_callback);
4✔
4460
            REQUIRE(open_realm_pf.future.get());
4!
4461
            REQUIRE(subscription_pf.future.get());
4!
4462

4463
            SECTION("rerun on open = false. Subscription not run") {
4✔
4464
                subscription_invoked = false;
2✔
4465
                auto async_open = Realm::get_synchronized_realm(config);
2✔
4466
                auto open_realm_pf = util::make_promise_future<bool>();
2✔
4467
                auto open_realm_completed_callback =
2✔
4468
                    [promise_holder = util::CopyablePromiseHolder(std::move(open_realm_pf.promise))](
2✔
4469
                        ThreadSafeReference, std::exception_ptr) mutable {
2✔
4470
                        // no need to verify if the subscription has changed the db, since it has not run as we test
4471
                        // below
4472
                        promise_holder.get_promise().emplace_value(true);
2✔
4473
                    };
2✔
4474
                async_open->start(open_realm_completed_callback);
2✔
4475
                REQUIRE(open_realm_pf.future.get());
2!
4476
                REQUIRE_FALSE(subscription_invoked.load());
2!
4477
            }
2✔
4478

4479
            SECTION("rerun on open = true. Subscription not run cause realm already opened once") {
4✔
4480
                subscription_invoked = false;
2✔
4481
                auto realm = Realm::get_shared_realm(config);
2✔
4482
                auto init_subscription = [&subscription_invoked](std::shared_ptr<Realm> realm) mutable {
2✔
4483
                    REQUIRE(realm);
×
4484
                    auto table = realm->read_group().get_table("class_TopLevel");
×
4485
                    Query query(table);
×
4486
                    auto subscription = realm->get_latest_subscription_set();
×
4487
                    auto mutable_subscription = subscription.make_mutable_copy();
×
4488
                    mutable_subscription.insert_or_assign(query);
×
4489
                    mutable_subscription.commit();
×
4490
                    subscription_invoked.store(true);
×
4491
                };
×
4492
                config.sync_config->rerun_init_subscription_on_open = true;
2✔
4493
                config.sync_config->subscription_initializer = init_subscription;
2✔
4494
                auto async_open = Realm::get_synchronized_realm(config);
2✔
4495
                auto open_realm_pf = util::make_promise_future<bool>();
2✔
4496
                auto open_realm_completed_callback =
2✔
4497
                    [promise_holder = util::CopyablePromiseHolder(std::move(open_realm_pf.promise))](
2✔
4498
                        ThreadSafeReference, std::exception_ptr) mutable {
2✔
4499
                        // no need to verify if the subscription has changed the db, since it has not run as we test
4500
                        // below
4501
                        promise_holder.get_promise().emplace_value(true);
2✔
4502
                    };
2✔
4503
                async_open->start(open_realm_completed_callback);
2✔
4504
                REQUIRE(open_realm_pf.future.get());
2!
4505
                REQUIRE_FALSE(subscription_invoked.load());
2!
4506
                REQUIRE(realm->get_latest_subscription_set().version() == 1);
2!
4507
                REQUIRE(realm->get_active_subscription_set().version() == 1);
2!
4508
            }
2✔
4509
        }
4✔
4510

4511
        SECTION("rerun on open set for multiple async open tasks (subscription runs only once)") {
8✔
4512
            auto init_subscription = [](std::shared_ptr<Realm> realm) mutable {
8✔
4513
                REQUIRE(realm);
8!
4514
                auto table = realm->read_group().get_table("class_TopLevel");
8✔
4515
                Query query(table);
8✔
4516
                auto subscription = realm->get_latest_subscription_set();
8✔
4517
                auto mutable_subscription = subscription.make_mutable_copy();
8✔
4518
                mutable_subscription.insert_or_assign(query);
8✔
4519
                mutable_subscription.commit();
8✔
4520
            };
8✔
4521

4522
            auto open_task1_pf = util::make_promise_future<SharedRealm>();
4✔
4523
            auto open_task2_pf = util::make_promise_future<SharedRealm>();
4✔
4524
            auto open_callback1 = [promise_holder = util::CopyablePromiseHolder(std::move(open_task1_pf.promise))](
4✔
4525
                                      ThreadSafeReference ref, std::exception_ptr err) mutable {
4✔
4526
                REQUIRE_FALSE(err);
4!
4527
                auto realm = Realm::get_shared_realm(std::move(ref));
4✔
4528
                REQUIRE(realm);
4!
4529
                promise_holder.get_promise().emplace_value(realm);
4✔
4530
            };
4✔
4531
            auto open_callback2 = [promise_holder = util::CopyablePromiseHolder(std::move(open_task2_pf.promise))](
4✔
4532
                                      ThreadSafeReference ref, std::exception_ptr err) mutable {
4✔
4533
                REQUIRE_FALSE(err);
4!
4534
                auto realm = Realm::get_shared_realm(std::move(ref));
4✔
4535
                REQUIRE(realm);
4!
4536
                promise_holder.get_promise().emplace_value(realm);
4✔
4537
            };
4✔
4538

4539
            config.sync_config->rerun_init_subscription_on_open = true;
4✔
4540
            config.sync_config->subscription_initializer = init_subscription;
4✔
4541

4542
            SECTION("Realm was already created, but we want to rerun on first open using multiple tasks") {
4✔
4543
                {
2✔
4544
                    subscription_invoked = false;
2✔
4545
                    auto realm = Realm::get_shared_realm(config);
2✔
4546
                    auto sb = realm->get_latest_subscription_set();
2✔
4547
                    auto future = sb.get_state_change_notification(realm::sync::SubscriptionSet::State::Complete);
2✔
4548
                    auto state = future.get();
2✔
4549
                    REQUIRE(state == realm::sync::SubscriptionSet::State::Complete);
2!
4550
                    realm->refresh(); // refresh is needed otherwise table_ref->size() would be 0
2✔
4551
                    REQUIRE(verify_subscription(realm));
2!
4552
                    REQUIRE(realm->get_latest_subscription_set().version() == 1);
2!
4553
                    REQUIRE(realm->get_active_subscription_set().version() == 1);
2!
4554
                }
2✔
4555

4556
                auto async_open_task1 = Realm::get_synchronized_realm(config);
2✔
4557
                auto async_open_task2 = Realm::get_synchronized_realm(config);
2✔
4558
                async_open_task1->start(open_callback1);
2✔
4559
                async_open_task2->start(open_callback2);
2✔
4560

4561
                auto realm1 = open_task1_pf.future.get();
2✔
4562
                auto realm2 = open_task2_pf.future.get();
2✔
4563

4564
                const auto version_expected = 2;
2✔
4565
                auto r1_latest = realm1->get_latest_subscription_set().version();
2✔
4566
                auto r1_active = realm1->get_active_subscription_set().version();
2✔
4567
                REQUIRE(realm2->get_latest_subscription_set().version() == r1_latest);
2!
4568
                REQUIRE(realm2->get_active_subscription_set().version() == r1_active);
2!
4569
                REQUIRE(r1_latest == version_expected);
2!
4570
                REQUIRE(r1_active == version_expected);
2!
4571
            }
2✔
4572
            SECTION("First time realm is created but opened via open async. Both tasks could run the subscription") {
4✔
4573
                auto async_open_task1 = Realm::get_synchronized_realm(config);
2✔
4574
                auto async_open_task2 = Realm::get_synchronized_realm(config);
2✔
4575
                async_open_task1->start(open_callback1);
2✔
4576
                async_open_task2->start(open_callback2);
2✔
4577
                auto realm1 = open_task1_pf.future.get();
2✔
4578
                auto realm2 = open_task2_pf.future.get();
2✔
4579

4580
                auto r1_latest = realm1->get_latest_subscription_set().version();
2✔
4581
                auto r1_active = realm1->get_active_subscription_set().version();
2✔
4582
                REQUIRE(realm2->get_latest_subscription_set().version() == r1_latest);
2!
4583
                REQUIRE(realm2->get_active_subscription_set().version() == r1_active);
2!
4584
                // the callback may be run twice, if task1 is the first task to open realm
4585
                // but it is scheduled after tasks2, which have opened realm later but
4586
                // by the time it runs, subscription version is equal to 0 (realm creation).
4587
                // This can only happen the first time that realm is created. All the other times
4588
                // the init_sb callback is guaranteed to run once.
4589
                REQUIRE(r1_latest >= 1);
2!
4590
                REQUIRE(r1_latest <= 2);
2!
4591
                REQUIRE(r1_active >= 1);
2!
4592
                REQUIRE(r1_active <= 2);
2!
4593
            }
2✔
4594
        }
4✔
4595
    }
8✔
4596
}
12✔
4597
TEST_CASE("flx sync: Client reset during async open", "[sync][flx][client reset][async open][baas]") {
2✔
4598
    FLXSyncTestHarness harness("flx_bootstrap_reset");
2✔
4599
    auto foo_obj_id = ObjectId::gen();
2✔
4600
    std::atomic<bool> subscription_invoked = false;
2✔
4601
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4602
        CppContext c(realm);
2✔
4603
        Object::create(c, realm, "TopLevel",
2✔
4604
                       std::any(AnyDict{{"_id", foo_obj_id},
2✔
4605
                                        {"queryable_str_field", "foo"s},
2✔
4606
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4607
                                        {"non_queryable_field", "created as initial data seed"s}}));
2✔
4608
    });
2✔
4609
    SyncTestFile realm_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4610

4611
    auto subscription_callback = [&](std::shared_ptr<Realm> realm) {
2✔
4612
        REQUIRE(realm);
2!
4613
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4614
        Query query(table);
2✔
4615
        auto subscription = realm->get_latest_subscription_set();
2✔
4616
        auto mutable_subscription = subscription.make_mutable_copy();
2✔
4617
        mutable_subscription.insert_or_assign(query);
2✔
4618
        subscription_invoked = true;
2✔
4619
        mutable_subscription.commit();
2✔
4620
    };
2✔
4621

4622
    realm_config.sync_config->client_resync_mode = ClientResyncMode::Recover;
2✔
4623
    realm_config.sync_config->subscription_initializer = subscription_callback;
2✔
4624

4625
    bool client_reset_triggered = false;
2✔
4626
    realm_config.sync_config->on_sync_client_event_hook = [&](std::weak_ptr<SyncSession> weak_sess,
2✔
4627
                                                              const SyncClientHookData& event_data) {
54✔
4628
        auto sess = weak_sess.lock();
54✔
4629
        if (!sess) {
54✔
4630
            return SyncClientHookAction::NoAction;
×
4631
        }
×
4632
        if (sess->path() != realm_config.path) {
54✔
4633
            return SyncClientHookAction::NoAction;
24✔
4634
        }
24✔
4635

4636
        if (event_data.event != SyncClientHookEvent::DownloadMessageReceived) {
30✔
4637
            return SyncClientHookAction::NoAction;
24✔
4638
        }
24✔
4639

4640
        if (client_reset_triggered) {
6✔
4641
            return SyncClientHookAction::NoAction;
4✔
4642
        }
4✔
4643

4644
        client_reset_triggered = true;
2✔
4645
        reset_utils::trigger_client_reset(harness.session().app_session(), *sess);
2✔
4646
        return SyncClientHookAction::SuspendWithRetryableError;
2✔
4647
    };
6✔
4648

4649
    auto before_callback_called = util::make_promise_future<void>();
2✔
4650
    realm_config.sync_config->notify_before_client_reset = [&](std::shared_ptr<Realm> realm) {
2✔
4651
        CHECK(realm->schema_version() == 0);
2!
4652
        before_callback_called.promise.emplace_value();
2✔
4653
    };
2✔
4654

4655
    auto after_callback_called = util::make_promise_future<void>();
2✔
4656
    realm_config.sync_config->notify_after_client_reset = [&](std::shared_ptr<Realm> realm, ThreadSafeReference,
2✔
4657
                                                              bool) {
2✔
4658
        CHECK(realm->schema_version() == 0);
2!
4659
        after_callback_called.promise.emplace_value();
2✔
4660
    };
2✔
4661

4662
    auto realm_task = Realm::get_synchronized_realm(realm_config);
2✔
4663
    auto realm_pf = util::make_promise_future<SharedRealm>();
2✔
4664
    realm_task->start([&](ThreadSafeReference ref, std::exception_ptr ex) {
2✔
4665
        auto& promise = realm_pf.promise;
2✔
4666
        try {
2✔
4667
            if (ex) {
2✔
4668
                std::rethrow_exception(ex);
×
4669
            }
×
4670
            promise.emplace_value(Realm::get_shared_realm(std::move(ref)));
2✔
4671
        }
2✔
4672
        catch (...) {
2✔
4673
            promise.set_error(exception_to_status());
×
4674
        }
×
4675
    });
2✔
4676
    auto realm = realm_pf.future.get();
2✔
4677
    before_callback_called.future.get();
2✔
4678
    after_callback_called.future.get();
2✔
4679
    REQUIRE(subscription_invoked.load());
2!
4680
}
2✔
4681

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

4686
    std::vector<ObjectId> obj_ids_at_end = fill_large_array_schema(harness);
2✔
4687
    SyncTestFile interrupted_realm_config(harness.app()->current_user(), harness.schema(),
2✔
4688
                                          SyncConfig::FLXSyncEnabled{});
2✔
4689

4690
    {
2✔
4691
        auto pf = util::make_promise_future<void>();
2✔
4692
        Realm::Config config = interrupted_realm_config;
2✔
4693
        config.sync_config = std::make_shared<SyncConfig>(*interrupted_realm_config.sync_config);
2✔
4694
        config.sync_config->on_sync_client_event_hook =
2✔
4695
            [promise = util::CopyablePromiseHolder(std::move(pf.promise))](std::weak_ptr<SyncSession> weak_session,
2✔
4696
                                                                           const SyncClientHookData& data) mutable {
68✔
4697
                if (data.event != SyncClientHookEvent::BootstrapMessageProcessed &&
68✔
4698
                    data.event != SyncClientHookEvent::BootstrapProcessed) {
68✔
4699
                    return SyncClientHookAction::NoAction;
50✔
4700
                }
50✔
4701
                auto session = weak_session.lock();
18✔
4702
                if (!session) {
18✔
4703
                    return SyncClientHookAction::NoAction;
×
4704
                }
×
4705
                if (data.query_version != 1) {
18✔
4706
                    return SyncClientHookAction::NoAction;
4✔
4707
                }
4✔
4708

4709
                // Commit a subscriptions set whenever a bootstrap message is received for query version 1.
4710
                if (data.event == SyncClientHookEvent::BootstrapMessageProcessed) {
14✔
4711
                    auto latest_subs = session->get_flx_subscription_store()->get_latest().make_mutable_copy();
12✔
4712
                    latest_subs.commit();
12✔
4713
                    return SyncClientHookAction::NoAction;
12✔
4714
                }
12✔
4715
                // At least one subscription set was created.
4716
                CHECK(session->get_flx_subscription_store()->get_latest().version() > 1);
2!
4717
                promise.get_promise().emplace_value();
2✔
4718
                // Reconnect once query version 1 is bootstrapped.
4719
                return SyncClientHookAction::TriggerReconnect;
2✔
4720
            };
2✔
4721

4722
        auto realm = Realm::get_shared_realm(config);
2✔
4723
        {
2✔
4724
            auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
2✔
4725
            auto table = realm->read_group().get_table("class_TopLevel");
2✔
4726
            mut_subs.insert_or_assign(Query(table));
2✔
4727
            mut_subs.commit();
2✔
4728
        }
2✔
4729
        pf.future.get();
2✔
4730
        realm->sync_session()->shutdown_and_wait();
2✔
4731
        realm->close();
2✔
4732
    }
2✔
4733

4734
    _impl::RealmCoordinator::assert_no_open_realms();
2✔
4735

4736
    // Check at least one subscription set needs to be resent.
4737
    {
2✔
4738
        DBOptions options;
2✔
4739
        options.encryption_key = test_util::crypt_key();
2✔
4740
        auto realm = DB::create(sync::make_client_replication(), interrupted_realm_config.path, options);
2✔
4741
        auto sub_store = sync::SubscriptionStore::create(realm);
2✔
4742
        auto version_info = sub_store->get_version_info();
2✔
4743
        REQUIRE(version_info.latest > version_info.active);
2!
4744
    }
2✔
4745

4746
    // Resend the pending subscriptions.
4747
    auto realm = Realm::get_shared_realm(interrupted_realm_config);
2✔
4748
    wait_for_upload(*realm);
2✔
4749
    wait_for_download(*realm);
2✔
4750
}
2✔
4751

4752
TEST_CASE("flx: fatal errors and session becoming inactive cancel pending waits", "[sync][flx][baas]") {
2✔
4753
    std::vector<ObjectSchema> schema{
2✔
4754
        {"TopLevel",
2✔
4755
         {
2✔
4756
             {"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
4757
             {"queryable_int_field", PropertyType::Int | PropertyType::Nullable},
2✔
4758
         }},
2✔
4759
    };
2✔
4760

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

4764
    auto check_status = [](auto status) {
4✔
4765
        CHECK(!status.is_ok());
4!
4766
        std::string reason = status.get_status().reason();
4✔
4767
        // Subscription notification is cancelled either because the sync session is inactive, or because a fatal
4768
        // error is received from the server.
4769
        if (reason.find("Sync session became inactive") == std::string::npos &&
4✔
4770
            reason.find("Invalid schema change (UPLOAD): non-breaking schema change: adding \"Int\" column at field "
4✔
4771
                        "\"other_col\" in schema \"TopLevel\", schema changes from clients are restricted when "
2✔
4772
                        "developer mode is disabled") == std::string::npos) {
2✔
4773
            FAIL(reason);
×
4774
        }
×
4775
    };
4✔
4776

4777
    auto create_subscription = [](auto realm) -> realm::sync::SubscriptionSet {
4✔
4778
        auto mut_subs = realm->get_latest_subscription_set().make_mutable_copy();
4✔
4779
        auto table = realm->read_group().get_table("class_TopLevel");
4✔
4780
        mut_subs.insert_or_assign(Query(table));
4✔
4781
        return mut_subs.commit();
4✔
4782
    };
4✔
4783

4784
    auto [error_occured_promise, error_occurred] = util::make_promise_future<void>();
2✔
4785
    config.sync_config->error_handler = [promise = util::CopyablePromiseHolder(std::move(error_occured_promise))](
2✔
4786
                                            std::shared_ptr<SyncSession>, SyncError) mutable {
2✔
4787
        promise.get_promise().emplace_value();
2✔
4788
    };
2✔
4789

4790
    auto realm = Realm::get_shared_realm(config);
2✔
4791
    wait_for_download(*realm);
2✔
4792

4793
    auto subs = create_subscription(realm);
2✔
4794
    auto subs_future = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
4795

4796
    realm->sync_session()->pause();
2✔
4797
    auto state = subs_future.get_no_throw();
2✔
4798
    check_status(state);
2✔
4799

4800
    auto [download_complete_promise, download_complete] = util::make_promise_future<void>();
2✔
4801
    realm->sync_session()->wait_for_upload_completion([promise = std::move(download_complete_promise)](auto) mutable {
2✔
4802
        promise.emplace_value();
2✔
4803
    });
2✔
4804
    schema[0].persisted_properties.push_back({"other_col", PropertyType::Int | PropertyType::Nullable});
2✔
4805
    realm->update_schema(schema);
2✔
4806

4807
    subs = create_subscription(realm);
2✔
4808
    subs_future = subs.get_state_change_notification(sync::SubscriptionSet::State::Complete);
2✔
4809

4810
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4811
        CppContext c(realm);
2✔
4812
        Object::create(c, realm, "TopLevel",
2✔
4813
                       std::any(AnyDict{{"_id", ObjectId::gen()},
2✔
4814
                                        {"queryable_int_field", static_cast<int64_t>(5)},
2✔
4815
                                        {"other_col", static_cast<int64_t>(42)}}));
2✔
4816
    });
2✔
4817

4818
    realm->sync_session()->resume();
2✔
4819
    download_complete.get();
2✔
4820
    error_occurred.get();
2✔
4821
    state = subs_future.get_no_throw();
2✔
4822
    check_status(state);
2✔
4823
}
2✔
4824

4825
TEST_CASE("flx: pause and resume bootstrapping at query version 0", "[sync][flx][baas]") {
2✔
4826
    FLXSyncTestHarness harness("flx_pause_resume_bootstrap");
2✔
4827
    SyncTestFile triggered_config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4828
    auto [interrupted_promise, interrupted] = util::make_promise_future<void>();
2✔
4829
    std::mutex download_message_mutex;
2✔
4830
    int download_message_integrated_count = 0;
2✔
4831
    triggered_config.sync_config->on_sync_client_event_hook =
2✔
4832
        [promise = util::CopyablePromiseHolder(std::move(interrupted_promise)), &download_message_integrated_count,
2✔
4833
         &download_message_mutex](std::weak_ptr<SyncSession> weak_sess, const SyncClientHookData& data) mutable {
22✔
4834
            auto sess = weak_sess.lock();
22✔
4835
            if (!sess || data.event != SyncClientHookEvent::DownloadMessageIntegrated) {
22✔
4836
                return SyncClientHookAction::NoAction;
18✔
4837
            }
18✔
4838

4839
            std::lock_guard<std::mutex> lk(download_message_mutex);
4✔
4840
            // Pause and resume the first session after the bootstrap message is integrated.
4841
            if (download_message_integrated_count == 0) {
4✔
4842
                sess->pause();
2✔
4843
                sess->resume();
2✔
4844
            }
2✔
4845
            // Complete the test when the second session integrates the empty download
4846
            // message it receives.
4847
            else {
2✔
4848
                promise.get_promise().emplace_value();
2✔
4849
            }
2✔
4850
            ++download_message_integrated_count;
4✔
4851
            return SyncClientHookAction::NoAction;
4✔
4852
        };
22✔
4853
    auto realm = Realm::get_shared_realm(triggered_config);
2✔
4854
    interrupted.get();
2✔
4855
    std::lock_guard<std::mutex> lk(download_message_mutex);
2✔
4856
    CHECK(download_message_integrated_count == 2);
2!
4857
    auto active_sub_set = realm->sync_session()->get_flx_subscription_store()->get_active();
2✔
4858
    REQUIRE(active_sub_set.version() == 0);
2!
4859
    REQUIRE(active_sub_set.state() == sync::SubscriptionSet::State::Complete);
2!
4860
}
2✔
4861

4862
TEST_CASE("flx: collections in mixed - merge lists", "[sync][flx][baas]") {
2✔
4863
    Schema schema{{"TopLevel",
2✔
4864
                   {{"_id", PropertyType::ObjectId, Property::IsPrimary{true}},
2✔
4865
                    {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
4866
                    {"any", PropertyType::Mixed | PropertyType::Nullable}}}};
2✔
4867

4868
    FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field"}};
2✔
4869
    FLXSyncTestHarness harness("flx_collections_in_mixed", server_schema);
2✔
4870
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4871

4872
    auto set_list_and_insert_element = [](Obj& obj, ColKey col_any, Mixed value) {
8✔
4873
        obj.set_collection(col_any, CollectionType::List);
8✔
4874
        auto list = obj.get_list_ptr<Mixed>(col_any);
8✔
4875
        list->add(value);
8✔
4876
    };
8✔
4877

4878
    // Client 1 creates an object and sets property 'any' to an integer value.
4879
    auto foo_obj_id = ObjectId::gen();
2✔
4880
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4881
        CppContext c(realm);
2✔
4882
        Object::create(c, realm, "TopLevel",
2✔
4883
                       std::any(AnyDict{{"_id", foo_obj_id}, {"queryable_str_field", "foo"s}, {"any", 42}}));
2✔
4884
    });
2✔
4885

4886
    // Client 2 opens the realm and downloads schema and object created by Client 1.
4887
    auto realm = Realm::get_shared_realm(config);
2✔
4888
    subscribe_to_all_and_bootstrap(*realm);
2✔
4889
    realm->sync_session()->pause();
2✔
4890

4891
    // Client 3 sets property 'any' to List and inserts two integers in the list.
4892
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4893
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4894
        auto obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
4895
        auto col_any = table->get_column_key("any");
2✔
4896
        set_list_and_insert_element(obj, col_any, 1);
2✔
4897
        set_list_and_insert_element(obj, col_any, 2);
2✔
4898
    });
2✔
4899

4900
    // While its session is paused, Client 2 sets property 'any' to List and inserts two integers in the list.
4901
    CppContext c(realm);
2✔
4902
    realm->begin_transaction();
2✔
4903
    auto table = realm->read_group().get_table("class_TopLevel");
2✔
4904
    auto obj = table->get_object_with_primary_key(Mixed{foo_obj_id});
2✔
4905
    auto col_any = table->get_column_key("any");
2✔
4906
    set_list_and_insert_element(obj, col_any, 3);
2✔
4907
    set_list_and_insert_element(obj, col_any, 4);
2✔
4908
    realm->commit_transaction();
2✔
4909

4910
    realm->sync_session()->resume();
2✔
4911
    wait_for_upload(*realm);
2✔
4912
    wait_for_download(*realm);
2✔
4913
    wait_for_advance(*realm);
2✔
4914

4915
    // Client 2 ends up with four integers in the list (in the correct order).
4916
    auto list = obj.get_list_ptr<Mixed>(col_any);
2✔
4917
    CHECK(list->size() == 4);
2!
4918
    CHECK(list->get(0) == 1);
2!
4919
    CHECK(list->get(1) == 2);
2!
4920
    CHECK(list->get(2) == 3);
2!
4921
    CHECK(list->get(3) == 4);
2!
4922
}
2✔
4923

4924
TEST_CASE("flx: nested collections in mixed", "[sync][flx][baas]") {
2✔
4925
    Schema schema{{"TopLevel",
2✔
4926
                   {{"_id", PropertyType::Int, Property::IsPrimary{true}},
2✔
4927
                    {"queryable_str_field", PropertyType::String | PropertyType::Nullable},
2✔
4928
                    {"any", PropertyType::Mixed | PropertyType::Nullable}}}};
2✔
4929

4930
    FLXSyncTestHarness::ServerSchema server_schema{schema, {"queryable_str_field"}};
2✔
4931
    FLXSyncTestHarness harness("flx_collections_in_mixed", server_schema);
2✔
4932
    SyncTestFile config(harness.app()->current_user(), harness.schema(), SyncConfig::FLXSyncEnabled{});
2✔
4933

4934
    // Client 1: {_id: 1, any: ["abc", [42]]}
4935
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4936
        CppContext c(realm);
2✔
4937
        auto obj = Object::create(c, realm, "TopLevel",
2✔
4938
                                  std::any(AnyDict{{"_id", INT64_C(1)}, {"queryable_str_field", "foo"s}}));
2✔
4939
        auto table = realm->read_group().get_table("class_TopLevel");
2✔
4940
        auto col_any = table->get_column_key("any");
2✔
4941
        obj.get_obj().set_collection(col_any, CollectionType::List);
2✔
4942
        List list(obj, obj.get_object_schema().property_for_name("any"));
2✔
4943
        list.insert_any(0, "abc");
2✔
4944
        list.insert_collection(1, CollectionType::List);
2✔
4945
        auto list2 = list.get_list(1);
2✔
4946
        list2.insert_any(0, 42);
2✔
4947
    });
2✔
4948

4949
    // Client 2 opens the realm and downloads schema and object created by Client 1.
4950
    // {_id: 1, any: ["abc", [42]]}
4951
    auto realm = Realm::get_shared_realm(config);
2✔
4952
    subscribe_to_all_and_bootstrap(*realm);
2✔
4953
    realm->sync_session()->pause();
2✔
4954

4955
    // Client 3 adds a dictionary with an element to list 'any'
4956
    // {_id: 1, any: [{{"key": 6}}, "abc", [42]]}
4957
    harness.load_initial_data([&](SharedRealm realm) {
2✔
4958
        CppContext c(realm);
2✔
4959
        auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(INT64_C(1)));
2✔
4960
        List list(obj, obj.get_object_schema().property_for_name("any"));
2✔
4961
        list.insert_collection(PathElement(0), CollectionType::Dictionary);
2✔
4962
        auto dict = list.get_dictionary(PathElement(0));
2✔
4963
        dict.insert_any("key", INT64_C(6));
2✔
4964
    });
2✔
4965

4966
    // While its session is paused, Client 2 makes a change to a nested list
4967
    // {_id: 1, any: ["abc", [42, "foo"]]}
4968
    CppContext c(realm);
2✔
4969
    realm->begin_transaction();
2✔
4970
    auto obj = Object::get_for_primary_key(c, realm, "TopLevel", std::any(INT64_C(1)));
2✔
4971
    List list(obj, obj.get_object_schema().property_for_name("any"));
2✔
4972
    List list2 = list.get_list(PathElement(1));
2✔
4973
    list2.insert_any(list2.size(), "foo");
2✔
4974
    realm->commit_transaction();
2✔
4975

4976
    realm->sync_session()->resume();
2✔
4977
    wait_for_upload(*realm);
2✔
4978
    wait_for_download(*realm);
2✔
4979
    wait_for_advance(*realm);
2✔
4980

4981
    // Client 2 after the session is resumed
4982
    // {_id: 1, any: [{{"key": 6}}, "abc", [42, "foo"]]}
4983
    CHECK(list.size() == 3);
2!
4984
    auto nested_dict = list.get_dictionary(0);
2✔
4985
    CHECK(nested_dict.size() == 1);
2!
4986
    CHECK(nested_dict.get<Int>("key") == 6);
2!
4987

4988
    CHECK(list.get_any(1) == "abc");
2!
4989

4990
    auto nested_list = list.get_list(2);
2✔
4991
    CHECK(nested_list.size() == 2);
2!
4992
    CHECK(nested_list.get_any(0) == 42);
2!
4993
    CHECK(nested_list.get_any(1) == "foo");
2!
4994
}
2✔
4995

4996
} // namespace realm::app
4997

4998
#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