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

realm / realm-core / kirill.burtsev_130

14 Feb 2024 07:28PM UTC coverage: 91.891% (+0.01%) from 91.881%
kirill.burtsev_130

Pull #7344

Evergreen

kiburtse
fix some gcc build warnings
Pull Request #7344: Allow to set logging level through env var for object store tests

93086 of 171520 branches covered (54.27%)

36 of 40 new or added lines in 5 files covered. (90.0%)

47 existing lines in 10 files now uncovered.

235529 of 256314 relevant lines covered (91.89%)

6267890.8 hits per line

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

92.96
/src/realm/sync/noinst/client_reset.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
#include <realm/transaction.hpp>
20
#include <realm/dictionary.hpp>
21
#include <realm/object_converter.hpp>
22
#include <realm/table_view.hpp>
23
#include <realm/set.hpp>
24

25
#include <realm/sync/history.hpp>
26
#include <realm/sync/changeset_parser.hpp>
27
#include <realm/sync/instruction_applier.hpp>
28
#include <realm/sync/noinst/client_history_impl.hpp>
29
#include <realm/sync/noinst/client_reset.hpp>
30
#include <realm/sync/noinst/client_reset_recovery.hpp>
31
#include <realm/sync/subscriptions.hpp>
32

33
#include <realm/util/compression.hpp>
34

35
#include <algorithm>
36
#include <chrono>
37
#include <vector>
38

39
using namespace realm;
40
using namespace _impl;
41
using namespace sync;
42

43
namespace realm {
44

45
std::ostream& operator<<(std::ostream& os, const ClientResyncMode& mode)
46
{
22,710✔
47
    switch (mode) {
22,710✔
48
        case ClientResyncMode::Manual:
✔
49
            os << "Manual";
×
50
            break;
×
51
        case ClientResyncMode::DiscardLocal:
11,216✔
52
            os << "DiscardLocal";
11,216✔
53
            break;
11,216✔
54
        case ClientResyncMode::Recover:
11,374✔
55
            os << "Recover";
11,374✔
56
            break;
11,374✔
57
        case ClientResyncMode::RecoverOrDiscard:
120✔
58
            os << "RecoverOrDiscard";
120✔
59
            break;
120✔
60
    }
22,710✔
61
    return os;
22,710✔
62
}
22,710✔
63

64
} // namespace realm
65

66
namespace realm::_impl::client_reset {
67

68
static inline bool should_skip_table(const Transaction& group, TableKey key)
69
{
242,060✔
70
    return !group.table_is_public(key);
242,060✔
71
}
242,060✔
72

73
void transfer_group(const Transaction& group_src, Transaction& group_dst, util::Logger& logger,
74
                    bool allow_schema_additions)
75
{
7,356✔
76
    logger.debug("transfer_group, src size = %1, dst size = %2, allow_schema_additions = %3", group_src.size(),
7,356✔
77
                 group_dst.size(), allow_schema_additions);
7,356✔
78

3,678✔
79
    // Turn off the sync history tracking during state transfer since it will be thrown
3,678✔
80
    // away immediately after anyways. This reduces the memory footprint of a client reset.
3,678✔
81
    ClientReplication* client_repl = dynamic_cast<ClientReplication*>(group_dst.get_replication());
7,356✔
82
    REALM_ASSERT_RELEASE(client_repl);
7,356✔
83
    TempShortCircuitReplication sync_history_guard(*client_repl);
7,356✔
84

3,678✔
85
    // Find all tables in dst that should be removed.
3,678✔
86
    std::set<std::string> tables_to_remove;
7,356✔
87
    for (auto table_key : group_dst.get_table_keys()) {
33,064✔
88
        if (should_skip_table(group_dst, table_key))
33,064✔
89
            continue;
15,440✔
90
        StringData table_name = group_dst.get_table_name(table_key);
17,624✔
91
        logger.debug("key = %1, table_name = %2", table_key.value, table_name);
17,624✔
92
        ConstTableRef table_src = group_src.get_table(table_name);
17,624✔
93
        if (!table_src) {
17,624✔
94
            logger.debug("Table '%1' will be removed", table_name);
24✔
95
            tables_to_remove.insert(table_name);
24✔
96
            continue;
24✔
97
        }
24✔
98
        // Check whether the table type is the same.
8,800✔
99
        TableRef table_dst = group_dst.get_table(table_key);
17,600✔
100
        auto pk_col_src = table_src->get_primary_key_column();
17,600✔
101
        auto pk_col_dst = table_dst->get_primary_key_column();
17,600✔
102
        bool has_pk_src = bool(pk_col_src);
17,600✔
103
        bool has_pk_dst = bool(pk_col_dst);
17,600✔
104
        if (has_pk_src != has_pk_dst) {
17,600✔
105
            throw ClientResetFailed(util::format("Client reset requires a primary key column in %1 table '%2'",
×
106
                                                 (has_pk_src ? "dest" : "source"), table_name));
×
107
        }
×
108
        if (!has_pk_src)
17,600✔
109
            continue;
664✔
110

8,468✔
111
        // Now the tables both have primary keys. Check type.
8,468✔
112
        if (pk_col_src.get_type() != pk_col_dst.get_type()) {
16,936✔
113
            throw ClientResetFailed(
4✔
114
                util::format("Client reset found incompatible primary key types (%1 vs %2) on '%3'",
4✔
115
                             pk_col_src.get_type(), pk_col_dst.get_type(), table_name));
4✔
116
        }
4✔
117
        // Check collection type, nullability etc. but having an index doesn't matter;
8,466✔
118
        ColumnAttrMask pk_col_src_attr = pk_col_src.get_attrs();
16,932✔
119
        ColumnAttrMask pk_col_dst_attr = pk_col_dst.get_attrs();
16,932✔
120
        pk_col_src_attr.reset(ColumnAttr::col_attr_Indexed);
16,932✔
121
        pk_col_dst_attr.reset(ColumnAttr::col_attr_Indexed);
16,932✔
122
        if (pk_col_src_attr != pk_col_dst_attr) {
16,932✔
123
            throw ClientResetFailed(
×
124
                util::format("Client reset found incompatible primary key attributes (%1 vs %2) on '%3'",
×
125
                             pk_col_src.value, pk_col_dst.value, table_name));
×
126
        }
×
127
        // Check name.
8,466✔
128
        StringData pk_col_name_src = table_src->get_column_name(pk_col_src);
16,932✔
129
        StringData pk_col_name_dst = table_dst->get_column_name(pk_col_dst);
16,932✔
130
        if (pk_col_name_src != pk_col_name_dst) {
16,932✔
131
            throw ClientResetFailed(
×
132
                util::format("Client reset requires equal pk column names but '%1' != '%2' on '%3'", pk_col_name_src,
×
133
                             pk_col_name_dst, table_name));
×
134
        }
×
135
        // The table survives.
8,466✔
136
        logger.debug("Table '%1' will remain", table_name);
16,932✔
137
    }
16,932✔
138

3,678✔
139
    // If there have been any tables marked for removal stop.
3,678✔
140
    // We consider two possible options for recovery:
3,678✔
141
    // 1: Remove the tables. But this will generate destructive schema
3,678✔
142
    //    schema changes that the local Realm cannot advance through.
3,678✔
143
    //    Since this action will fail down the line anyway, give up now.
3,678✔
144
    // 2: Keep the tables locally and ignore them. But the local app schema
3,678✔
145
    //    still has these classes and trying to modify anything in them will
3,678✔
146
    //    create sync instructions on tables that sync doesn't know about.
3,678✔
147
    // As an exception in recovery mode, we assume that the corresponding
3,678✔
148
    // additive schema changes will be part of the recovery upload. If they
3,678✔
149
    // are present, then the server can choose to allow them (if in dev mode).
3,678✔
150
    // If they are not present, then the server will emit an error the next time
3,678✔
151
    // a value is set on the unknown property.
3,678✔
152
    if (!allow_schema_additions && !tables_to_remove.empty()) {
7,354✔
153
        std::string names_list;
16✔
154
        for (const std::string& table_name : tables_to_remove) {
24✔
155
            names_list += Group::table_name_to_class_name(table_name);
24✔
156
            names_list += ", ";
24✔
157
        }
24✔
158
        if (names_list.size() > 2) {
16✔
159
            // remove the final ", "
8✔
160
            names_list = names_list.substr(0, names_list.size() - 2);
16✔
161
        }
16✔
162
        throw ClientResetFailed(
16✔
163
            util::format("Client reset cannot recover when classes have been removed: {%1}", names_list));
16✔
164
    }
16✔
165

3,668✔
166
    // Create new tables in dst if needed.
3,668✔
167
    for (auto table_key : group_src.get_table_keys()) {
25,164✔
168
        if (should_skip_table(group_src, table_key))
25,164✔
169
            continue;
7,580✔
170
        ConstTableRef table_src = group_src.get_table(table_key);
17,584✔
171
        StringData table_name = table_src->get_name();
17,584✔
172
        auto pk_col_src = table_src->get_primary_key_column();
17,584✔
173
        TableRef table_dst = group_dst.get_table(table_name);
17,584✔
174
        if (!table_dst) {
17,584✔
175
            // Create the table.
16✔
176
            if (table_src->is_embedded()) {
32✔
177
                REALM_ASSERT(!pk_col_src);
16✔
178
                group_dst.add_table(table_name, Table::Type::Embedded);
16✔
179
            }
16✔
180
            else {
16✔
181
                REALM_ASSERT(pk_col_src); // a sync table will have a pk
16✔
182
                auto pk_col_src = table_src->get_primary_key_column();
16✔
183
                DataType pk_type = DataType(pk_col_src.get_type());
16✔
184
                StringData pk_col_name = table_src->get_column_name(pk_col_src);
16✔
185
                group_dst.add_table_with_primary_key(table_name, pk_type, pk_col_name, pk_col_src.is_nullable(),
16✔
186
                                                     table_src->get_table_type());
16✔
187
            }
16✔
188
        }
32✔
189
    }
17,584✔
190

3,668✔
191
    // Now the class tables are identical.
3,668✔
192
    size_t num_tables;
7,336✔
193
    {
7,336✔
194
        size_t num_tables_src = 0;
7,336✔
195
        for (auto table_key : group_src.get_table_keys()) {
25,164✔
196
            if (!should_skip_table(group_src, table_key))
25,164✔
197
                ++num_tables_src;
17,584✔
198
        }
25,164✔
199
        size_t num_tables_dst = 0;
7,336✔
200
        for (auto table_key : group_dst.get_table_keys()) {
32,968✔
201
            if (!should_skip_table(group_dst, table_key))
32,968✔
202
                ++num_tables_dst;
17,584✔
203
        }
32,968✔
204
        REALM_ASSERT_EX(allow_schema_additions || num_tables_src == num_tables_dst, num_tables_src, num_tables_dst);
7,336✔
205
        num_tables = num_tables_src;
7,336✔
206
    }
7,336✔
207
    logger.debug("The number of tables is %1", num_tables);
7,336✔
208

3,668✔
209
    // Remove columns in dst if they are absent in src.
3,668✔
210
    for (auto table_key : group_src.get_table_keys()) {
25,160✔
211
        if (should_skip_table(group_src, table_key))
25,160✔
212
            continue;
7,580✔
213
        ConstTableRef table_src = group_src.get_table(table_key);
17,580✔
214
        StringData table_name = table_src->get_name();
17,580✔
215
        TableRef table_dst = group_dst.get_table(table_name);
17,580✔
216
        REALM_ASSERT(table_dst);
17,580✔
217
        std::vector<std::string> columns_to_remove;
17,580✔
218
        for (ColKey col_key : table_dst->get_column_keys()) {
56,484✔
219
            StringData col_name = table_dst->get_column_name(col_key);
56,484✔
220
            ColKey col_key_src = table_src->get_column_key(col_name);
56,484✔
221
            if (!col_key_src) {
56,484✔
222
                columns_to_remove.push_back(col_name);
12✔
223
                continue;
12✔
224
            }
12✔
225
        }
56,484✔
226
        if (!allow_schema_additions && !columns_to_remove.empty()) {
17,580✔
227
            std::string columns_list;
4✔
228
            for (const std::string& col_name : columns_to_remove) {
12✔
229
                columns_list += col_name;
12✔
230
                columns_list += ", ";
12✔
231
            }
12✔
232
            throw ClientResetFailed(
4✔
233
                util::format("Client reset cannot recover when columns have been removed from '%1': {%2}", table_name,
4✔
234
                             columns_list));
4✔
235
        }
4✔
236
    }
17,580✔
237

3,668✔
238
    // Add columns in dst if present in src and absent in dst.
3,668✔
239
    for (auto table_key : group_src.get_table_keys()) {
25,144✔
240
        if (should_skip_table(group_src, table_key))
25,144✔
241
            continue;
7,580✔
242
        ConstTableRef table_src = group_src.get_table(table_key);
17,564✔
243
        StringData table_name = table_src->get_name();
17,564✔
244
        TableRef table_dst = group_dst.get_table(table_name);
17,564✔
245
        REALM_ASSERT(table_dst);
17,564✔
246
        for (ColKey col_key : table_src->get_column_keys()) {
56,540✔
247
            StringData col_name = table_src->get_column_name(col_key);
56,540✔
248
            ColKey col_key_dst = table_dst->get_column_key(col_name);
56,540✔
249
            if (!col_key_dst) {
56,540✔
250
                DataType col_type = table_src->get_column_type(col_key);
128✔
251
                bool nullable = col_key.is_nullable();
128✔
252
                auto search_index_type = table_src->search_index_type(col_key);
128✔
253
                logger.trace("Create column, table = %1, column name = %2, "
128✔
254
                             " type = %3, nullable = %4, search_index = %5",
128✔
255
                             table_name, col_name, col_key.get_type(), nullable, search_index_type);
128✔
256
                ColKey col_key_dst;
128✔
257
                if (Table::is_link_type(col_key.get_type())) {
128✔
258
                    ConstTableRef target_src = table_src->get_link_target(col_key);
48✔
259
                    TableRef target_dst = group_dst.get_table(target_src->get_name());
48✔
260
                    if (col_key.is_list()) {
48✔
261
                        col_key_dst = table_dst->add_column_list(*target_dst, col_name);
16✔
262
                    }
16✔
263
                    else if (col_key.is_set()) {
32✔
264
                        col_key_dst = table_dst->add_column_set(*target_dst, col_name);
×
265
                    }
×
266
                    else if (col_key.is_dictionary()) {
32✔
267
                        DataType key_type = table_src->get_dictionary_key_type(col_key);
8✔
268
                        col_key_dst = table_dst->add_column_dictionary(*target_dst, col_name, key_type);
8✔
269
                    }
8✔
270
                    else {
24✔
271
                        REALM_ASSERT(!col_key.is_collection());
24✔
272
                        col_key_dst = table_dst->add_column(*target_dst, col_name);
24✔
273
                    }
24✔
274
                }
48✔
275
                else if (col_key.is_list()) {
80✔
276
                    col_key_dst = table_dst->add_column_list(col_type, col_name, nullable);
8✔
277
                }
8✔
278
                else if (col_key.is_set()) {
72✔
279
                    col_key_dst = table_dst->add_column_set(col_type, col_name, nullable);
8✔
280
                }
8✔
281
                else if (col_key.is_dictionary()) {
64✔
282
                    DataType key_type = table_src->get_dictionary_key_type(col_key);
8✔
283
                    col_key_dst = table_dst->add_column_dictionary(col_type, col_name, nullable, key_type);
8✔
284
                }
8✔
285
                else {
56✔
286
                    REALM_ASSERT(!col_key.is_collection());
56✔
287
                    col_key_dst = table_dst->add_column(col_type, col_name, nullable);
56✔
288
                }
56✔
289

64✔
290
                if (search_index_type != IndexType::None)
128✔
291
                    table_dst->add_search_index(col_key_dst, search_index_type);
×
292
            }
128✔
293
            else {
56,412✔
294
                // column preexists in dest, make sure the types match
28,206✔
295
                if (col_key.get_type() != col_key_dst.get_type()) {
56,412✔
296
                    throw ClientResetFailed(util::format(
4✔
297
                        "Incompatable column type change detected during client reset for '%1.%2' (%3 vs %4)",
4✔
298
                        table_name, col_name, col_key.get_type(), col_key_dst.get_type()));
4✔
299
                }
4✔
300
                ColumnAttrMask src_col_attrs = col_key.get_attrs();
56,408✔
301
                ColumnAttrMask dst_col_attrs = col_key_dst.get_attrs();
56,408✔
302
                src_col_attrs.reset(ColumnAttr::col_attr_Indexed);
56,408✔
303
                dst_col_attrs.reset(ColumnAttr::col_attr_Indexed);
56,408✔
304
                // make sure the attributes such as collection type, nullability etc. match
28,204✔
305
                // but index equality doesn't matter here.
28,204✔
306
                if (src_col_attrs != dst_col_attrs) {
56,408✔
307
                    throw ClientResetFailed(util::format(
×
308
                        "Incompatable column attribute change detected during client reset for '%1.%2' (%3 vs %4)",
×
309
                        table_name, col_name, col_key.value, col_key_dst.value));
×
310
                }
×
311
            }
56,408✔
312
        }
56,540✔
313
    }
17,564✔
314

3,666✔
315
    // Now the schemas are identical.
3,666✔
316

3,666✔
317
    // Remove objects in dst that are absent in src.
3,666✔
318
    for (auto table_key : group_src.get_table_keys()) {
25,132✔
319
        if (should_skip_table(group_src, table_key))
25,132✔
320
            continue;
7,580✔
321
        auto table_src = group_src.get_table(table_key);
17,552✔
322
        // There are no primary keys in embedded tables but this is ok, because
8,776✔
323
        // embedded objects are tied to the lifetime of top level objects.
8,776✔
324
        if (table_src->is_embedded())
17,552✔
325
            continue;
680✔
326
        StringData table_name = table_src->get_name();
16,872✔
327
        logger.debug("Removing objects in '%1'", table_name);
16,872✔
328
        auto table_dst = group_dst.get_table(table_name);
16,872✔
329

8,436✔
330
        auto pk_col = table_dst->get_primary_key_column();
16,872✔
331
        REALM_ASSERT_DEBUG(pk_col); // sync realms always have a pk
16,872✔
332
        std::vector<std::pair<Mixed, ObjKey>> objects_to_remove;
16,872✔
333
        for (auto obj : *table_dst) {
24,808✔
334
            auto pk = obj.get_any(pk_col);
24,808✔
335
            if (!table_src->find_primary_key(pk)) {
24,808✔
336
                objects_to_remove.emplace_back(pk, obj.get_key());
832✔
337
            }
832✔
338
        }
24,808✔
339
        for (auto& pair : objects_to_remove) {
8,852✔
340
            logger.debug("  removing '%1'", pair.first);
832✔
341
            table_dst->remove_object(pair.second);
832✔
342
        }
832✔
343
    }
16,872✔
344

3,664✔
345
    // We must re-create any missing objects that are absent in dst before trying to copy
3,664✔
346
    // their properties because creating them may re-create any dangling links which would
3,664✔
347
    // otherwise cause inconsistencies when re-creating lists of links.
3,664✔
348
    for (auto table_key : group_src.get_table_keys()) {
25,132✔
349
        ConstTableRef table_src = group_src.get_table(table_key);
25,132✔
350
        auto table_name = table_src->get_name();
25,132✔
351
        if (should_skip_table(group_src, table_key) || table_src->is_embedded())
25,132✔
352
            continue;
8,260✔
353
        TableRef table_dst = group_dst.get_table(table_name);
16,872✔
354
        auto pk_col = table_src->get_primary_key_column();
16,872✔
355
        REALM_ASSERT(pk_col);
16,872✔
356
        logger.debug("Creating missing objects for table '%1', number of rows = %2, "
16,872✔
357
                     "primary_key_col = %3, primary_key_type = %4",
16,872✔
358
                     table_name, table_src->size(), pk_col.get_index().val, pk_col.get_type());
16,872✔
359
        for (const Obj& src : *table_src) {
24,648✔
360
            bool created = false;
24,648✔
361
            table_dst->create_object_with_primary_key(src.get_primary_key(), &created);
24,648✔
362
            if (created) {
24,648✔
363
                logger.debug("   created %1", src.get_primary_key());
672✔
364
            }
672✔
365
        }
24,648✔
366
    }
16,872✔
367

3,664✔
368
    converters::EmbeddedObjectConverter embedded_tracker;
7,328✔
369
    // Now src and dst have identical schemas and all the top level objects are created.
3,664✔
370
    // What is left to do is to diff all properties of the existing objects.
3,664✔
371
    // Embedded objects are created on the fly.
3,664✔
372
    for (auto table_key : group_src.get_table_keys()) {
25,132✔
373
        if (should_skip_table(group_src, table_key))
25,132✔
374
            continue;
7,580✔
375
        ConstTableRef table_src = group_src.get_table(table_key);
17,552✔
376
        // Embedded objects don't have a primary key, so they are handled
8,776✔
377
        // as a special case when they are encountered as a link value.
8,776✔
378
        if (table_src->is_embedded())
17,552✔
379
            continue;
680✔
380
        StringData table_name = table_src->get_name();
16,872✔
381
        TableRef table_dst = group_dst.get_table(table_name);
16,872✔
382
        REALM_ASSERT_EX(allow_schema_additions || table_src->get_column_count() == table_dst->get_column_count(),
16,872✔
383
                        allow_schema_additions, table_src->get_column_count(), table_dst->get_column_count());
16,872✔
384
        auto pk_col = table_src->get_primary_key_column();
16,872✔
385
        REALM_ASSERT(pk_col);
16,872✔
386
        logger.debug("Updating values for table '%1', number of rows = %2, "
16,872✔
387
                     "number of columns = %3, primary_key_col = %4, "
16,872✔
388
                     "primary_key_type = %5",
16,872✔
389
                     table_name, table_src->size(), table_src->get_column_count(), pk_col.get_index().val,
16,872✔
390
                     pk_col.get_type());
16,872✔
391

8,436✔
392
        converters::InterRealmObjectConverter converter(table_src, table_dst, &embedded_tracker);
16,872✔
393

8,436✔
394
        for (const Obj& src : *table_src) {
24,648✔
395
            auto src_pk = src.get_primary_key();
24,648✔
396
            // create the object - it should have been created above.
12,324✔
397
            auto dst = table_dst->get_object_with_primary_key(src_pk);
24,648✔
398
            REALM_ASSERT(dst);
24,648✔
399

12,324✔
400
            bool updated = false;
24,648✔
401
            converter.copy(src, dst, &updated);
24,648✔
402
            if (updated) {
24,648✔
403
                logger.debug("  updating %1", src_pk);
7,772✔
404
            }
7,772✔
405
        }
24,648✔
406
        embedded_tracker.process_pending();
16,872✔
407
    }
16,872✔
408
}
7,328✔
409

410
// A table without a "class_" prefix will not generate sync instructions.
411
constexpr static std::string_view s_meta_reset_table_name("client_reset_metadata");
412
constexpr static std::string_view s_pk_col_name("id");
413
constexpr static std::string_view s_version_column_name("version");
414
constexpr static std::string_view s_timestamp_col_name("event_time");
415
constexpr static std::string_view s_reset_type_col_name("type_of_reset");
416
constexpr int64_t metadata_version = 1;
417

418
void remove_pending_client_resets(Transaction& wt)
419
{
262✔
420
    if (auto table = wt.get_table(s_meta_reset_table_name); table && !table->is_empty()) {
262✔
421
        table->clear();
262✔
422
    }
262✔
423
}
262✔
424

425
util::Optional<PendingReset> has_pending_reset(const Transaction& rt)
426
{
17,850✔
427
    ConstTableRef table = rt.get_table(s_meta_reset_table_name);
17,850✔
428
    if (!table || table->size() == 0) {
17,850✔
429
        return util::none;
17,040✔
430
    }
17,040✔
431
    ColKey timestamp_col = table->get_column_key(s_timestamp_col_name);
810✔
432
    ColKey type_col = table->get_column_key(s_reset_type_col_name);
810✔
433
    ColKey version_col = table->get_column_key(s_version_column_name);
810✔
434
    REALM_ASSERT(timestamp_col);
810✔
435
    REALM_ASSERT(type_col);
810✔
436
    REALM_ASSERT(version_col);
810✔
437
    if (table->size() > 1) {
810✔
438
        // this may happen if a future version of this code changes the format and expectations around reset metadata.
439
        throw ClientResetFailed(
×
440
            util::format("Previous client resets detected (%1) but only one is expected.", table->size()));
×
441
    }
×
442
    Obj first = *table->begin();
810✔
443
    REALM_ASSERT(first);
810✔
444
    PendingReset pending;
810✔
445
    int64_t version = first.get<int64_t>(version_col);
810✔
446
    pending.time = first.get<Timestamp>(timestamp_col);
810✔
447
    if (version > metadata_version) {
810✔
448
        throw ClientResetFailed(util::format("Unsupported client reset metadata version: %1 vs %2, from %3", version,
×
449
                                             metadata_version, pending.time));
×
450
    }
×
451
    int64_t type = first.get<int64_t>(type_col);
810✔
452
    if (type == 0) {
810✔
453
        pending.type = ClientResyncMode::DiscardLocal;
440✔
454
    }
440✔
455
    else if (type == 1) {
370✔
456
        pending.type = ClientResyncMode::Recover;
370✔
457
    }
370✔
UNCOV
458
    else {
×
UNCOV
459
        throw ClientResetFailed(
×
UNCOV
460
            util::format("Unsupported client reset metadata type: %1 from %2", type, pending.time));
×
UNCOV
461
    }
×
462
    return pending;
810✔
463
}
810✔
464

465
void track_reset(Transaction& wt, ClientResyncMode mode)
466
{
7,396✔
467
    REALM_ASSERT(mode != ClientResyncMode::Manual);
7,396✔
468
    TableRef table = wt.get_table(s_meta_reset_table_name);
7,396✔
469
    ColKey version_col, timestamp_col, type_col;
7,396✔
470
    if (!table) {
7,396✔
471
        table = wt.add_table_with_primary_key(s_meta_reset_table_name, type_ObjectId, s_pk_col_name);
7,352✔
472
        REALM_ASSERT(table);
7,352✔
473
        version_col = table->add_column(type_Int, s_version_column_name);
7,352✔
474
        timestamp_col = table->add_column(type_Timestamp, s_timestamp_col_name);
7,352✔
475
        type_col = table->add_column(type_Int, s_reset_type_col_name);
7,352✔
476
    }
7,352✔
477
    else {
44✔
478
        version_col = table->get_column_key(s_version_column_name);
44✔
479
        timestamp_col = table->get_column_key(s_timestamp_col_name);
44✔
480
        type_col = table->get_column_key(s_reset_type_col_name);
44✔
481
    }
44✔
482
    REALM_ASSERT(version_col);
7,396✔
483
    REALM_ASSERT(timestamp_col);
7,396✔
484
    REALM_ASSERT(type_col);
7,396✔
485
    int64_t mode_val = 0; // Discard
7,396✔
486
    if (mode == ClientResyncMode::Recover || mode == ClientResyncMode::RecoverOrDiscard) {
7,396✔
487
        mode_val = 1; // Recover
3,732✔
488
    }
3,732✔
489

3,698✔
490
    if (table->size() > 1) {
7,396✔
491
        // this may happen if a future version of this code changes the format and expectations around reset metadata.
492
        throw ClientResetFailed(
×
493
            util::format("Previous client resets detected (%1) but only one is expected.", table->size()));
×
494
    }
×
495
    table->create_object_with_primary_key(ObjectId::gen(),
7,396✔
496
                                          {{version_col, metadata_version},
7,396✔
497
                                           {timestamp_col, Timestamp(std::chrono::system_clock::now())},
7,396✔
498
                                           {type_col, mode_val}});
7,396✔
499

3,698✔
500
    // Ensure we save the tracker object even if we encounter an error and roll
3,698✔
501
    // back the client reset later
3,698✔
502
    wt.commit_and_continue_writing();
7,396✔
503
}
7,396✔
504

505
static ClientResyncMode reset_precheck_guard(Transaction& wt, ClientResyncMode mode, bool recovery_is_allowed,
506
                                             util::Logger& logger)
507
{
7,396✔
508
    if (auto previous_reset = has_pending_reset(wt)) {
7,396✔
509
        logger.info("A previous reset was detected of type: '%1' at: %2", previous_reset->type, previous_reset->time);
32✔
510
        switch (previous_reset->type) {
32✔
511
            case ClientResyncMode::Manual:
✔
512
                REALM_UNREACHABLE();
513
            case ClientResyncMode::DiscardLocal:
12✔
514
                throw ClientResetFailed(util::format("A previous '%1' mode reset from %2 did not succeed, "
12✔
515
                                                     "giving up on '%3' mode to prevent a cycle",
12✔
516
                                                     previous_reset->type, previous_reset->time, mode));
12✔
517
            case ClientResyncMode::Recover:
20✔
518
                switch (mode) {
20✔
519
                    case ClientResyncMode::Recover:
8✔
520
                        throw ClientResetFailed(util::format("A previous '%1' mode reset from %2 did not succeed, "
8✔
521
                                                             "giving up on '%3' mode to prevent a cycle",
8✔
522
                                                             previous_reset->type, previous_reset->time, mode));
8✔
523
                    case ClientResyncMode::RecoverOrDiscard:
8✔
524
                        mode = ClientResyncMode::DiscardLocal;
8✔
525
                        logger.info("A previous '%1' mode reset from %2 downgrades this mode ('%3') to DiscardLocal",
8✔
526
                                    previous_reset->type, previous_reset->time, mode);
8✔
527
                        remove_pending_client_resets(wt);
8✔
528
                        break;
8✔
529
                    case ClientResyncMode::DiscardLocal:
4✔
530
                        remove_pending_client_resets(wt);
4✔
531
                        // previous mode Recover and this mode is Discard, this is not a cycle yet
2✔
532
                        break;
4✔
533
                    case ClientResyncMode::Manual:
✔
534
                        REALM_UNREACHABLE();
535
                }
20✔
536
                break;
16✔
537
            case ClientResyncMode::RecoverOrDiscard:
10✔
538
                throw ClientResetFailed(util::format("Unexpected previous '%1' mode reset from %2 did not "
×
539
                                                     "succeed, giving up on '%3' mode to prevent a cycle",
×
540
                                                     previous_reset->type, previous_reset->time, mode));
×
541
        }
7,376✔
542
    }
7,376✔
543
    if (!recovery_is_allowed) {
7,376✔
544
        if (mode == ClientResyncMode::Recover) {
24✔
545
            throw ClientResetFailed(
4✔
546
                "Client reset mode is set to 'Recover' but the server does not allow recovery for this client");
4✔
547
        }
4✔
548
        else if (mode == ClientResyncMode::RecoverOrDiscard) {
20✔
549
            logger.info("Client reset in 'RecoverOrDiscard' is choosing 'DiscardLocal' because the server does not "
12✔
550
                        "permit recovery for this client");
12✔
551
            mode = ClientResyncMode::DiscardLocal;
12✔
552
        }
12✔
553
    }
24✔
554
    track_reset(wt, mode);
7,374✔
555
    return mode;
7,372✔
556
}
7,376✔
557

558
bool perform_client_reset_diff(DB& db_local, DB& db_remote, sync::SaltedFileIdent client_file_ident,
559
                               util::Logger& logger, ClientResyncMode mode, bool recovery_is_allowed,
560
                               sync::SubscriptionStore* sub_store,
561
                               util::FunctionRef<void(int64_t)> on_flx_version_complete)
562
{
7,396✔
563
    auto wt_local = db_local.start_write();
7,396✔
564
    auto actual_mode = reset_precheck_guard(*wt_local, mode, recovery_is_allowed, logger);
7,396✔
565
    bool recover_local_changes =
7,396✔
566
        actual_mode == ClientResyncMode::Recover || actual_mode == ClientResyncMode::RecoverOrDiscard;
7,396✔
567

3,698✔
568
    logger.info("Client reset: path_local = %1, "
7,396✔
569
                "client_file_ident = (ident: %2, salt: %3), "
7,396✔
570
                "remote_path = %4, requested_mode = %5, recovery_is_allowed = %6, "
7,396✔
571
                "actual_mode = %7, will_recover = %8",
7,396✔
572
                db_local.get_path(), client_file_ident.ident, client_file_ident.salt, db_remote.get_path(), mode,
7,396✔
573
                recovery_is_allowed, actual_mode, recover_local_changes);
7,396✔
574

3,698✔
575
    auto& repl_local = dynamic_cast<ClientReplication&>(*db_local.get_replication());
7,396✔
576
    auto& history_local = repl_local.get_history();
7,396✔
577
    history_local.ensure_updated(wt_local->get_version());
7,396✔
578
    VersionID old_version_local = wt_local->get_version_of_current_transaction();
7,396✔
579

3,698✔
580
    auto& repl_remote = dynamic_cast<ClientReplication&>(*db_remote.get_replication());
7,396✔
581
    auto& history_remote = repl_remote.get_history();
7,396✔
582

3,698✔
583
    sync::SaltedVersion fresh_server_version = {0, 0};
7,396✔
584
    {
7,396✔
585
        SyncProgress remote_progress;
7,396✔
586
        sync::version_type remote_version_unused;
7,396✔
587
        SaltedFileIdent remote_ident_unused;
7,396✔
588
        history_remote.get_status(remote_version_unused, remote_ident_unused, remote_progress);
7,396✔
589
        fresh_server_version = remote_progress.latest_server_version;
7,396✔
590
    }
7,396✔
591

3,698✔
592
    TransactionRef tr_remote;
7,396✔
593
    std::vector<client_reset::RecoveredChange> recovered;
7,396✔
594
    if (recover_local_changes) {
7,396✔
595
        auto frozen_pre_local_state = db_local.start_frozen();
3,720✔
596
        auto local_changes = history_local.get_local_changes(wt_local->get_version());
3,720✔
597
        logger.info("Local changesets to recover: %1", local_changes.size());
3,720✔
598

1,860✔
599
        tr_remote = db_remote.start_write();
3,720✔
600
        recovered = process_recovered_changesets(*tr_remote, *frozen_pre_local_state, logger, local_changes);
3,720✔
601
    }
3,720✔
602
    else {
3,676✔
603
        tr_remote = db_remote.start_read();
3,676✔
604
    }
3,676✔
605

3,698✔
606
    // transform the local Realm such that all public tables become identical to the remote Realm
3,698✔
607
    transfer_group(*tr_remote, *wt_local, logger, false);
7,396✔
608

3,698✔
609
    // now that the state of the fresh and local Realms are identical,
3,698✔
610
    // reset the local sync history and steal the fresh Realm's ident
3,698✔
611
    history_local.set_client_reset_adjustments(logger, wt_local->get_version(), client_file_ident,
7,396✔
612
                                               fresh_server_version, recovered);
7,396✔
613

3,698✔
614
    int64_t subscription_version = 0;
7,396✔
615
    if (sub_store) {
7,396✔
616
        if (recover_local_changes) {
124✔
617
            subscription_version = sub_store->mark_active_as_complete(*wt_local);
76✔
618
        }
76✔
619
        else {
48✔
620
            subscription_version = sub_store->set_active_as_latest(*wt_local);
48✔
621
        }
48✔
622
    }
124✔
623

3,698✔
624
    wt_local->commit_and_continue_as_read();
7,396✔
625
    on_flx_version_complete(subscription_version);
7,396✔
626

3,698✔
627
    VersionID new_version_local = wt_local->get_version_of_current_transaction();
7,396✔
628
    logger.info("perform_client_reset_diff is done: old_version = (version: %1, index: %2), "
7,396✔
629
                "new_version = (version: %3, index: %4)",
7,396✔
630
                old_version_local.version, old_version_local.index, new_version_local.version,
7,396✔
631
                new_version_local.index);
7,396✔
632

3,698✔
633
    return recover_local_changes;
7,396✔
634
}
7,396✔
635

636
} // namespace realm::_impl::client_reset
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc