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

realm / realm-core / thomas.goyne_111

27 Oct 2023 10:49AM UTC coverage: 91.582% (+0.01%) from 91.571%
thomas.goyne_111

push

Evergreen

web-flow
Merge pull request #7085 from realm/release/13.23.2

Release/13.23.2

91742 of 168234 branches covered (0.0%)

230135 of 251288 relevant lines covered (91.58%)

6778766.91 hits per line

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

61.39
/src/realm/sync/transform.cpp
1
#include <algorithm>
2
#include <functional>
3
#include <utility>
4
#include <vector>
5
#include <map>
6
#include <sstream>
7
#include <fstream>
8

9
#if REALM_DEBUG
10
#include <iostream> // std::cerr used for debug tracing
11
#include <mutex>    // std::unique_lock used for debug tracing
12
#endif              // REALM_DEBUG
13

14
#include <realm/util/buffer.hpp>
15
#include <realm/string_data.hpp>
16
#include <realm/data_type.hpp>
17
#include <realm/mixed.hpp>
18
#include <realm/column_fwd.hpp>
19
#include <realm/db.hpp>
20
#include <realm/impl/transact_log.hpp>
21
#include <realm/replication.hpp>
22
#include <realm/sync/instructions.hpp>
23
#include <realm/sync/protocol.hpp>
24
#include <realm/sync/transform.hpp>
25
#include <realm/sync/changeset_parser.hpp>
26
#include <realm/sync/changeset_encoder.hpp>
27
#include <realm/sync/noinst/changeset_index.hpp>
28
#include <realm/sync/noinst/protocol_codec.hpp>
×
29
#include <realm/util/logger.hpp>
×
30

×
31
namespace realm {
×
32

33
namespace {
34

×
35
#if REALM_DEBUG
36
#if defined(_MSC_VER)
37
#define TERM_RED ""
38
#define TERM_YELLOW ""
39
#define TERM_CYAN ""
40
#define TERM_MAGENTA ""
41
#define TERM_GREEN ""
42
#define TERM_BOLD ""
43
#define TERM_RESET ""
44
#else
12,013,642✔
45
#define TERM_RED "\x1b[31;22m"
12,013,642✔
46
#define TERM_YELLOW "\x1b[33;22m"
47
#define TERM_CYAN "\x1b[36;22m"
48
#define TERM_MAGENTA "\x1b[35;22m"
49
#define TERM_GREEN "\x1b[32;22m"
50
#define TERM_BOLD "\x1b[1m"
51
#define TERM_RESET "\x1b[39;49;22m"
31,988✔
52
#endif
16,660✔
53
#endif
31,566✔
54

31,988✔
55
} // unnamed namespace
56

57
using namespace realm;
×
58
using namespace realm::sync;
×
59
using namespace realm::util;
×
60

61
namespace _impl {
×
62

×
63
struct TransformerImpl::Discriminant {
×
64
    timestamp_type timestamp;
65
    file_ident_type client_file_ident;
66
    Discriminant(timestamp_type t, file_ident_type p)
67
        : timestamp(t)
68
        , client_file_ident(p)
69
    {
70
    }
71

72
    Discriminant(const Discriminant&) = default;
73
    Discriminant& operator=(const Discriminant&) = default;
74

75
    bool operator<(const Discriminant& other) const
76
    {
77
        return timestamp == other.timestamp ? (client_file_ident < other.client_file_ident)
78
                                            : timestamp < other.timestamp;
79
    }
80

836,754✔
81
    bool operator==(const Discriminant& other) const
836,754✔
82
    {
83
        return timestamp == other.timestamp && client_file_ident == other.client_file_ident;
84
    }
85
    bool operator!=(const Discriminant& other) const
86
    {
87
        return !((*this) == other);
88
    }
×
89
};
×
90

×
91
struct TransformerImpl::Side {
×
92
    Transformer& m_transformer;
93
    Changeset* m_changeset = nullptr;
94
    Discriminant m_discriminant;
32✔
95

16✔
96
    bool was_discarded = false;
32✔
97
    bool was_replaced = false;
32✔
98
    size_t m_path_len = 0;
99

100
    Side(Transformer& transformer)
35,702✔
101
        : m_transformer(transformer)
17,982✔
102
        , m_discriminant(0, 0)
35,702✔
103
    {
35,702✔
104
    }
105

106
    virtual void skip_tombstones() noexcept = 0;
×
107
    virtual void next_instruction() noexcept = 0;
×
108
    virtual Instruction& get() noexcept = 0;
×
109

110
    void substitute(const Instruction& instr)
111
    {
63,976✔
112
        was_replaced = true;
63,976✔
113
        get() = instr;
63,976✔
114
    }
115

116
    StringData get_string(StringBufferRange range) const
×
117
    {
118
        // Relying on the transaction parser to only provide valid StringBufferRanges.
119
        return m_changeset->get_string(range);
×
120
    }
×
121

×
122
    StringData get_string(InternString intern_string) const
123
    {
124
        // Rely on the parser having checked the consistency of the interned strings
×
125
        return m_changeset->get_string(intern_string);
×
126
    }
×
127

×
128
    InternString intern_string(StringData data) const
×
129
    {
×
130
        return m_changeset->intern_string(data);
×
131
    }
×
132

×
133
    const Discriminant& timestamp() const
134
    {
135
        return m_discriminant;
136
    }
×
137

×
138
    InternString adopt_string(const Side& other_side, InternString other_string)
×
139
    {
×
140
        // FIXME: This needs to change if we choose to compare strings through a
×
141
        // mapping of InternStrings.
×
142
        StringData string = other_side.get_string(other_string);
×
143
        return intern_string(string);
×
144
    }
×
145

×
146
    Instruction::PrimaryKey adopt_key(const Side& other_side, const Instruction::PrimaryKey& other_key)
×
147
    {
×
148
        if (auto str = mpark::get_if<InternString>(&other_key)) {
×
149
            return adopt_string(other_side, *str);
×
150
        }
×
151
        else {
×
152
            // Non-string keys do not need to be adopted.
×
153
            return other_key;
×
154
        }
155
    }
156

157
    void adopt_path(Instruction::PathInstruction& instr, const Side& other_side,
11,176,826✔
158
                    const Instruction::PathInstruction& other)
11,176,826✔
159
    {
11,176,826✔
160
        instr.table = adopt_string(other_side, other.table);
11,176,826✔
161
        instr.object = adopt_key(other_side, other.object);
11,176,826✔
162
        instr.field = adopt_string(other_side, other.field);
163
        instr.path.m_path.clear();
164
        instr.path.m_path.reserve(other.path.size());
165
        for (auto& element : other.path.m_path) {
166
            auto push = util::overload{
167
                [&](uint32_t index) {
418,378✔
168
                    instr.path.m_path.push_back(index);
418,378✔
169
                },
170
                [&](InternString str) {
171
                    instr.path.m_path.push_back(adopt_string(other_side, str));
172
                },
173
            };
174
            mpark::visit(push, element);
175
        }
176
    }
177

8,580,606✔
178
protected:
8,580,606✔
179
    void init_with_instruction(const Instruction& instr) noexcept
8,580,606✔
180
    {
8,580,606✔
181
        was_discarded = false;
8,580,606✔
182
        was_replaced = false;
8,580,606✔
183
        m_path_len = instr.path_length();
4,303,652✔
184
    }
8,580,606✔
185
};
4,303,652✔
186

8,580,606✔
187
struct TransformerImpl::MajorSide : TransformerImpl::Side {
8,580,606✔
188
    MajorSide(Transformer& transformer)
189
        : Side(transformer)
190
    {
36,951,138✔
191
    }
36,954,246✔
192

3,108✔
193
    void set_next_changeset(Changeset* changeset) noexcept;
3,108✔
194
    void discard();
36,951,138✔
195
    void prepend(Instruction operation);
196
    template <class InputIterator>
197
    void prepend(InputIterator begin, InputIterator end);
8,513,922✔
198

8,513,922✔
199
    void init_with_instruction(Changeset::iterator position) noexcept
8,514,134✔
200
    {
8,514,134✔
201
        REALM_ASSERT(position >= m_changeset->begin());
8,514,134✔
202
        REALM_ASSERT(position != m_changeset->end());
8,513,922✔
203
        m_position = position;
204
        skip_tombstones();
205
        REALM_ASSERT(position != m_changeset->end());
38,740,050✔
206

38,740,050✔
207
        m_discriminant = Discriminant{m_changeset->origin_timestamp, m_changeset->origin_file_ident};
38,740,050✔
208

209
        Side::init_with_instruction(get());
210
    }
7,659,566✔
211

7,659,566✔
212
    void skip_tombstones() noexcept final
7,659,566✔
213
    {
214
        while (m_position != m_changeset->end() && !*m_position) {
215
            ++m_position;
216
        }
217
    }
218

219
    void next_instruction() noexcept final
220
    {
221
        REALM_ASSERT(m_position != m_changeset->end());
222
        do {
418,378✔
223
            ++m_position;
418,378✔
224
        } while (m_position != m_changeset->end() && !*m_position);
225
    }
226

227
    Instruction& get() noexcept final
228
    {
229
        return **m_position;
230
    }
231

×
232
    size_t get_object_ids_in_current_instruction(_impl::ChangesetIndex::GlobalID* ids, size_t max_ids)
×
233
    {
×
234
        return _impl::get_object_ids_in_instruction(*m_changeset, get(), ids, max_ids);
×
235
    }
236

237
    Changeset::iterator m_position;
8,580,736✔
238
};
8,580,736✔
239

8,580,736✔
240
struct TransformerImpl::MinorSide : TransformerImpl::Side {
241
    using Position = _impl::ChangesetIndex::RangeIterator;
242

59,915,058✔
243
    MinorSide(Transformer& transformer)
59,915,058✔
244
        : Side(transformer)
59,915,058✔
245
    {
246
    }
247

15,988,680✔
248
    void discard();
15,988,680✔
249
    void prepend(Instruction operation);
2,783,622✔
250
    template <class InputIterator>
2,783,622✔
251
    void prepend(InputIterator begin, InputIterator end);
13,205,058✔
252

13,205,058✔
253
    void substitute(const Instruction& instr)
13,205,058✔
254
    {
15,988,680✔
255
        was_replaced = true;
256
        get() = instr;
257
    }
16,187,898✔
258

16,187,898✔
259
    Position begin() noexcept
5,343,386✔
260
    {
10,844,512✔
261
        return Position{m_conflict_ranges};
10,844,512✔
262
    }
263

264
    Position end() noexcept
10,844,914✔
265
    {
11,490,060✔
266
        return Position{m_conflict_ranges, Position::end_tag{}};
645,146✔
267
    }
645,146✔
268

10,844,914✔
269
    void update_changeset_pointer() noexcept
10,844,914✔
270
    {
271
        if (REALM_LIKELY(m_position != end())) {
272
            m_changeset = m_position.m_outer->first;
2,481,478✔
273
        }
2,481,478✔
274
        else {
2,481,478✔
275
            m_changeset = nullptr;
2,481,478✔
276
        }
2,481,478✔
277
    }
2,481,478✔
278

279
    void skip_tombstones() noexcept final
280
    {
16,518,728✔
281
        if (m_position != end() && *m_position)
16,518,728✔
282
            return;
16,518,728✔
283
        skip_tombstones_slow();
16,518,728✔
284
    }
16,518,728✔
285

286
    REALM_NOINLINE void skip_tombstones_slow() noexcept
287
    {
2,596,552✔
288
        while (m_position != end() && !*m_position) {
1,256,756✔
289
            ++m_position;
2,596,552✔
290
        }
2,596,552✔
291
        update_changeset_pointer();
2,596,552✔
292
    }
2,596,552✔
293

2,596,552✔
294
    void next_instruction() noexcept final
1,256,756✔
295
    {
2,596,552✔
296
        REALM_ASSERT(m_position != end());
1,256,756✔
297
        ++m_position;
2,596,552✔
298
        update_changeset_pointer();
2,596,552✔
299
        skip_tombstones();
300
    }
301

302
    Instruction& get() noexcept final
303
    {
304
        Instruction* instr = *m_position;
305
        REALM_ASSERT(instr != nullptr);
306
        return *instr;
307
    }
308

309
    void init_with_instruction(Position position)
310
    {
311
        // REALM_ASSERT(position >= Position(m_conflict_ranges));
312
        REALM_ASSERT(position != end());
313
        m_position = position;
314
        update_changeset_pointer();
315
        skip_tombstones();
316
        REALM_ASSERT(position != end());
317

318
        m_discriminant = Discriminant{m_changeset->origin_timestamp, m_changeset->origin_file_ident};
319

320
        Side::init_with_instruction(get());
321
    }
322

×
323
    _impl::ChangesetIndex::RangeIterator m_position;
×
324
    _impl::ChangesetIndex* m_changeset_index = nullptr;
×
325
    _impl::ChangesetIndex::Ranges* m_conflict_ranges = nullptr;
326
};
327

328
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug utilities
329

330
struct TransformerImpl::MergeTracer {
331
public:
332
    Side& m_minor;
333
    Side& m_major;
334
    const Changeset& m_minor_log;
×
335
    const Changeset& m_major_log;
×
336
    Instruction minor_before;
337
    Instruction major_before;
338

339
    // field => pair(original_value, change)
340
    struct Diff {
341
        std::map<std::string, std::pair<int64_t, int64_t>> numbers;
342
        std::map<std::string, std::pair<std::string, std::string>> strings;
343

344
        bool empty() const noexcept
×
345
        {
×
346
            return numbers.empty() && strings.empty();
×
347
        }
348
    };
349

×
350
    explicit MergeTracer(Side& minor, Side& major)
×
351
        : m_minor(minor)
×
352
        , m_major(major)
353
        , m_minor_log(*minor.m_changeset)
354
        , m_major_log(*major.m_changeset)
×
355
        , minor_before(minor.get())
×
356
        , major_before(major.get())
×
357
    {
358
    }
359

360
    struct FieldTracer : sync::Changeset::Reflector::Tracer {
×
361
        std::string m_name;
×
362
        std::map<std::string, std::string, std::less<>> m_fields;
×
363

×
364
        const Changeset* m_changeset = nullptr;
×
365

366
        void set_changeset(const Changeset* changeset) override
367
        {
×
368
            m_changeset = changeset;
×
369
        }
×
370

371
        StringData get_string(InternString str)
372
        {
×
373
            return m_changeset->get_string(str);
×
374
        }
×
375

376
        void name(StringData n) override
377
        {
×
378
            m_name = n;
×
379
        }
×
380

381
        void path(StringData n, InternString table, const Instruction::PrimaryKey& pk,
382
                  util::Optional<InternString> field, const Instruction::Path* path) override
×
383
        {
×
384
            std::stringstream ss;
×
385
            m_changeset->print_path(ss, table, pk, field, path);
×
386
            m_fields.emplace(n, ss.str());
×
387
        }
×
388

389
        void field(StringData n, InternString str) override
390
        {
×
391
            m_fields.emplace(n, get_string(str));
×
392
        }
×
393

×
394
        void field(StringData n, Instruction::Payload::Type type) override
×
395
        {
396
            m_fields.emplace(n, get_type_name(type));
397
        }
×
398

×
399
        void field(StringData n, Instruction::AddColumn::CollectionType type) override
×
400
        {
×
401
            m_fields.emplace(n, get_collection_type(type));
×
402
        }
403

404
        void field(StringData n, const Instruction::PrimaryKey& key) override
×
405
        {
×
406
            auto real_key = m_changeset->get_key(key);
×
407
            std::stringstream ss;
×
408
            ss << format_pk(real_key);
×
409
            m_fields.emplace(n, ss.str());
410
        }
411

412
        void field(StringData n, const Instruction::Payload& value) override
413
        {
414
            std::stringstream ss;
415
            m_changeset->print_value(ss, value);
416
            m_fields.emplace(n, ss.str());
417
        }
418

419
        void field(StringData n, const Instruction::Path& value) override
420
        {
×
421
            std::stringstream ss;
×
422
            m_changeset->print_path(ss, value);
423
            m_fields.emplace(n, ss.str());
424
        }
×
425

×
426
        void field(StringData n, uint32_t value) override
×
427
        {
428
            std::stringstream ss;
429
            ss << value;
×
430
            m_fields.emplace(n, ss.str());
×
431
        }
×
432
    };
433

434
    struct PrintDiffTracer : sync::Changeset::Reflector::Tracer {
×
435
        std::ostream& m_os;
×
436
        const FieldTracer& m_before;
×
437
        bool m_first = true;
438
        const Changeset* m_changeset = nullptr;
439

440
        PrintDiffTracer(std::ostream& os, const FieldTracer& before)
×
441
            : m_os(os)
×
442
            , m_before(before)
×
443
        {
×
444
        }
×
445

446
        void set_changeset(const Changeset* changeset) override
447
        {
×
448
            m_changeset = changeset;
×
449
        }
×
450

451
        StringData get_string(InternString str) const noexcept
452
        {
×
453
            return m_changeset->get_string(str);
×
454
        }
×
455

456
        void name(StringData n) override
457
        {
×
458
            m_os << std::left << std::setw(16) << std::string(n);
×
459
        }
×
460

461
        void path(StringData n, InternString table, const Instruction::PrimaryKey& pk,
462
                  util::Optional<InternString> field, const Instruction::Path* path) override
×
463
        {
×
464
            std::stringstream ss;
×
465
            m_changeset->print_path(ss, table, pk, field, path);
×
466
            diff_field(n, ss.str());
×
467
        }
468

469
        void field(StringData n, InternString str) override
×
470
        {
×
471
            diff_field(n, get_string(str));
×
472
        }
×
473

×
474
        void field(StringData n, Instruction::Payload::Type type) override
475
        {
476
            diff_field(n, get_type_name(type));
×
477
        }
×
478

×
479
        void field(StringData n, Instruction::AddColumn::CollectionType type) override
×
480
        {
×
481
            diff_field(n, get_collection_type(type));
482
        }
483

×
484
        void field(StringData n, const Instruction::PrimaryKey& value) override
×
485
        {
×
486
            std::stringstream ss;
×
487
            ss << format_pk(m_changeset->get_key(value));
×
488
            diff_field(n, ss.str());
489
        }
490

×
491
        void field(StringData n, const Instruction::Payload& value) override
×
492
        {
×
493
            std::stringstream ss;
×
494
            m_changeset->print_value(ss, value);
×
495
            diff_field(n, ss.str());
×
496
        }
×
497

×
498
        void field(StringData n, const Instruction::Path& value) override
×
499
        {
×
500
            std::stringstream ss;
×
501
            m_changeset->print_path(ss, value);
×
502
            diff_field(n, ss.str());
×
503
        }
×
504

×
505
        void field(StringData n, uint32_t value) override
×
506
        {
507
            std::stringstream ss;
508
            ss << value;
509
            diff_field(n, ss.str());
×
510
        }
×
511

×
512
        void diff_field(StringData name, std::string value)
×
513
        {
×
514
            std::stringstream ss;
515
            ss << name << "=";
516
            auto it = m_before.m_fields.find(name);
517
            if (it == m_before.m_fields.end() || it->second == value) {
×
518
                ss << value;
×
519
            }
×
520
            else {
×
521
                ss << it->second << "->" << value;
×
522
            }
×
523
            if (!m_first) {
×
524
                m_os << ", ";
×
525
            }
×
526
            m_os << ss.str();
×
527
            m_first = false;
×
528
        }
×
529
    };
×
530

×
531
    static void print_instr(std::ostream& os, const Instruction& instr, const Changeset& changeset)
×
532
    {
×
533
        Changeset::Printer printer{os};
×
534
        Changeset::Reflector reflector{printer, changeset};
×
535
        instr.visit(reflector);
×
536
    }
×
537

×
538
    bool print_diff(std::ostream& os, bool print_unmodified, const Instruction& before, const Changeset& before_log,
×
539
                    Side& side) const
×
540
    {
×
541
        if (side.was_discarded) {
×
542
            print_instr(os, before, before_log);
×
543
            os << " (DISCARDED)";
544
        }
545
        else if (side.was_replaced) {
×
546
            print_instr(os, before, before_log);
×
547
            os << " (REPLACED)";
×
548
        }
×
549
        else {
×
550
            Instruction after = side.get();
×
551
            if (print_unmodified || (before != after)) {
×
552
                FieldTracer before_tracer;
×
553
                before_tracer.set_changeset(&before_log);
×
554
                PrintDiffTracer after_tracer{os, before_tracer};
×
555
                Changeset::Reflector before_reflector{before_tracer, *side.m_changeset};
×
556
                Changeset::Reflector after_reflector{after_tracer, *side.m_changeset};
×
557
                before.visit(before_reflector);
×
558
                after.visit(after_reflector); // This prints the diff'ed instruction
×
559
            }
×
560
            else {
561
                os << "(=)";
×
562
            }
×
563
        }
564
        return true;
×
565
    }
×
566

×
567
    void print_diff(std::ostream& os, bool print_unmodified) const
×
568
    {
569
        bool must_print_minor = m_minor.was_discarded || m_minor.was_replaced;
570
        if (!must_print_minor) {
×
571
            Instruction minor_after = m_minor.get();
×
572
            must_print_minor = (minor_before != minor_after);
×
573
        }
×
574
        bool must_print_major = m_major.was_discarded || m_major.was_replaced;
×
575
        if (!must_print_major) {
×
576
            Instruction major_after = m_major.get();
×
577
            must_print_major = (major_before != major_after);
×
578
        }
×
579
        bool must_print = (print_unmodified || must_print_minor || must_print_major);
580
        if (must_print) {
581
            std::stringstream ss_minor;
582
            std::stringstream ss_major;
583

584
            print_diff(ss_minor, true, minor_before, m_minor_log, m_minor);
585
            print_diff(ss_major, print_unmodified, major_before, m_major_log, m_major);
586

587
            os << std::left << std::setw(80) << ss_minor.str();
588
            os << ss_major.str() << "\n";
589
        }
590
    }
591

592
    void pad_or_ellipsis(std::ostream& os, const std::string& str, int width) const
418,376✔
593
    {
418,376✔
594
        // FIXME: Does not work with UTF-8.
595
        if (str.size() > size_t(width)) {
596
            os << str.substr(0, width - 1) << "~";
9,895,400✔
597
        }
9,895,400✔
598
        else {
9,895,400✔
599
            os << std::left << std::setw(width) << str;
4,951,190✔
600
        }
18,476,016✔
601
    }
8,580,616✔
602
};
4,303,656✔
603
#endif // LCOV_EXCL_STOP REALM_DEBUG
8,580,616✔
604

8,580,616✔
605

8,580,616✔
606
struct TransformerImpl::Transformer {
8,580,616✔
607
    MajorSide m_major_side;
4,303,656✔
608
    MinorSide m_minor_side;
8,580,616✔
609
    MinorSide::Position m_minor_end;
4,270,408✔
610
    bool m_trace;
8,513,942✔
611

8,580,616✔
612
    Transformer(bool trace)
8,580,616✔
613
        : m_major_side{*this}
9,895,400✔
614
        , m_minor_side{*this}
615
        , m_trace{trace}
616
    {
8,580,550✔
617
    }
8,580,550✔
618

4,303,656✔
619
    void transform()
8,580,550✔
620
    {
454,042✔
621
        m_major_side.m_position = m_major_side.m_changeset->begin();
454,042✔
622
        m_major_side.skip_tombstones();
454,042✔
623

921,096✔
624
        while (m_major_side.m_position != m_major_side.m_changeset->end()) {
921,096✔
625
            m_major_side.init_with_instruction(m_major_side.m_position);
334,188✔
626

680,716✔
627
            set_conflict_ranges();
×
628
            m_minor_end = m_minor_side.end();
×
629
            m_minor_side.m_position = m_minor_side.begin();
680,716✔
630
            transform_major();
680,716✔
631

921,096✔
632
            if (!m_major_side.was_discarded)
921,096✔
633
                // Discarding the instruction moves to the next one.
7,659,454✔
634
                m_major_side.next_instruction();
3,849,614✔
635
            m_major_side.skip_tombstones();
3,849,614✔
636
        }
3,849,614✔
637
    }
3,849,614✔
638

7,659,454✔
639
    _impl::ChangesetIndex::Ranges* get_conflict_ranges_for_instruction(const Instruction& instr)
7,659,454✔
640
    {
7,659,454✔
641
        _impl::ChangesetIndex& index = *m_minor_side.m_changeset_index;
7,659,454✔
642

3,849,614✔
643
        if (_impl::is_schema_change(instr)) {
7,659,454✔
644
            ///
×
645
            /// CONFLICT GROUP: Everything touching that class
×
646
            ///
×
647
            auto ranges = index.get_everything();
×
648
            if (!ranges->empty()) {
×
649
#if REALM_DEBUG // LCOV_EXCL_START
×
650
                if (m_trace) {
×
651
                    std::cerr << TERM_RED << "Conflict group: Everything (due to schema change)\n" << TERM_RESET;
×
652
                }
×
653
#endif // REALM_DEBUG LCOV_EXCL_STOP
×
654
            }
×
655
            return ranges;
7,659,454✔
656
        }
7,659,454✔
657
        else {
7,659,454✔
658
            ///
74✔
659
            /// CONFLICT GROUP: Everything touching the involved objects,
74✔
660
            /// including schema changes.
148✔
661
            ///
148✔
662
            _impl::ChangesetIndex::GlobalID major_ids[2];
7,659,454✔
663
            size_t num_major_ids = m_major_side.get_object_ids_in_current_instruction(major_ids, 2);
7,659,454✔
664
            REALM_ASSERT(num_major_ids <= 2);
8,580,550✔
665
            REALM_ASSERT(num_major_ids >= 1);
666
#if REALM_DEBUG // LCOV_EXCL_START
667
            if (m_trace) {
8,580,564✔
668
                std::cerr << TERM_RED << "Conflict group: ";
8,580,564✔
669
                if (num_major_ids == 0) {
8,580,564✔
670
                    std::cerr << "(nothing - no object references)";
4,303,646✔
671
                }
8,580,564✔
672
                for (size_t i = 0; i < num_major_ids; ++i) {
673
                    std::cerr << major_ids[i].table_name << "[" << format_pk(major_ids[i].object_id) << "]";
674
                    if (i + 1 != num_major_ids)
9,895,498✔
675
                        std::cerr << ", ";
9,895,498✔
676
                }
9,895,498✔
677
                std::cerr << "\n" << TERM_RESET;
9,895,498✔
678
            }
9,895,498✔
679
#endif // REALM_DEBUG LCOV_EXCL_STOP
680
            auto ranges = index.get_modifications_for_object(major_ids[0]);
681
            if (num_major_ids == 2) {
66,730✔
682
                // Check that the index has correctly joined the ranges for the
66,730✔
683
                // two object IDs.
66,730✔
684
                REALM_ASSERT(ranges == index.get_modifications_for_object(major_ids[1]));
66,730✔
685
            }
66,730✔
686
            return ranges;
687
        }
688
    }
66,140✔
689

66,140✔
690
    void set_conflict_ranges()
66,140✔
691
    {
66,140✔
692
        const auto& major_instr = m_major_side.get();
66,140✔
693
        m_minor_side.m_conflict_ranges = get_conflict_ranges_for_instruction(major_instr);
66,140✔
694
        /* m_minor_side.m_changeset_index->verify(); */
695
    }
696

697
    void set_next_major_changeset(Changeset* changeset) noexcept
×
698
    {
×
699
        m_major_side.m_changeset = changeset;
×
700
        m_major_side.m_position = changeset->begin();
×
701
        m_major_side.skip_tombstones();
×
702
    }
×
703

×
704
    void discard_major()
×
705
    {
706
        m_major_side.m_position = m_major_side.m_changeset->erase_stable(m_major_side.m_position);
707
        m_major_side.was_discarded = true; // This terminates the loop in transform_major();
×
708
        m_major_side.m_changeset->set_dirty(true);
×
709
    }
×
710

×
711
    void discard_minor()
×
712
    {
713
        m_minor_side.was_discarded = true;
714
        m_minor_side.m_position = m_minor_side.m_changeset_index->erase_instruction(m_minor_side.m_position);
715
        m_minor_side.m_changeset->set_dirty(true);
×
716
        m_minor_side.update_changeset_pointer();
×
717
    }
×
718

×
719
    template <class InputIterator>
×
720
    void prepend_major(InputIterator instr_begin, InputIterator instr_end)
×
721
    {
×
722
        REALM_ASSERT(*m_major_side.m_position); // cannot prepend a tombstone
723
        auto insert_position = m_major_side.m_position;
×
724
        m_major_side.m_position = m_major_side.m_changeset->insert_stable(insert_position, instr_begin, instr_end);
×
725
        m_major_side.m_changeset->set_dirty(true);
×
726
        size_t num_prepended = instr_end - instr_begin;
×
727
        transform_prepended_major(num_prepended);
×
728
    }
729

730
    void prepend_major(Instruction instr)
×
731
    {
×
732
        const Instruction* begin = &instr;
×
733
        const Instruction* end = begin + 1;
×
734
        prepend_major(begin, end);
×
735
    }
736

737
    template <class InputIterator>
×
738
    void prepend_minor(InputIterator instr_begin, InputIterator instr_end)
×
739
    {
×
740
        REALM_ASSERT(*m_minor_side.m_position); // cannot prepend a tombstone
741
        auto insert_position = m_minor_side.m_position.m_pos;
742
        m_minor_side.m_position.m_pos =
743
            m_minor_side.m_changeset->insert_stable(insert_position, instr_begin, instr_end);
744
        m_minor_side.m_changeset->set_dirty(true);
×
745
        size_t num_prepended = instr_end - instr_begin;
×
746
        // Go back to the instruction that initiated this prepend
747
        for (size_t i = 0; i < num_prepended; ++i) {
×
748
            ++m_minor_side.m_position;
×
749
        }
×
750
        REALM_ASSERT(m_minor_end == m_minor_side.end());
×
751
    }
×
752

×
753
    void prepend_minor(Instruction instr)
×
754
    {
755
        const Instruction* begin = &instr;
×
756
        const Instruction* end = begin + 1;
×
757
        prepend_minor(begin, end);
×
758
    }
×
759

×
760
    void transform_prepended_major(size_t num_prepended)
761
    {
762
        auto orig_major_was_discarded = m_major_side.was_discarded;
×
763
        auto orig_major_path_len = m_major_side.m_path_len;
764

×
765
        // Reset 'was_discarded', as it should refer to the prepended
×
766
        // instructions in the below, not the instruction that instigated the
767
        // prepend.
×
768
        m_major_side.was_discarded = false;
×
769
        REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
×
770

×
771
#if defined(REALM_DEBUG) // LCOV_EXCL_START
×
772
        if (m_trace) {
×
773
            std::cerr << std::setw(80) << " ";
774
            MergeTracer::print_instr(std::cerr, m_major_side.get(), *m_major_side.m_changeset);
×
775
            std::cerr << " (PREPENDED " << num_prepended << ")\n";
×
776
        }
×
777
#endif // REALM_DEBUG LCOV_EXCL_STOP
778

×
779
        for (size_t i = 0; i < num_prepended; ++i) {
×
780
            auto orig_minor_index = m_minor_side.m_position;
×
781
            auto orig_minor_was_discarded = m_minor_side.was_discarded;
×
782
            auto orig_minor_was_replaced = m_minor_side.was_replaced;
×
783
            auto orig_minor_path_len = m_minor_side.m_path_len;
×
784

785
            // Skip the instruction that initiated this prepend.
×
786
            if (!m_minor_side.was_discarded) {
×
787
                // Discarding an instruction moves to the next.
×
788
                m_minor_side.next_instruction();
×
789
            }
×
790

791
            REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
×
792
            m_major_side.init_with_instruction(m_major_side.m_position);
×
793
            REALM_ASSERT(!m_major_side.was_discarded);
×
794
            REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
795
            transform_major();
796
            if (!m_major_side.was_discarded) {
8,580,724✔
797
                // Discarding an instruction moves to the next.
8,580,724✔
798
                m_major_side.next_instruction();
4,303,736✔
799
            }
8,580,724✔
800
            REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
8,580,724✔
801

8,580,724✔
802
            m_minor_side.m_position = orig_minor_index;
8,580,724✔
803
            m_minor_side.was_discarded = orig_minor_was_discarded;
4,303,736✔
804
            m_minor_side.was_replaced = orig_minor_was_replaced;
11,110,548✔
805
            m_minor_side.m_path_len = orig_minor_path_len;
2,596,554✔
806
            m_minor_side.update_changeset_pointer();
1,256,750✔
807
        }
2,596,554✔
808

2,596,554✔
809
#if defined(REALM_DEBUG) // LCOV_EXCL_START
×
810
        if (m_trace) {
×
811
            std::cerr << TERM_CYAN << "(end transform of prepended major)\n" << TERM_RESET;
×
812
        }
×
813
#endif // REALM_DEBUG LCOV_EXCL_STOP
×
814

×
815
        m_major_side.was_discarded = orig_major_was_discarded;
×
816
        m_major_side.m_path_len = orig_major_path_len;
2,596,554✔
817
    }
2,596,554✔
818

2,596,554✔
819
    void transform_major()
2,596,554✔
820
    {
2,596,554✔
821
        m_minor_side.skip_tombstones();
2,596,554✔
822

1,256,750✔
823
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug tracing
2,596,554✔
824
        const bool print_noop_merges = false;
66,730✔
825
        bool new_major = true; // print an instruction every time we go to the next major regardless
2,529,824✔
826
#endif                         // LCOV_EXCL_STOP REALM_DEBUG
1,199,394✔
827

2,481,484✔
828
        while (m_minor_side.m_position != m_minor_end) {
2,529,824✔
829
            m_minor_side.init_with_instruction(m_minor_side.m_position);
2,529,824✔
830

8,580,724✔
831
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug tracing
832
            if (m_trace) {
833
                MergeTracer tracer{m_minor_side, m_major_side};
834
                merge_instructions(m_major_side, m_minor_side);
835
                if (new_major)
836
                    std::cerr << TERM_CYAN << "\n(new major round)\n" << TERM_RESET;
9,895,506✔
837
                tracer.print_diff(std::cerr, new_major || print_noop_merges);
9,895,506✔
838
                new_major = false;
9,895,506✔
839
            }
840
            else {
66,730✔
841
#endif // LCOV_EXCL_STOP REALM_DEBUG
66,730✔
842
                merge_instructions(m_major_side, m_minor_side);
66,730✔
843
#if defined(REALM_DEBUG) // LCOV_EXCL_START
844
            }
×
845
#endif // LCOV_EXCL_STOP REALM_DEBUG
×
846

×
847
            if (m_major_side.was_discarded)
848
                break;
849
            if (!m_minor_side.was_discarded)
850
                // Discarding an instruction moves to the next one.
851
                m_minor_side.next_instruction();
852
            m_minor_side.skip_tombstones();
853
        }
66,140✔
854
    }
66,140✔
855

66,140✔
856
    void merge_instructions(MajorSide& left, MinorSide& right);
857
    template <class OuterSide, class InnerSide>
×
858
    void merge_nested(OuterSide& outer, InnerSide& inner);
×
859
};
×
860

861
void TransformerImpl::MajorSide::set_next_changeset(Changeset* changeset) noexcept
862
{
863
    m_transformer.set_next_major_changeset(changeset);
864
}
865
void TransformerImpl::MajorSide::discard()
866
{
867
    m_transformer.discard_major();
50✔
868
}
50✔
869
void TransformerImpl::MajorSide::prepend(Instruction operation)
50✔
870
{
871
    m_transformer.prepend_major(std::move(operation));
872
}
873
template <class InputIterator>
50✔
874
void TransformerImpl::MajorSide::prepend(InputIterator begin, InputIterator end)
50✔
875
{
50✔
876
    m_transformer.prepend_major(std::move(begin), std::move(end));
877
}
878
void TransformerImpl::MinorSide::discard()
×
879
{
×
880
    m_transformer.discard_minor();
×
881
}
×
882
void TransformerImpl::MinorSide::prepend(Instruction operation)
×
883
{
884
    m_transformer.prepend_minor(std::move(operation));
885
}
886
template <class InputIterator>
887
void TransformerImpl::MinorSide::prepend(InputIterator begin, InputIterator end)
888
{
889
    m_transformer.prepend_minor(std::move(begin), std::move(end));
890
}
891
} // namespace _impl
892

893
namespace {
1,229,774✔
894

1,229,774✔
895
REALM_NORETURN void throw_bad_merge(std::string msg)
896
{
897
    throw sync::TransformError{std::move(msg)};
898
}
899

900
template <class... Params>
901
REALM_NORETURN void bad_merge(const char* msg, Params&&... params)
1,296,834✔
902
{
629,964✔
903
    throw_bad_merge(util::format(msg, std::forward<Params>(params)...));
1,296,834✔
904
}
1,296,834✔
905

906
REALM_NORETURN void bad_merge(_impl::TransformerImpl::Side& side, Instruction::PathInstruction instr,
907
                              const std::string& msg)
301,438✔
908
{
147,624✔
909
    std::stringstream ss;
147,624✔
910
    side.m_changeset->print_path(ss, instr.table, instr.object, instr.field, &instr.path);
301,438✔
911
    bad_merge("%1 (instruction target: %2). Please contact support.", msg, ss.str());
301,438✔
912
}
301,438✔
913

301,438✔
914
template <class LeftInstruction, class RightInstruction, class Enable = void>
915
struct Merge;
916
template <class Outer>
216✔
917
struct MergeNested;
216✔
918

108✔
919
struct MergeUtils {
216✔
920
    using TransformerImpl = _impl::TransformerImpl;
160✔
921
    MergeUtils(TransformerImpl::Side& left_side, TransformerImpl::Side& right_side)
28✔
922
        : m_left_side(left_side)
56✔
923
        , m_right_side(right_side)
✔
924
    {
×
925
    }
✔
926

×
927
    // CAUTION: All of these utility functions rely implicitly on the "left" and
✔
928
    // "right" arguments corresponding to the left and right sides. If the
×
929
    // arguments are switched, mayhem ensues.
✔
930

×
931
    bool same_string(InternString left, InternString right) const noexcept
✔
932
    {
×
933
        // FIXME: Optimize string comparison by building a map of InternString values up front.
24✔
934
        return m_left_side.m_changeset->get_string(left) == m_right_side.m_changeset->get_string(right);
24✔
935
    }
✔
936

×
937
    bool same_key(const Instruction::PrimaryKey& left, const Instruction::PrimaryKey& right) const noexcept
16✔
938
    {
16✔
939
        // FIXME: Once we can compare string by InternString map lookups,
✔
940
        // compare the string components of the keys using that.
×
941
        PrimaryKey left_key = m_left_side.m_changeset->get_key(left);
✔
942
        PrimaryKey right_key = m_right_side.m_changeset->get_key(right);
×
943
        return left_key == right_key;
16✔
944
    }
16✔
945

✔
946
    bool same_payload(const Instruction::Payload& left, const Instruction::Payload& right)
×
947
    {
✔
948
        using Type = Instruction::Payload::Type;
×
949

✔
950
        if (left.type != right.type)
×
951
            return false;
×
952

×
953
        switch (left.type) {
×
954
            case Type::Null:
×
955
                return true;
×
956
            case Type::Erased:
×
957
                return true;
✔
958
            case Type::Dictionary:
×
959
                return true;
✔
960
            case Type::ObjectValue:
×
961
                return true;
×
962
            case Type::GlobalKey:
963
                return left.data.key == right.data.key;
×
964
            case Type::Int:
×
965
                return left.data.integer == right.data.integer;
966
            case Type::Bool:
967
                return left.data.boolean == right.data.boolean;
968
            case Type::String:
1,476✔
969
                return m_left_side.get_string(left.data.str) == m_right_side.get_string(right.data.str);
1,476✔
970
            case Type::Binary:
1,392✔
971
                return m_left_side.get_string(left.data.binary) == m_right_side.get_string(right.data.binary);
1,308✔
972
            case Type::Timestamp:
1,308✔
973
                return left.data.timestamp == right.data.timestamp;
1,002✔
974
            case Type::Float:
168✔
975
                return left.data.fnum == right.data.fnum;
168✔
976
            case Type::Double:
918✔
977
                return left.data.dnum == right.data.dnum;
978
            case Type::Decimal:
979
                return left.data.decimal == right.data.decimal;
×
980
            case Type::Link: {
×
981
                if (!same_key(left.data.link.target, right.data.link.target)) {
1,476✔
982
                    return false;
1,476✔
983
                }
1,476✔
984
                auto left_target = m_left_side.get_string(left.data.link.target_table);
985
                auto right_target = m_right_side.get_string(right.data.link.target_table);
986
                return left_target == right_target;
10,198✔
987
            }
10,198✔
988
            case Type::ObjectId:
10,420✔
989
                return left.data.object_id == right.data.object_id;
1,468✔
990
            case Type::UUID:
1,180✔
991
                return left.data.uuid == right.data.uuid;
1,180✔
992
        }
1,468✔
993

9,686✔
994
        bad_merge("Invalid payload type in instruction");
66✔
995
    }
66✔
996

66✔
997
    bool same_path_element(const Instruction::Path::Element& left,
998
                           const Instruction::Path::Element& right) const noexcept
999
    {
1000
        const auto& pred = util::overload{
1,220,854✔
1001
            [&](uint32_t lhs, uint32_t rhs) {
1,220,854✔
1002
                return lhs == rhs;
1,220,854✔
1003
            },
1004
            [&](InternString lhs, InternString rhs) {
1005
                return same_string(lhs, rhs);
1006
            },
1,000,310✔
1007
            [&](const auto&, const auto&) {
1,000,310✔
1008
                // FIXME: Paths contain incompatible element types. Should we raise an
1,000,310✔
1009
                // error here?
1010
                return false;
1011
            },
1012
        };
37,616✔
1013
        return mpark::visit(pred, left, right);
37,616✔
1014
    }
37,616✔
1015

18,266!
1016
    bool same_path(const Instruction::Path& left, const Instruction::Path& right) const noexcept
×
1017
    {
37,616✔
1018
        if (left.size() == right.size()) {
18,266✔
1019
            for (size_t i = 0; i < left.size(); ++i) {
37,616✔
1020
                if (!same_path_element(left[i], right[i])) {
37,616✔
1021
                    return false;
37,616✔
1022
                }
37,616!
1023
            }
37,616✔
1024
            return true;
37,616✔
1025
        }
1026
        return false;
1027
    }
1028

214,294✔
1029
    bool same_table(const Instruction::TableInstruction& left,
214,294✔
1030
                    const Instruction::TableInstruction& right) const noexcept
214,294✔
1031
    {
1032
        return same_string(left.table, right.table);
1033
    }
28,652✔
1034

28,652✔
1035
    bool same_object(const Instruction::ObjectInstruction& left,
28,652✔
1036
                     const Instruction::ObjectInstruction& right) const noexcept
1037
    {
1038
        return same_table(left, right) && same_key(left.object, right.object);
33,672✔
1039
    }
17,784✔
1040

17,784✔
1041
    template <class Left, class Right>
17,784✔
1042
    bool same_column(const Left& left, const Right& right) const noexcept
17,784✔
1043
    {
33,672✔
1044
        if constexpr (std::is_convertible_v<const Right&, const Instruction::PathInstruction&>) {
33,648✔
1045
            const Instruction::PathInstruction& rhs = right;
×
1046
            return same_table(left, right) && same_string(left.field, rhs.field);
17,772✔
1047
        }
33,648✔
1048
        else if constexpr (std::is_convertible_v<const Right&, const Instruction::ObjectInstruction&>) {
×
1049
            // CreateObject/EraseObject do not have a column built in.
×
1050
            return false;
×
1051
        }
×
1052
        else {
33,648✔
1053
            return same_table(left, right) && same_string(left.field, right.field);
24✔
1054
        }
24✔
1055
    }
24✔
1056

1057
    bool same_field(const Instruction::PathInstruction& left,
1058
                    const Instruction::PathInstruction& right) const noexcept
1059
    {
144,650✔
1060
        return same_object(left, right) && same_string(left.field, right.field);
144,650✔
1061
    }
144,650✔
1062

1063
    bool same_path(const Instruction::PathInstruction& left, const Instruction::PathInstruction& right) const noexcept
1064
    {
1065
        return same_field(left, right) && same_path(left.path, right.path);
1066
    }
1067

1068
    bool same_container(const Instruction::Path& left, const Instruction::Path& right) const noexcept
×
1069
    {
×
1070
        // The instructions refer to the same container if the paths have the
×
1071
        // same length, and elements [0..n-1] are equal (so the last element is
1072
        // disregarded). If the path length is 1, this counts as referring to
1073
        // the same container.
163,276✔
1074
        if (left.size() == right.size()) {
163,276✔
1075
            if (left.size() == 0)
163,276✔
1076
                return true;
1077

1078
            for (size_t i = 0; i < left.size() - 1; ++i) {
×
1079
                if (!same_path_element(left[i], right[i])) {
×
1080
                    return false;
×
1081
                }
×
1082
            }
1083
            return true;
1084
        }
×
1085
        return false;
×
1086
    }
×
1087

×
1088
    bool same_container(const Instruction::PathInstruction& left,
1089
                        const Instruction::PathInstruction& right) const noexcept
1090
    {
×
1091
        return same_field(left, right) && same_container(left.path, right.path);
×
1092
    }
×
1093

1094
    // NOTE: `is_prefix_of()` should only return true if the left is a strictly
1095
    // shorter path than the right, and the entire left path is the initial
1096
    // sequence of the right.
×
1097

×
1098
    bool is_prefix_of(const Instruction::AddTable& left, const Instruction::TableInstruction& right) const noexcept
×
1099
    {
1100
        return same_table(left, right);
1101
    }
×
1102

1103
    bool is_prefix_of(const Instruction::EraseTable& left, const Instruction::TableInstruction& right) const noexcept
×
1104
    {
×
1105
        return same_table(left, right);
1106
    }
1107

1108
    bool is_prefix_of(const Instruction::AddColumn&, const Instruction::TableInstruction&) const noexcept
245,798✔
1109
    {
245,798✔
1110
        // Right side is a schema instruction.
245,798✔
1111
        return false;
1112
    }
1113

×
1114
    bool is_prefix_of(const Instruction::EraseColumn&, const Instruction::TableInstruction&) const noexcept
1115
    {
1116
        // Right side is a schema instruction.
×
1117
        return false;
×
1118
    }
1119

1120
    bool is_prefix_of(const Instruction::AddColumn& left, const Instruction::ObjectInstruction& right) const noexcept
1121
    {
40,968✔
1122
        return same_column(left, right);
40,968✔
1123
    }
416✔
1124

8✔
1125
    bool is_prefix_of(const Instruction::EraseColumn& left,
8✔
1126
                      const Instruction::ObjectInstruction& right) const noexcept
8✔
1127
    {
8✔
1128
        return same_column(left, right);
412✔
1129
    }
40,552✔
1130

40,552✔
1131
    bool is_prefix_of(const Instruction::ObjectInstruction&, const Instruction::TableInstruction&) const noexcept
40,552✔
1132
    {
1133
        // Right side is a schema instruction.
1134
        return false;
1135
    }
1136

1137
    bool is_prefix_of(const Instruction::ObjectInstruction& left,
1138
                      const Instruction::PathInstruction& right) const noexcept
24✔
1139
    {
24✔
1140
        return same_object(left, right);
24✔
1141
    }
×
1142

×
1143
    bool is_prefix_of(const Instruction::PathInstruction&, const Instruction::TableInstruction&) const noexcept
×
1144
    {
×
1145
        // Path instructions can never be full prefixes of table-level instructions. Note that this also covers
24✔
1146
        // ObjectInstructions.
×
1147
        return false;
×
1148
    }
×
1149

1150
    bool is_prefix_of(const Instruction::PathInstruction& left,
1151
                      const Instruction::PathInstruction& right) const noexcept
×
1152
    {
×
1153
        if (left.path.size() < right.path.size() && same_field(left, right)) {
×
1154
            for (size_t i = 0; i < left.path.size(); ++i) {
1155
                if (!same_path_element(left.path[i], right.path[i])) {
1156
                    return false;
1157
                }
×
1158
            }
×
1159
            return true;
×
1160
        }
×
1161
        return false;
×
1162
    }
×
1163

×
1164
    // True if the left side is an instruction that touches a container within
×
1165
    // right's path. Equivalent to is_prefix_of, except the last element (the
1166
    // index) is not considered.
1167
    bool is_container_prefix_of(const Instruction::PathInstruction& left,
1168
                                const Instruction::PathInstruction& right) const
×
1169
    {
×
1170
        if (left.path.size() != 0 && left.path.size() < right.path.size() && same_field(left, right)) {
×
1171
            for (size_t i = 0; i < left.path.size() - 1; ++i) {
×
1172
                if (!same_path_element(left.path[i], right.path[i])) {
×
1173
                    return false;
×
1174
                }
1175
            }
1176
            return true;
×
1177
        }
×
1178
        return false;
×
1179
    }
1180

1181
    bool is_container_prefix_of(const Instruction::PathInstruction&, const Instruction::TableInstruction&) const
×
1182
    {
×
1183
        return false;
×
1184
    }
1185

1186
    bool value_targets_table(const Instruction::Payload& value,
1187
                             const Instruction::TableInstruction& right) const noexcept
1188
    {
1189
        if (value.type == Instruction::Payload::Type::Link) {
1190
            StringData target_table = m_left_side.get_string(value.data.link.target_table);
1191
            StringData right_table = m_right_side.get_string(right.table);
1192
            return target_table == right_table;
24✔
1193
        }
24✔
1194
        return false;
24✔
1195
    }
24✔
1196

24✔
1197
    bool value_targets_object(const Instruction::Payload& value,
24✔
1198
                              const Instruction::ObjectInstruction& right) const noexcept
×
1199
    {
×
1200
        if (value_targets_table(value, right)) {
24✔
1201
            return same_key(value.data.link.target, right.object);
24✔
1202
        }
1203
        return false;
1204
    }
1205

×
1206
    bool value_targets_object(const Instruction::Update& left, const Instruction::ObjectInstruction& right) const
1207
    {
1208
        return value_targets_object(left.value, right);
×
1209
    }
×
1210

1211
    bool value_targets_object(const Instruction::ArrayInsert& left, const Instruction::ObjectInstruction& right) const
1212
    {
1213
        return value_targets_object(left.value, right);
×
1214
    }
×
1215

1216
    // When the left side has a shorter path, get the path component on the
1217
    // right that corresponds to the last component on the left.
1218
    //
1219
    // Note that this will only be used in the context of array indices, because
×
1220
    // those are the only path components that are modified during OT.
×
1221
    uint32_t& corresponding_index_in_path(const Instruction::PathInstruction& left,
×
1222
                                          Instruction::PathInstruction& right) const
1223
    {
×
1224
        REALM_ASSERT(left.path.size() != 0);
×
1225
        REALM_ASSERT(left.path.size() < right.path.size());
×
1226
        REALM_ASSERT(mpark::holds_alternative<uint32_t>(left.path.back()));
1227
        size_t index = left.path.size() - 1;
×
1228
        if (!mpark::holds_alternative<uint32_t>(right.path[index])) {
×
1229
            bad_merge("Inconsistent paths");
×
1230
        }
×
1231
        return mpark::get<uint32_t>(right.path[index]);
×
1232
    }
1233

1234
    uint32_t& corresponding_index_in_path(const Instruction::PathInstruction&,
1235
                                          const Instruction::TableInstruction&) const
1236
    {
1237
        // A path instruction can never have a shorter path than something that
1238
        // isn't a PathInstruction.
1239
        REALM_UNREACHABLE();
1240
    }
1241

1242
    void merge_get_vs_move(uint32_t& get_ndx, const uint32_t& move_from_ndx,
1243
                           const uint32_t& move_to_ndx) const noexcept
1244
    {
1245
        if (get_ndx == move_from_ndx) {
1246
            // CONFLICT: Update of a moved element.
779,652✔
1247
            //
779,652✔
1248
            // RESOLUTION: On the left side, use the MOVE operation to transform the
1249
            // UPDATE operation received from the right side.
1250
            get_ndx = move_to_ndx; // --->
1251
        }
1252
        else {
1253
            // Right update vs left remove
1254
            if (get_ndx > move_from_ndx) {
1255
                get_ndx -= 1; // --->
1256
            }
1257
            // Right update vs left insert
1258
            if (get_ndx >= move_to_ndx) {
1259
                get_ndx += 1; // --->
1260
            }
1261
        }
1262
    }
1263

1264
protected:
1265
    TransformerImpl::Side& m_left_side;
1266
    TransformerImpl::Side& m_right_side;
779,652✔
1267
};
779,652✔
1268

1269
template <class LeftInstruction, class RightInstruction>
1270
struct MergeBase : MergeUtils {
1271
    static const Instruction::Type A = Instruction::GetInstructionType<LeftInstruction>::value;
1272
    static const Instruction::Type B = Instruction::GetInstructionType<RightInstruction>::value;
779,652✔
1273
    static_assert(A >= B, "A < B. Please reverse the order of instruction types. :-)");
779,652✔
1274

779,652✔
1275
    MergeBase(TransformerImpl::Side& left_side, TransformerImpl::Side& right_side)
779,652✔
1276
        : MergeUtils(left_side, right_side)
1277
    {
1278
    }
1279
    MergeBase(MergeBase&&) = delete;
1280
};
1281

1282
#define DEFINE_MERGE(A, B)                                                                                           \
1283
    template <>                                                                                                      \
1284
    struct Merge<A, B> {                                                                                             \
1285
        template <class LeftSide, class RightSide>                                                                   \
1286
        struct DoMerge : MergeBase<A, B> {                                                                           \
1287
            A& left;                                                                                                 \
1288
            B& right;                                                                                                \
1289
            LeftSide& left_side;                                                                                     \
1,758,508✔
1290
            RightSide& right_side;                                                                                   \
1,758,508✔
1291
            DoMerge(A& left, B& right, LeftSide& left_side, RightSide& right_side)                                   \
1292
                : MergeBase<A, B>(left_side, right_side)                                                             \
1293
                , left(left)                                                                                         \
1294
                , right(right)                                                                                       \
1295
                , left_side(left_side)                                                                               \
1296
                , right_side(right_side)                                                                             \
1297
            {                                                                                                        \
1298
            }                                                                                                        \
1299
            void do_merge();                                                                                         \
1300
        };                                                                                                           \
1301
        template <class LeftSide, class RightSide>                                                                   \
1302
        static inline void merge(A& left, B& right, LeftSide& left_side, RightSide& right_side)                      \
1303
        {                                                                                                            \
1304
            DoMerge<LeftSide, RightSide> do_merge{left, right, left_side, right_side};                               \
1305
            do_merge.do_merge();                                                                                     \
1306
        }                                                                                                            \
1307
    };                                                                                                               \
1308
    template <class LeftSide, class RightSide>                                                                       \
1309
    void Merge<A, B>::DoMerge<LeftSide, RightSide>::do_merge()
450,122✔
1310

450,122✔
1311
#define DEFINE_MERGE_NOOP(A, B)                                                                                      \
1312
    template <>                                                                                                      \
1313
    struct Merge<A, B> {                                                                                             \
1314
        static const Instruction::Type left_type = Instruction::GetInstructionType<A>::value;                        \
1315
        static const Instruction::Type right_type = Instruction::GetInstructionType<B>::value;                       \
450,122✔
1316
        static_assert(left_type >= right_type,                                                                       \
450,122✔
1317
                      "left_type < right_type. Please reverse the order of instruction types. :-)");                 \
450,122✔
1318
        template <class LeftSide, class RightSide>                                                                   \
450,122✔
1319
        static inline void merge(A&, B&, LeftSide&, RightSide&)                                                      \
1320
        { /* Do nothing */                                                                                           \
1321
        }                                                                                                            \
1322
    }
1323

1324

1325
#define DEFINE_NESTED_MERGE(A)                                                                                       \
1326
    template <>                                                                                                      \
1327
    struct MergeNested<A> {                                                                                          \
1328
        template <class B, class OuterSide, class InnerSide>                                                         \
644,396✔
1329
        struct DoMerge : MergeUtils {                                                                                \
644,396✔
1330
            A& outer;                                                                                                \
1331
            B& inner;                                                                                                \
1332
            OuterSide& outer_side;                                                                                   \
1333
            InnerSide& inner_side;                                                                                   \
1334
            DoMerge(A& outer, B& inner, OuterSide& outer_side, InnerSide& inner_side)                                \
1335
                : MergeUtils(outer_side, inner_side)                                                                 \
1336
                , outer(outer)                                                                                       \
1337
                , inner(inner)                                                                                       \
1338
                , outer_side(outer_side)                                                                             \
1339
                , inner_side(inner_side)                                                                             \
901,738✔
1340
            {                                                                                                        \
901,738✔
1341
            }                                                                                                        \
901,738✔
1342
            void do_merge();                                                                                         \
1343
        };                                                                                                           \
1344
        template <class B, class OuterSide, class InnerSide>                                                         \
1345
        static inline void merge(A& outer, B& inner, OuterSide& outer_side, InnerSide& inner_side)                   \
1346
        {                                                                                                            \
1347
            DoMerge<B, OuterSide, InnerSide> do_merge{outer, inner, outer_side, inner_side};                         \
1348
            do_merge.do_merge();                                                                                     \
1349
        }                                                                                                            \
1350
    };                                                                                                               \
1351
    template <class B, class OuterSide, class InnerSide>                                                             \
1352
    void MergeNested<A>::DoMerge<B, OuterSide, InnerSide>::do_merge()
1353

1354
#define DEFINE_NESTED_MERGE_NOOP(A)                                                                                  \
1355
    template <>                                                                                                      \
1356
    struct MergeNested<A> {                                                                                          \
1357
        template <class B, class OuterSide, class InnerSide>                                                         \
1358
        static inline void merge(const A&, const B&, const OuterSide&, const InnerSide&)                             \
1359
        { /* Do nothing */                                                                                           \
1360
        }                                                                                                            \
1361
    }
1362

1363
// Implementation that reverses order.
1364
template <class A, class B>
1365
struct Merge<A, B,
1366
             typename std::enable_if<(Instruction::GetInstructionType<A>::value <
1367
                                      Instruction::GetInstructionType<B>::value)>::type> {
1368
    template <class LeftSide, class RightSide>
1369
    static void merge(A& left, B& right, LeftSide& left_side, RightSide& right_side)
14,162✔
1370
    {
14,162✔
1371
        Merge<B, A>::merge(right, left, right_side, left_side);
7,350✔
1372
    }
7,350✔
1373
};
7,222✔
1374

7,222✔
1375
///
7,222✔
1376
///  GET READY!
7,222✔
1377
///
6✔
1378
///  Realm supports 14 instructions at the time of this writing. Each
6✔
1379
///  instruction type needs one rule for each other instruction type. We only
6✔
1380
///  define one rule to handle each combination (A vs B and B vs A are handle by
6✔
1381
///  a single rule).
3,678✔
1382
///
7,222✔
1383
///  This gives (14 * (14 + 1)) / 2 = 105 merge rules below.
8✔
1384
///
8✔
1385
///  Merge rules are ordered such that the second instruction type is always of
8✔
1386
///  a lower enum value than the first.
8✔
1387
///
8✔
1388
///  Nested merge rules apply when one instruction has a strictly longer path
3,678✔
1389
///  than another. All instructions that have a path of the same length will
7,222✔
1390
///  meet each other through regular merge rules, regardless of whether they
8✔
1391
///  share a prefix.
8✔
1392
///
8✔
1393

8✔
1394

3,678✔
1395
/// AddTable rules
7,222✔
1396

4✔
1397
DEFINE_NESTED_MERGE_NOOP(Instruction::AddTable);
4✔
1398

7,222✔
1399
DEFINE_MERGE(Instruction::AddTable, Instruction::AddTable)
×
1400
{
×
1401
    if (same_table(left, right)) {
×
1402
        StringData left_name = left_side.get_string(left.table);
7,222✔
1403
        if (auto left_spec = mpark::get_if<Instruction::AddTable::TopLevelTable>(&left.type)) {
128✔
1404
            if (auto right_spec = mpark::get_if<Instruction::AddTable::TopLevelTable>(&right.type)) {
128✔
1405
                StringData left_pk_name = left_side.get_string(left_spec->pk_field);
×
1406
                StringData right_pk_name = right_side.get_string(right_spec->pk_field);
×
1407
                if (left_pk_name != right_pk_name) {
128✔
1408
                    bad_merge(
3,742✔
1409
                        "Schema mismatch: '%1' has primary key '%2' on one side, but primary key '%3' on the other.",
3,742✔
1410
                        left_name, left_pk_name, right_pk_name);
3,742✔
1411
                }
7,350✔
1412

7,350✔
1413
                if (left_spec->pk_type != right_spec->pk_type) {
7,350✔
1414
                    bad_merge("Schema mismatch: '%1' has primary key '%2', which is of type %3 on one side and type "
7,350✔
1415
                              "%4 on the other.",
14,162✔
1416
                              left_name, left_pk_name, get_type_name(left_spec->pk_type),
1417
                              get_type_name(right_spec->pk_type));
1418
                }
4,036✔
1419

4,036✔
1420
                if (left_spec->pk_nullable != right_spec->pk_nullable) {
×
1421
                    bad_merge("Schema mismatch: '%1' has primary key '%2', which is nullable on one side, but not "
×
1422
                              "the other.",
4,036✔
1423
                              left_name, left_pk_name);
1424
                }
1425

1426
                if (left_spec->is_asymmetric != right_spec->is_asymmetric) {
1427
                    bad_merge("Schema mismatch: '%1' is asymmetric on one side, but not on the other.", left_name);
1428
                }
1429
            }
1430
            else {
1431
                bad_merge("Schema mismatch: '%1' has a primary key on one side, but not on the other.", left_name);
1432
            }
1433
        }
1434
        else if (mpark::get_if<Instruction::AddTable::EmbeddedTable>(&left.type)) {
1435
            if (!mpark::get_if<Instruction::AddTable::EmbeddedTable>(&right.type)) {
1436
                bad_merge("Schema mismatch: '%1' is an embedded table on one side, but not the other.", left_name);
1437
            }
1438
        }
1439

1440
        // Names are the same, PK presence is the same, and if there is a primary
163,276✔
1441
        // key, its name, type, and nullability are the same. Discard both sides.
163,276!
1442
        left_side.discard();
36,344✔
1443
        right_side.discard();
36,344✔
1444
        return;
163,276✔
1445
    }
1446
}
1447

1,456✔
1448
DEFINE_MERGE(Instruction::EraseTable, Instruction::AddTable)
1,456✔
1449
{
296✔
1450
    if (same_table(left, right)) {
296✔
1451
        right_side.discard();
296✔
1452
    }
1,456✔
1453
}
1454

1455
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::AddTable);
1456
DEFINE_MERGE_NOOP(Instruction::EraseObject, Instruction::AddTable);
1457
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::AddTable);
1458
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::AddTable);
1459
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::AddTable);
1460
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::AddTable);
1461
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::AddTable);
8,864✔
1462
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::AddTable);
4,156✔
1463
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::AddTable);
4,156✔
1464
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::AddTable);
8,864!
1465
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::AddTable);
1466
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::AddTable);
×
1467

×
1468
/// EraseTable rules
×
1469

×
1470
DEFINE_NESTED_MERGE(Instruction::EraseTable)
×
1471
{
×
1472
    if (is_prefix_of(outer, inner)) {
8,864✔
1473
        inner_side.discard();
1474
    }
1475
}
1476

1477
DEFINE_MERGE(Instruction::EraseTable, Instruction::EraseTable)
1478
{
1479
    if (same_table(left, right)) {
1480
        left_side.discard();
1481
        right_side.discard();
1482
    }
1483
}
1484

1485
// Handled by nesting rule.
1486
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::EraseTable);
1487
DEFINE_MERGE_NOOP(Instruction::EraseObject, Instruction::EraseTable);
1488
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::EraseTable);
1489
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::EraseTable);
1490

1491
DEFINE_MERGE(Instruction::AddColumn, Instruction::EraseTable)
1492
{
1493
    // AddColumn on an erased table handled by nesting.
398,900✔
1494

398,900✔
1495
    if (left.type == Instruction::Payload::Type::Link && same_string(left.link_target_table, right.table)) {
7,906✔
1496
        // Erase of a table where the left side adds a link column targeting it.
7,906✔
1497
        Instruction::EraseColumn erase_column;
7,906✔
1498
        erase_column.table = right_side.adopt_string(left_side, left.table);
15,536✔
1499
        erase_column.field = right_side.adopt_string(left_side, left.field);
15,536✔
1500
        right_side.prepend(erase_column);
398,900✔
1501
        left_side.discard();
1502
    }
1503
}
1504

1505
// Handled by nested rule.
1506
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::EraseTable);
1507
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseTable);
1508
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::EraseTable);
1509
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::EraseTable);
1510
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::EraseTable);
1511
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::EraseTable);
1512
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::EraseTable);
1513

1514

1515
/// CreateObject rules
1516

1517
// CreateObject cannot interfere with instructions that have a longer path.
245,798✔
1518
DEFINE_NESTED_MERGE_NOOP(Instruction::CreateObject);
245,798!
1519

10,534✔
1520
// CreateObject is idempotent.
21,664✔
1521
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::CreateObject);
21,664✔
1522

245,798✔
1523
DEFINE_MERGE(Instruction::EraseObject, Instruction::CreateObject)
1524
{
1525
    if (same_object(left, right)) {
141,316✔
1526
        // CONFLICT: Create and Erase of the same object.
141,316✔
1527
        //
7,504✔
1528
        // RESOLUTION: Erase always wins.
7,504✔
1529
        right_side.discard();
7,504✔
1530
    }
14,308✔
1531
}
7,154✔
1532

7,154✔
1533
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::CreateObject);
7,154✔
1534
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::CreateObject);
7,154✔
1535
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::CreateObject);
7,154✔
1536
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::CreateObject);
14,308✔
1537
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::CreateObject);
141,316✔
1538
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::CreateObject);
1539
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::CreateObject);
1540
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::CreateObject);
1541
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::CreateObject);
1542
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::CreateObject);
1543

1544

1545
/// Erase rules
1546

1547
DEFINE_NESTED_MERGE(Instruction::EraseObject)
1548
{
1549
    if (is_prefix_of(outer, inner)) {
1550
        // Erase always wins.
1551
        inner_side.discard();
1552
    }
1553
}
1554

1555
DEFINE_MERGE(Instruction::EraseObject, Instruction::EraseObject)
40,314✔
1556
{
40,314✔
1557
    if (same_object(left, right)) {
18,314✔
1558
        // We keep the most recent erase. This prevents the situation where a
40,314!
1559
        // high number of EraseObject instructions in the past trumps a
32✔
1560
        // Erase-Create pair in the future.
32✔
1561
        if (right_side.timestamp() < left_side.timestamp()) {
64✔
1562
            right_side.discard();
64✔
1563
        }
18,282✔
1564
        else {
18,282✔
1565
            left_side.discard();
18,282✔
1566
        }
40,250!
1567
    }
80✔
1568
}
80✔
1569

40,250✔
1570
// Handled by nested merge.
1571
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::EraseObject);
1572
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::EraseObject);
25,900✔
1573
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::EraseObject);
12,812✔
1574
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::EraseObject);
12,812✔
1575
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseObject);
25,900✔
1576
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::EraseObject);
12,812✔
1577
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::EraseObject);
25,900✔
1578
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::EraseObject);
8,248✔
1579
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::EraseObject);
8,248✔
1580
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::EraseObject);
8,248✔
1581

×
1582

×
1583
/// Set rules
4,232✔
1584

8,248✔
1585
DEFINE_NESTED_MERGE(Instruction::Update)
8,056✔
1586
{
×
1587
    using Type = Instruction::Payload::Type;
×
1588

8,056✔
1589
    if (outer.value.type == Type::ObjectValue || outer.value.type == Type::Dictionary) {
8,056✔
1590
        // Creating an embedded object or a dictionary is an idempotent
8,056✔
1591
        // operation, and should not eliminate updates to the subtree.
192✔
1592
        return;
×
1593
    }
×
1594

4,232✔
1595
    // Setting a value higher up in the hierarchy overwrites any modification to
8,248✔
1596
    // the inner value, regardless of when this happened.
112✔
1597
    if (is_prefix_of(outer, inner)) {
112✔
1598
        inner_side.discard();
112✔
1599
    }
224✔
1600
}
24✔
1601

24✔
1602
DEFINE_MERGE(Instruction::Update, Instruction::Update)
24✔
1603
{
200✔
1604
    // The two instructions are at the same level of nesting.
24✔
1605

24✔
1606
    using Type = Instruction::Payload::Type;
24✔
1607

8,200✔
1608
    if (same_path(left, right)) {
4,208✔
1609
        bool left_is_default = false;
4,208✔
1610
        bool right_is_default = false;
4,208✔
1611
        if (!(left.is_array_update() == right.is_array_update())) {
4,208✔
1612
            bad_merge(left_side, left, "Merge error: left.is_array_update() == right.is_array_update()");
4,208✔
1613
        }
4,208✔
1614

4,208✔
1615
        if (!left.is_array_update()) {
8,200✔
1616
            if (right.is_array_update()) {
8,018✔
1617
                bad_merge(right_side, right, "Merge error: !right.is_array_update()");
4,254✔
1618
            }
4,254✔
1619
            left_is_default = left.is_default;
3,764✔
1620
            right_is_default = right.is_default;
3,764✔
1621
        }
3,764✔
1622
        else if (!(left.prior_size == right.prior_size)) {
8,018✔
1623
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
182✔
1624
        }
182✔
1625

92✔
1626
        if (left.value.type != right.value.type) {
92✔
1627
            // Embedded object / dictionary creation should always lose to an
90✔
1628
            // Update(value), because these structures are nested, and we need to
90✔
1629
            // discard any update inside the structure.
90✔
1630
            if (left.value.type == Type::Dictionary || left.value.type == Type::ObjectValue) {
182✔
1631
                left_side.discard();
8,200✔
1632
                return;
25,900✔
1633
            }
1634
            else if (right.value.type == Type::Dictionary || right.value.type == Type::ObjectValue) {
1635
                right_side.discard();
2,500✔
1636
                return;
1,226✔
1637
            }
1,226✔
1638
        }
2,500✔
1639

236✔
1640
        // CONFLICT: Two updates of the same element.
236✔
1641
        //
236✔
1642
        // RESOLUTION: Suppress the effect of the UPDATE operation with the lower
236✔
1643
        // timestamp. Note that the timestamps can never be equal. This is
236✔
1644
        // achieved on both sides by discarding the received UPDATE operation if
464✔
1645
        // it has a lower timestamp than the previously applied UPDATE operation.
×
1646
        if (left_is_default == right_is_default) {
×
1647
            if (left_side.timestamp() < right_side.timestamp()) {
×
1648
                left_side.discard(); // --->
236✔
1649
            }
464✔
1650
            else {
236✔
1651
                right_side.discard(); // <---
236✔
1652
            }
464✔
1653
        }
340✔
1654
        else {
28✔
1655
            if (left_is_default) {
28✔
1656
                left_side.discard();
28✔
1657
            }
60✔
1658
            else {
60✔
1659
                right_side.discard();
144✔
1660
            }
144✔
1661
        }
280✔
1662
    }
280✔
1663
}
280✔
1664

280✔
1665
DEFINE_MERGE(Instruction::AddInteger, Instruction::Update)
124✔
1666
{
124✔
1667
    // The two instructions are at the same level of nesting.
124✔
1668

464✔
1669
    if (same_path(left, right)) {
2,500✔
1670
        // CONFLICT: Add vs Set of the same element.
1671
        //
1672
        // RESOLUTION: If the Add was later than the Set, add its value to
1673
        // the payload of the Set instruction. Otherwise, discard it.
1674

×
1675
        if (!(right.value.type == Instruction::Payload::Type::Int || right.value.is_null())) {
×
1676
            bad_merge(right_side, right,
×
1677
                      "Merge error: right.value.type == Instruction::Payload::Type::Int || right.value.is_null()");
×
1678
        }
×
1679

1680
        bool right_is_default = !right.is_array_update() && right.is_default;
1681

53,680✔
1682
        // Note: AddInteger survives SetDefault, regardless of timestamp.
53,680✔
1683
        if (right_side.timestamp() < left_side.timestamp() || right_is_default) {
8,040✔
1684
            if (right.value.is_null()) {
8,040✔
1685
                // The AddInteger happened "after" the Set(null). This becomes a
×
1686
                // no-op, but if the server later integrates a Set(int) that
×
1687
                // came-before the AddInteger, it will be taken into account again.
8,040✔
1688
                return;
×
1689
            }
×
1690

8,040✔
1691
            // Wrapping add
×
1692
            uint64_t ua = uint64_t(right.value.data.integer);
×
1693
            uint64_t ub = uint64_t(left.value);
8,040✔
1694
            right.value.data.integer = int64_t(ua + ub);
8,040✔
1695
        }
3,380✔
1696
        else {
3,380✔
1697
            left_side.discard();
8,040✔
1698
        }
53,680✔
1699
    }
1700
}
1701

24✔
1702
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::Update);
24✔
1703

×
1704
DEFINE_MERGE(Instruction::EraseColumn, Instruction::Update)
1705
{
×
1706
    if (same_column(left, right)) {
×
1707
        right_side.discard();
×
1708
    }
×
1709
}
×
1710

×
1711
DEFINE_MERGE(Instruction::ArrayInsert, Instruction::Update)
1712
{
1713
    if (same_container(left, right)) {
×
1714
        REALM_ASSERT(right.is_array_update());
×
1715
        if (!(left.prior_size == right.prior_size)) {
24✔
1716
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
1717
        }
1718
        if (!(left.index() <= left.prior_size)) {
11,152✔
1719
            bad_merge(left_side, left, "Merge error: left.index() <= left.prior_size");
11,152✔
1720
        }
2,356✔
1721
        if (!(right.index() < right.prior_size)) {
2,356✔
1722
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
1723
        }
×
1724
        right.prior_size += 1;
2,356✔
1725
        if (right.index() >= left.index()) {
×
1726
            right.index() += 1; // --->
×
1727
        }
2,356✔
1728
    }
×
1729
}
×
1730

1,360✔
1731
DEFINE_MERGE(Instruction::ArrayMove, Instruction::Update)
1,360✔
1732
{
1,360✔
1733
    if (same_container(left, right)) {
1,360✔
1734
        REALM_ASSERT(right.is_array_update());
2,356✔
1735

1,360✔
1736
        if (!(left.index() < left.prior_size)) {
2,356✔
1737
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
300✔
1738
        }
300✔
1739
        if (!(right.index() < right.prior_size)) {
300✔
1740
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
496✔
1741
        }
496✔
1742

1,860✔
1743
        // FIXME: This marks both sides as dirty, even when they are unmodified.
988✔
1744
        merge_get_vs_move(right.index(), left.index(), left.ndx_2);
988✔
1745
    }
2,356✔
1746
}
11,152✔
1747

1748
DEFINE_MERGE(Instruction::ArrayErase, Instruction::Update)
1749
{
1750
    if (same_container(left, right)) {
1751
        REALM_ASSERT(right.is_array_update());
1752
        if (!(left.prior_size == right.prior_size)) {
1753
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
1754
        }
1755
        if (!(left.index() < left.prior_size)) {
1756
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
1757
        }
1758
        if (!(right.index() < right.prior_size)) {
1759
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
1760
        }
1761

1762
        // CONFLICT: Update of a removed element.
1763
        //
1764
        // RESOLUTION: Discard the UPDATE operation received on the right side.
1765
        right.prior_size -= 1;
1766

1767
        if (left.index() == right.index()) {
1768
            // CONFLICT: Update of a removed element.
1769
            //
1770
            // RESOLUTION: Discard the UPDATE operation received on the right side.
1771
            right_side.discard();
1772
        }
1773
        else if (right.index() > left.index()) {
37,616✔
1774
            right.index() -= 1;
37,616✔
1775
        }
10,020✔
1776
    }
10,020✔
1777
}
8✔
1778

8✔
1779
// Handled by nested rule
8✔
1780
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::Update);
8✔
1781
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::Update);
4,940✔
1782
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::Update);
10,020✔
1783

8✔
1784

8✔
1785
/// AddInteger rules
8✔
1786

4,940✔
1787
DEFINE_NESTED_MERGE_NOOP(Instruction::AddInteger);
10,020✔
1788
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::AddInteger);
×
1789
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::AddInteger);
×
1790
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::AddInteger);
×
1791
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::AddInteger);
×
1792
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::AddInteger);
×
1793
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::AddInteger);
×
1794
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::AddInteger);
×
1795
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::AddInteger);
×
1796
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::AddInteger);
×
1797

×
1798

×
1799
/// AddColumn rules
×
1800

×
1801
DEFINE_NESTED_MERGE_NOOP(Instruction::AddColumn);
1802

×
1803
DEFINE_MERGE(Instruction::AddColumn, Instruction::AddColumn)
×
1804
{
×
1805
    if (same_column(left, right)) {
×
1806
        StringData left_name = left_side.get_string(left.field);
×
1807
        if (left.type != right.type) {
×
1808
            bad_merge(
4,940✔
1809
                "Schema mismatch: Property '%1' in class '%2' is of type %3 on one side and type %4 on the other.",
10,020✔
1810
                left_name, left_side.get_string(left.table), get_type_name(left.type), get_type_name(right.type));
1,932✔
1811
        }
1,932✔
1812

1,932✔
1813
        if (left.nullable != right.nullable) {
8✔
1814
            bad_merge("Schema mismatch: Property '%1' in class '%2' is nullable on one side and not on the other.",
8✔
1815
                      left_name, left_side.get_string(left.table));
8✔
1816
        }
8✔
1817

1,932✔
1818
        if (left.collection_type != right.collection_type) {
4,940✔
1819
            auto collection_type_name = [](Instruction::AddColumn::CollectionType type) -> const char* {
4,940✔
1820
                switch (type) {
4,940✔
1821
                    case Instruction::AddColumn::CollectionType::Single:
10,020✔
1822
                        return "single value";
10,020✔
1823
                    case Instruction::AddColumn::CollectionType::List:
10,020✔
1824
                        return "list";
37,616✔
1825
                    case Instruction::AddColumn::CollectionType::Dictionary:
1826
                        return "dictionary";
1827
                    case Instruction::AddColumn::CollectionType::Set:
×
1828
                        return "set";
×
1829
                }
×
1830
                REALM_TERMINATE("");
×
1831
            };
×
1832

1833
            std::stringstream ss;
1834
            const char* left_type = collection_type_name(left.collection_type);
1835
            const char* right_type = collection_type_name(right.collection_type);
1836
            bad_merge("Schema mismatch: Property '%1' in class '%2' is a %3 on one side, and a %4 on the other.",
1837
                      left_name, left_side.get_string(left.table), left_type, right_type);
1838
        }
1839

1840
        if (left.type == Instruction::Payload::Type::Link) {
1841
            StringData left_target = left_side.get_string(left.link_target_table);
1842
            StringData right_target = right_side.get_string(right.link_target_table);
1843
            if (left_target != right_target) {
1844
                bad_merge("Schema mismatch: Link property '%1' in class '%2' points to class '%3' on one side and to "
1845
                          "'%4' on the other.",
1846
                          left_name, left_side.get_string(left.table), left_target, right_target);
×
1847
            }
×
1848
        }
×
1849

×
1850
        // Name, type, nullability and link targets match -- discard both
×
1851
        // sides and proceed.
×
1852
        left_side.discard();
1853
        right_side.discard();
1854
    }
1855
}
1856

1857
DEFINE_MERGE(Instruction::EraseColumn, Instruction::AddColumn)
1858
{
1859
    if (same_column(left, right)) {
1860
        right_side.discard();
1861
    }
1862
}
1863

16✔
1864
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::AddColumn);
16!
1865
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::AddColumn);
16✔
1866
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::AddColumn);
16!
1867
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::AddColumn);
8✔
1868
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::AddColumn);
8✔
1869
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::AddColumn);
16✔
1870

16✔
1871

1872
/// EraseColumn rules
1873

54,652✔
1874
DEFINE_NESTED_MERGE_NOOP(Instruction::EraseColumn);
54,652✔
1875

15,216✔
1876
DEFINE_MERGE(Instruction::EraseColumn, Instruction::EraseColumn)
×
1877
{
×
1878
    if (same_column(left, right)) {
15,216✔
1879
        left_side.discard();
15,216✔
1880
        right_side.discard();
7,718✔
1881
    }
15,216✔
1882
}
3,036✔
1883

3,036✔
1884
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseColumn);
12,180✔
1885
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::EraseColumn);
3,040✔
1886
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::EraseColumn);
3,040✔
1887
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::EraseColumn);
9,140✔
1888
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::EraseColumn);
4,344✔
1889
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::EraseColumn);
4,344✔
1890

4,344✔
1891
/// ArrayInsert rules
4,344✔
1892

9,140✔
1893
DEFINE_NESTED_MERGE(Instruction::ArrayInsert)
4,566✔
1894
{
4,566✔
1895
    if (is_container_prefix_of(outer, inner)) {
4,574✔
1896
        auto& index = corresponding_index_in_path(outer, inner);
4,574✔
1897
        if (index >= outer.index()) {
4,574✔
1898
            index += 1;
9,140✔
1899
        }
15,216✔
1900
    }
54,652✔
1901
}
1902

1903
DEFINE_MERGE(Instruction::ArrayInsert, Instruction::ArrayInsert)
×
1904
{
×
1905
    if (same_container(left, right)) {
×
1906
        if (!(left.prior_size == right.prior_size)) {
1907
            bad_merge(right_side, right, "Exception: left.prior_size == right.prior_size");
1908
        }
×
1909
        left.prior_size++;
×
1910
        right.prior_size++;
×
1911

×
1912
        if (left.index() > right.index()) {
×
1913
            left.index() += 1; // --->
×
1914
        }
1915
        else if (left.index() < right.index()) {
1916
            right.index() += 1; // <---
×
1917
        }
×
1918
        else { // left index == right index
×
1919
            // CONFLICT: Two element insertions at the same position.
×
1920
            //
×
1921
            // Resolution: Place the inserted elements in order of increasing
×
1922
            // timestamp. Note that the timestamps can never be equal.
×
1923
            if (left_side.timestamp() < right_side.timestamp()) {
1924
                right.index() += 1;
1925
            }
1926
            else {
1927
                left.index() += 1;
×
1928
            }
×
1929
        }
×
1930
    }
×
1931
}
×
1932

×
1933
DEFINE_MERGE(Instruction::ArrayMove, Instruction::ArrayInsert)
×
1934
{
×
1935
    if (same_container(left, right)) {
×
1936
        left.prior_size += 1;
1937

1938
        // Left insertion vs right removal
22,434✔
1939
        if (right.index() > left.index()) {
22,434✔
1940
            right.index() -= 1; // --->
6,960✔
1941
        }
×
1942
        else {
×
1943
            left.index() += 1; // <---
6,960✔
1944
        }
×
1945

×
1946
        // Left insertion vs left insertion
6,960✔
1947
        if (right.index() < left.ndx_2) {
×
1948
            left.ndx_2 += 1; // <---
×
1949
        }
3,698✔
1950
        else if (right.index() > left.ndx_2) {
6,960✔
1951
            right.index() += 1; // --->
6,960✔
1952
        }
6,960✔
1953
        else { // right.index() == left.ndx_2
3,084✔
1954
            // CONFLICT: Insertion and movement to same position.
3,084✔
1955
            //
3,876✔
1956
            // RESOLUTION: Place the two elements in order of increasing
3,876✔
1957
            // timestamp. Note that the timestamps can never be equal.
3,876✔
1958
            if (left_side.timestamp() < right_side.timestamp()) {
6,960✔
1959
                left.ndx_2 += 1; // <---
22,434✔
1960
            }
1961
            else {
1962
                right.index() += 1; // --->
1963
            }
1964
        }
1965
    }
1966
}
1967

1968
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayInsert)
1969
{
1970
    if (same_container(left, right)) {
×
1971
        if (!(left.prior_size == right.prior_size)) {
×
1972
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
1973
        }
×
1974
        if (!(left.index() < left.prior_size)) {
×
1975
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
1976
        }
1977
        if (!(right.index() <= right.prior_size)) {
1978
            bad_merge(left_side, left, "Merge error: right.index() <= right.prior_size");
28✔
1979
        }
28✔
1980

28✔
1981
        left.prior_size++;
×
1982
        right.prior_size--;
×
1983
        if (right.index() <= left.index()) {
28✔
1984
            left.index() += 1; // --->
×
1985
        }
×
1986
        else {
28✔
1987
            right.index() -= 1; // <---
×
1988
        }
×
1989
    }
28✔
1990
}
×
1991

×
1992
// Handled by nested rules
28✔
1993
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayInsert);
×
1994
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayInsert);
×
1995
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::ArrayInsert);
14✔
1996

28✔
1997

4✔
1998
/// ArrayMove rules
4✔
1999

24✔
2000
DEFINE_NESTED_MERGE(Instruction::ArrayMove)
4✔
2001
{
4✔
2002
    if (is_container_prefix_of(outer, inner)) {
20✔
2003
        auto& index = corresponding_index_in_path(outer, inner);
10✔
2004
        merge_get_vs_move(outer.index(), index, outer.ndx_2);
10✔
2005
    }
10✔
2006
}
10✔
2007

10✔
2008
DEFINE_MERGE(Instruction::ArrayMove, Instruction::ArrayMove)
10✔
2009
{
10✔
2010
    if (same_container(left, right)) {
20✔
2011
        if (!(left.prior_size == right.prior_size)) {
12✔
2012
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
12✔
2013
        }
12✔
2014
        if (!(left.index() < left.prior_size)) {
×
2015
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
2016
        }
12✔
2017
        if (!(right.index() < right.prior_size)) {
8✔
2018
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
8✔
2019
        }
8✔
2020
        if (!(left.ndx_2 < left.prior_size)) {
×
2021
            bad_merge(left_side, left, "Merge error: left.ndx_2 < left.prior_size");
×
2022
        }
8✔
2023
        if (!(right.ndx_2 < right.prior_size)) {
8✔
2024
            bad_merge(right_side, right, "Merge error: right.ndx_2 < right.prior_size");
20✔
2025
        }
20✔
2026

4✔
2027
        if (left.index() < right.index()) {
4✔
2028
            right.index() -= 1; // <---
8✔
2029
        }
4✔
2030
        else if (left.index() > right.index()) {
4✔
2031
            left.index() -= 1; // --->
4✔
2032
        }
4✔
2033
        else {
4✔
2034
            // CONFLICT: Two movements of same element.
4✔
2035
            //
4✔
2036
            // RESOLUTION: Respect the MOVE operation associated with the higher
8✔
2037
            // timestamp. If the previously applied MOVE operation has the higher
4✔
2038
            // timestamp, discard the received MOVE operation, otherwise use the
4✔
2039
            // previously applied MOVE operation to transform the received MOVE
4✔
2040
            // operation. Note that the timestamps are never equal.
4✔
2041
            if (left_side.timestamp() < right_side.timestamp()) {
4✔
2042
                right.index() = left.ndx_2; // <---
4✔
2043
                left_side.discard();        // --->
4✔
2044
                if (right.index() == right.ndx_2) {
8✔
2045
                    right_side.discard(); // <---
4✔
2046
                }
4✔
2047
            }
4✔
2048
            else {
4✔
2049
                left.index() = right.ndx_2; // --->
4✔
2050
                if (left.index() == left.ndx_2) {
×
2051
                    left_side.discard(); // --->
2052
                }
2053
                right_side.discard(); // <---
2054
            }
2055
            return;
×
2056
        }
×
2057

×
2058
        // Left insertion vs right removal
×
2059
        if (left.ndx_2 > right.index()) {
×
2060
            left.ndx_2 -= 1; // --->
×
2061
        }
×
2062
        else {
4✔
2063
            right.index() += 1; // <---
8✔
2064
        }
×
2065

×
2066
        // Left removal vs right insertion
8✔
2067
        if (left.index() < right.ndx_2) {
×
2068
            right.ndx_2 -= 1; // <---
×
2069
        }
8✔
2070
        else {
28✔
2071
            left.index() += 1; // --->
2072
        }
2073

×
2074
        // Left insertion vs right insertion
×
2075
        if (left.ndx_2 < right.ndx_2) {
×
2076
            right.ndx_2 += 1; // <---
×
2077
        }
×
2078
        else if (left.ndx_2 > right.ndx_2) {
×
2079
            left.ndx_2 += 1; // --->
×
2080
        }
×
2081
        else { // left.ndx_2 == right.ndx_2
×
2082
            // CONFLICT: Two elements moved to the same position
×
2083
            //
×
2084
            // RESOLUTION: Place the moved elements in order of increasing
2085
            // timestamp. Note that the timestamps can never be equal.
×
2086
            if (left_side.timestamp() < right_side.timestamp()) {
2087
                right.ndx_2 += 1; // <---
×
2088
            }
2089
            else {
2090
                left.ndx_2 += 1; // --->
2091
            }
2092
        }
2093

×
2094
        if (left.index() == left.ndx_2) {
×
2095
            left_side.discard(); // --->
×
2096
        }
×
2097
        if (right.index() == right.ndx_2) {
2098
            right_side.discard(); // <---
×
2099
        }
×
2100
    }
×
2101
}
×
2102

×
2103
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayMove)
×
2104
{
2105
    if (same_container(left, right)) {
×
2106
        if (!(left.prior_size == right.prior_size)) {
×
2107
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
2108
        }
×
2109
        if (!(left.index() < left.prior_size)) {
×
2110
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
2111
        }
2112
        if (!(right.index() < right.prior_size)) {
×
2113
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
2114
        }
×
2115

×
2116
        right.prior_size -= 1;
×
2117

×
2118
        if (left.index() == right.index()) {
2119
            // CONFLICT: Removal of a moved element.
2120
            //
2121
            // RESOLUTION: Discard the received MOVE operation on the left side, and
2122
            // use the previously applied MOVE operation to transform the received
2123
            // REMOVE operation on the right side.
2124
            left.index() = right.ndx_2; // --->
2125
            right_side.discard();       // <---
2126
        }
2127
        else {
2128
            // Left removal vs right removal
8✔
2129
            if (left.index() > right.index()) {
8!
2130
                left.index() -= 1; // --->
2131
            }
×
2132
            else {                  // left.index() < right.index()
×
2133
                right.index() -= 1; // <---
8!
2134
            }
4✔
2135
            // Left removal vs right insertion
8✔
2136
            if (left.index() >= right.ndx_2) {
8!
2137
                left.index() += 1; // --->
8✔
2138
            }
8✔
2139
            else {
×
2140
                right.ndx_2 -= 1; // <---
×
2141
            }
×
2142

8✔
2143
            if (right.index() == right.ndx_2) {
8✔
2144
                right_side.discard(); // <---
2145
            }
2146
        }
2,680✔
2147
    }
2,680✔
2148
}
1,048✔
2149

×
2150
// Handled by nested rule.
×
2151
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayMove);
1,048✔
2152
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayMove);
×
2153
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::ArrayMove);
×
2154

1,048✔
2155

×
2156
/// ArrayErase rules
×
2157

558✔
2158
DEFINE_NESTED_MERGE(Instruction::ArrayErase)
1,048✔
2159
{
1,048✔
2160
    if (is_prefix_of(outer, inner)) {
558✔
2161
        // Erase of subtree - inner instruction touches the subtree.
1,048✔
2162
        inner_side.discard();
412✔
2163
    }
412✔
2164
    else if (is_container_prefix_of(outer, inner)) {
636✔
2165
        // Erase of a sibling element in the container - adjust the path.
416✔
2166
        auto& index = corresponding_index_in_path(outer, inner);
416✔
2167
        if (outer.index() < index) {
220✔
2168
            index -= 1;
116✔
2169
        }
116✔
2170
        else {
116✔
2171
            REALM_ASSERT(index != outer.index());
220✔
2172
        }
220✔
2173
    }
220✔
2174
}
1,048✔
2175

2,680✔
2176
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayErase)
2177
{
2178
    if (same_container(left, right)) {
2179
        if (!(left.prior_size == right.prior_size)) {
2180
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
2181
        }
2182
        if (!(left.index() < left.prior_size)) {
2183
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
2184
        }
2185
        if (!(right.index() < right.prior_size)) {
2186
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
710✔
2187
        }
468✔
2188

710!
2189
        left.prior_size -= 1;
328✔
2190
        right.prior_size -= 1;
328✔
2191

710✔
2192
        if (left.index() > right.index()) {
2193
            left.index() -= 1; // --->
2194
        }
16✔
2195
        else if (left.index() < right.index()) {
16✔
2196
            right.index() -= 1; // <---
8✔
2197
        }
8✔
2198
        else { // left.index() == right.index()
8✔
2199
            // CONFLICT: Two removals of the same element.
8✔
2200
            //
8✔
2201
            // RESOLUTION: On each side, discard the received REMOVE operation.
16✔
2202
            left_side.discard();  // --->
12✔
2203
            right_side.discard(); // <---
12✔
2204
        }
4✔
2205
    }
4✔
2206
}
4✔
2207

16✔
2208
// Handled by nested rules.
16✔
2209
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayErase);
2210
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayErase);
2211
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::ArrayErase);
8✔
2212

8!
2213

4✔
2214
/// Clear rules
4✔
2215

8✔
2216
DEFINE_NESTED_MERGE(Instruction::Clear)
2217
{
2218
    // Note: Clear instructions do not have an index in their path.
8✔
2219
    if (is_prefix_of(outer, inner)) {
8!
2220
        inner_side.discard();
4✔
2221
    }
4✔
2222
}
8✔
2223

2224
DEFINE_MERGE(Instruction::Clear, Instruction::Clear)
2225
{
2226
    if (same_path(left, right)) {
2227
        // CONFLICT: Two clears of the same container.
2228
        //
2229
        // RESOLUTION: Discard the clear with the lower timestamp. This has the
2230
        // effect of preserving insertions that came after the clear from the
156✔
2231
        // side that has the higher timestamp.
156✔
2232
        if (left_side.timestamp() < right_side.timestamp()) {
76✔
2233
            left_side.discard();
76✔
2234
        }
76✔
2235
        else {
76✔
2236
            right_side.discard();
76✔
2237
        }
76✔
2238
    }
76✔
2239
}
76✔
2240

152✔
2241
DEFINE_MERGE(Instruction::SetInsert, Instruction::Clear)
24✔
2242
{
12✔
2243
    if (same_path(left, right)) {
12✔
2244
        left_side.discard();
12✔
2245
    }
12✔
2246
}
12✔
2247

24✔
2248
DEFINE_MERGE(Instruction::SetErase, Instruction::Clear)
152✔
2249
{
156✔
2250
    if (same_path(left, right)) {
2251
        left_side.discard();
2252
    }
64✔
2253
}
64✔
2254

32✔
2255

32✔
2256
/// SetInsert rules
32✔
2257

32✔
2258
DEFINE_NESTED_MERGE_NOOP(Instruction::SetInsert);
32✔
2259

32✔
2260
DEFINE_MERGE(Instruction::SetInsert, Instruction::SetInsert)
32✔
2261
{
64✔
2262
    if (same_path(left, right)) {
×
2263
        // CONFLICT: Two inserts into the same set.
×
2264
        //
×
2265
        // RESOLUTION: If the values are the same, discard the insertion with the lower timestamp. Otherwise,
×
2266
        // do nothing.
×
2267
        //
×
2268
        // NOTE: Set insertion is idempotent. Keeping the instruction with the higher timestamp is necessary
×
2269
        // because we want to maintain associativity in the case where intermittent erases (as ordered by
64✔
2270
        // timestamp) arrive at a later point in time.
64✔
2271
        if (same_payload(left.value, right.value)) {
2272
            if (left_side.timestamp() < right_side.timestamp()) {
2273
                left_side.discard();
2274
            }
2275
            else {
2276
                right_side.discard();
2277
            }
2278
        }
×
2279
    }
×
2280
}
2281

2282
DEFINE_MERGE(Instruction::SetErase, Instruction::SetInsert)
2283
{
2284
    if (same_path(left, right)) {
×
2285
        // CONFLICT: Insertion and erase in the same set.
×
2286
        //
×
2287
        // RESOLUTION: If the inserted/erased values are the same, discard the instruction with the lower
×
2288
        // timestamp. Otherwise, do nothing.
×
2289
        //
×
2290
        // Note: Set insertion and erase are both idempotent. Keeping the instruction with the higher
×
2291
        // timestamp is necessary because we want to maintain associativity.
×
2292
        if (same_payload(left.value, right.value)) {
×
2293
            if (left_side.timestamp() < right_side.timestamp()) {
×
2294
                left_side.discard();
2295
            }
2296
            else {
2297
                right_side.discard();
2298
            }
2299
        }
2300
    }
2301
}
2302

2,538,160✔
2303

2,538,160✔
2304
/// SetErase rules.
2,538,160✔
2305

2306
DEFINE_NESTED_MERGE_NOOP(Instruction::SetErase);
2307

2308
DEFINE_MERGE(Instruction::SetErase, Instruction::SetErase)
1,094,518✔
2309
{
1,094,518✔
2310
    if (same_path(left, right)) {
1,094,518✔
2311
        // CONFLICT: Two erases in the same set.
2312
        //
2313
        // RESOLUTION: If the values are the same, discard the instruction with the lower timestamp.
2314
        // Otherwise, do nothing.
1,094,518✔
2315
        if (left.value == right.value) {
1,094,518✔
2316
            if (left_side.timestamp() < right_side.timestamp()) {
1,094,518✔
2317
                left_side.discard();
1,094,518✔
2318
            }
1,094,518✔
2319
            else {
1,094,518✔
2320
                right_side.discard();
1,094,518✔
2321
            }
2322
        }
2323
    }
2,596,536✔
2324
}
1,256,742✔
2325

2,596,536✔
2326

2,596,536✔
2327
///
1,256,742✔
2328
/// END OF MERGE RULES!
2,596,536✔
2329
///
182,686✔
2330

182,686✔
2331
} // namespace
2,596,536✔
2332

230,860✔
2333
namespace _impl {
230,860✔
2334
template <class Left, class Right>
2,596,536✔
2335
void merge_instructions_2(Left& left, Right& right, TransformerImpl::MajorSide& left_side,
532,624✔
2336
                          TransformerImpl::MinorSide& right_side)
532,624✔
2337
{
2,596,536✔
2338
    Merge<Left, Right>::merge(left, right, left_side, right_side);
606,040✔
2339
}
606,040✔
2340

1,256,742✔
2341
template <class Outer, class Inner, class OuterSide, class InnerSide>
1,256,742✔
2342
void merge_nested_2(Outer& outer, Inner& inner, OuterSide& outer_side, InnerSide& inner_side)
1,256,742✔
2343
{
1,256,742✔
2344
    MergeNested<Outer>::merge(outer, inner, outer_side, inner_side);
2,596,536✔
2345
}
453,786✔
2346

453,786✔
2347
void TransformerImpl::Transformer::merge_instructions(MajorSide& their_side, MinorSide& our_side)
29,234✔
2348
{
2,142,750✔
2349
    // FIXME: Find a way to avoid heap-copies of the path.
2,142,750✔
2350
    Instruction their_before = their_side.get();
640,732✔
2351
    Instruction our_before = our_side.get();
640,732✔
2352

29,182✔
2353
    if (their_side.get().get_if<Instruction::Update>()) {
2,538,120✔
2354
        REALM_ASSERT(their_side.m_path_len > 2);
1,228,356✔
2355
    }
2,538,134✔
2356
    if (our_side.get().get_if<Instruction::Update>()) {
1,228,354✔
2357
        REALM_ASSERT(our_side.m_path_len > 2);
1,228,354✔
2358
    }
1,228,354✔
2359
    if (their_side.get().get_if<Instruction::EraseObject>()) {
1,228,354✔
2360
        REALM_ASSERT(their_side.m_path_len == 2);
1,228,354✔
2361
    }
2,538,158✔
2362
    if (our_side.get().get_if<Instruction::EraseObject>()) {
2,538,160✔
2363
        REALM_ASSERT(our_side.m_path_len == 2);
2,538,160✔
2364
    }
2,538,160✔
2365

2,538,158✔
2366
    // Update selections on the major side (outer loop) according to events on
2,538,132✔
2367
    // the minor side (inner loop). The selection may only be impacted if the
1,228,356✔
2368
    // instruction level is lower (i.e. at a higher point in the hierarchy).
1,228,356✔
2369
    if (our_side.m_path_len < their_side.m_path_len) {
1,228,356✔
2370
        merge_nested(our_side, their_side);
1,228,356✔
2371
        if (their_side.was_discarded)
2,538,120✔
2372
            return;
2,500,596✔
2373
    }
2,500,596✔
2374
    else if (our_side.m_path_len > their_side.m_path_len) {
28,110✔
2375
        merge_nested(their_side, our_side);
28,110✔
2376
        if (our_side.was_discarded)
2,500,596✔
2377
            return;
1,228,356✔
2378
    }
2,538,120✔
2379

2,501,138✔
2380
    if (!their_side.was_discarded && !our_side.was_discarded) {
2,501,138✔
2381
        // Even if the instructions were nested, we must still perform a regular
28,114✔
2382
        // merge, because link-related instructions contain information from higher
28,114✔
2383
        // levels (both rows, columns, and tables).
2,501,138✔
2384
        //
2,538,120✔
2385
        // FIXME: This condition goes away when dangling links are implemented.
2386
        their_side.get().visit([&](auto& their_instruction) {
2387
            our_side.get().visit([&](auto& our_instruction) {
2388
                merge_instructions_2(their_instruction, our_instruction, their_side, our_side);
2389
            });
2390
        });
2391
    }
418,376✔
2392

418,376✔
2393
    // Note: `left` and/or `right` may be dangling at this point due to
418,376✔
2394
    // discard/prepend. However, if they were not discarded, their iterators are
418,376✔
2395
    // required to point to an instruction of the same type.
418,376✔
2396
    if (!their_side.was_discarded && !their_side.was_replaced) {
211,710✔
2397
        const auto& their_after = their_side.get();
418,376✔
2398
        if (!(their_after == their_before)) {
418,376!
2399
            their_side.m_changeset->set_dirty(true);
418,376✔
2400
        }
418,376✔
2401
    }
418,376✔
2402

×
2403
    if (!our_side.was_discarded && !our_side.was_replaced) {
×
2404
        const auto& our_after = our_side.get();
418,376✔
2405
        if (!(our_after == our_before)) {
418,376✔
2406
            our_side.m_changeset->set_dirty(true);
211,710✔
2407
        }
418,376✔
2408
    }
418,376✔
2409
}
418,376✔
2410

211,710✔
2411

211,710✔
2412
template <class OuterSide, class InnerSide>
211,710✔
2413
void TransformerImpl::Transformer::merge_nested(OuterSide& outer_side, InnerSide& inner_side)
211,710✔
2414
{
211,710✔
2415
    outer_side.get().visit([&](auto& outer) {
211,710✔
2416
        inner_side.get().visit([&](auto& inner) {
858,772✔
2417
            merge_nested_2(outer, inner, outer_side, inner_side);
440,396✔
2418
        });
440,396✔
2419
    });
440,396✔
2420
}
440,396✔
2421

221,608✔
2422

440,396✔
2423
void TransformerImpl::merge_changesets(file_ident_type local_file_ident, Changeset* their_changesets,
440,396✔
2424
                                       size_t their_size, Changeset** our_changesets, size_t our_size,
10,313,810✔
2425
                                       util::Logger& logger)
9,895,434✔
2426
{
9,895,434✔
2427
    REALM_ASSERT(their_size != 0);
9,895,434✔
2428
    REALM_ASSERT(our_size != 0);
9,895,434✔
2429
    bool trace = false;
9,895,434✔
2430
#if REALM_DEBUG && !REALM_UWP
4,951,186✔
2431
    // FIXME: Not thread-safe (use config parameter instead and confine environment reading to test/test_all.cpp)
9,895,434✔
2432
    const char* trace_p = ::getenv("UNITTEST_TRACE_TRANSFORM");
9,895,434✔
2433
    trace = (trace_p && StringData{trace_p} != "no");
211,710✔
2434
    static std::mutex trace_mutex;
211,710✔
2435
    util::Optional<std::unique_lock<std::mutex>> l;
858,768✔
2436
    if (trace) {
440,392✔
2437
        l = std::unique_lock<std::mutex>{trace_mutex};
440,392✔
2438
    }
440,392✔
2439
#endif
440,392✔
2440
    Transformer transformer{trace};
211,710✔
2441

418,376✔
2442
    _impl::ChangesetIndex their_index;
418,376✔
2443
    size_t their_num_instructions = 0;
418,376✔
2444
    size_t our_num_instructions = 0;
418,376✔
2445

211,710✔
2446
    // Loop through all instructions on both sides and build conflict groups.
211,710✔
2447
    // This causes the index to merge ranges that are connected by instructions
418,376✔
2448
    // on the left side, but which aren't connected on the right side.
×
2449
    // FIXME: The conflict groups can be persisted as part of the changeset to
×
2450
    // skip this step in the future.
×
2451
    for (size_t i = 0; i < their_size; ++i) {
×
2452
        size_t num_instructions = their_changesets[i].size();
×
2453
        their_num_instructions += num_instructions;
×
2454
        logger.trace("Scanning incoming changeset [%1/%2] (%3 instructions)", i + 1, their_size, num_instructions);
×
2455

×
2456
        their_index.scan_changeset(their_changesets[i]);
×
2457
    }
×
2458
    for (size_t i = 0; i < our_size; ++i) {
×
2459
        Changeset& our_changeset = *our_changesets[i];
×
2460
        size_t num_instructions = our_changeset.size();
×
2461
        our_num_instructions += num_instructions;
×
2462
        logger.trace("Scanning local changeset [%1/%2] (%3 instructions)", i + 1, our_size, num_instructions);
2463

×
2464
        their_index.scan_changeset(our_changeset);
×
2465
    }
×
2466

×
2467
    // Build the index.
2468
    for (size_t i = 0; i < their_size; ++i) {
×
2469
        logger.trace("Indexing incoming changeset [%1/%2] (%3 instructions)", i + 1, their_size,
×
2470
                     their_changesets[i].size());
×
2471
        their_index.add_changeset(their_changesets[i]);
×
2472
    }
2473

×
2474
    logger.debug("Finished changeset indexing (incoming: %1 changeset(s) / %2 instructions, local: %3 "
×
2475
                 "changeset(s) / %4 instructions, conflict group(s): %5)",
×
2476
                 their_size, their_num_instructions, our_size, our_num_instructions,
×
2477
                 their_index.get_num_conflict_groups());
2478

×
2479
#if REALM_DEBUG // LCOV_EXCL_START
×
2480
    if (trace) {
×
2481
        std::cerr << TERM_YELLOW << "\n=> PEER " << std::hex << local_file_ident
×
2482
                  << " merging "
2483
                     "changeset(s)/from peer(s):\n";
2484
        for (size_t i = 0; i < their_size; ++i) {
2485
            std::cerr << "Changeset version " << std::dec << their_changesets[i].version << " from peer "
211,710✔
2486
                      << their_changesets[i].origin_file_ident << " at timestamp "
10,313,834✔
2487
                      << their_changesets[i].origin_timestamp << "\n";
9,895,458✔
2488
        }
9,895,458✔
2489
        std::cerr << "Transforming through local changeset(s):\n";
9,895,458✔
2490
        for (size_t i = 0; i < our_size; ++i) {
9,895,458✔
2491
            std::cerr << "Changeset version " << our_changesets[i]->version << " from peer "
4,951,198✔
2492
                      << our_changesets[i]->origin_file_ident << " at timestamp "
9,895,458✔
2493
                      << our_changesets[i]->origin_timestamp << "\n";
4,951,198✔
2494
        }
9,895,458✔
2495

9,895,458✔
2496
        for (size_t i = 0; i < our_size; ++i) {
9,895,458✔
2497
            std::cerr << TERM_RED << "\nLOCAL (RECIPROCAL) CHANGESET BEFORE MERGE:\n" << TERM_RESET;
211,710✔
2498
            our_changesets[i]->print(std::cerr);
418,376✔
2499
        }
418,376✔
2500

418,376✔
2501
        for (size_t i = 0; i < their_size; ++i) {
418,376✔
2502
            std::cerr << TERM_RED << "\nINCOMING CHANGESET BEFORE MERGE:\n" << TERM_RESET;
211,710✔
2503
            their_changesets[i].print(std::cerr);
211,710✔
2504
        }
211,710✔
2505

418,376✔
2506
        std::cerr << TERM_MAGENTA << "\nINCOMING CHANGESET INDEX:\n" << TERM_RESET;
418,376✔
2507
        their_index.print(std::cerr);
211,710✔
2508
        std::cerr << '\n';
211,710✔
2509
        their_index.verify();
418,376✔
2510

×
2511
        std::cerr << TERM_YELLOW << std::setw(80) << std::left << "MERGE TRACE (incoming):"
×
2512
                  << "MERGE TRACE (local):\n"
×
2513
                  << TERM_RESET;
×
2514
    }
×
2515
#else
×
2516
    static_cast<void>(local_file_ident);
×
2517
#endif // REALM_DEBUG LCOV_EXCL_STOP
×
2518

×
2519
    for (size_t i = 0; i < our_size; ++i) {
×
2520
        logger.trace(
×
2521
            "Transforming local changeset [%1/%2] through %3 incoming changeset(s) with %4 conflict group(s)", i + 1,
418,376✔
2522
            our_size, their_size, their_index.get_num_conflict_groups());
418,376✔
2523
        Changeset* our_changeset = our_changesets[i];
2524

2525
        transformer.m_major_side.set_next_changeset(our_changeset);
2526
        // MinorSide uses the index to find the Changeset.
2527
        transformer.m_minor_side.m_changeset_index = &their_index;
2528
        transformer.transform(); // Throws
2529
    }
453,728✔
2530

453,728✔
2531
    logger.debug("Finished transforming %1 local changesets through %2 incoming changesets (%3 vs %4 "
228,720✔
2532
                 "instructions, in %5 conflict groups)",
453,728✔
2533
                 our_size, their_size, our_num_instructions, their_num_instructions,
228,720✔
2534
                 their_index.get_num_conflict_groups());
228,720✔
2535

228,720✔
2536
#if REALM_DEBUG // LCOV_EXCL_START
453,728✔
2537
    // Check that the index is still valid after transformation.
453,728✔
2538
    their_index.verify();
228,720✔
2539
#endif // REALM_DEBUG LCOV_EXCL_STOP
912,978✔
2540

232,088✔
2541
#if REALM_DEBUG // LCOV_EXCL_START
232,088✔
2542
    if (trace) {
251,206✔
2543
        for (size_t i = 0; i < our_size; ++i) {
35,310✔
2544
            std::cerr << TERM_CYAN << "\nRECIPROCAL CHANGESET AFTER MERGE:\n" << TERM_RESET;
35,310✔
2545
            our_changesets[i]->print(std::cerr);
232,088✔
2546
            std::cerr << '\n';
459,250✔
2547
        }
459,250✔
2548
        for (size_t i = 0; i < their_size; ++i) {
10,354,646✔
2549
            std::cerr << TERM_CYAN << "INCOMING CHANGESET AFTER MERGE:\n" << TERM_RESET;
10,354,646✔
2550
            their_changesets[i].print(std::cerr);
10,354,646✔
2551
            std::cerr << '\n';
10,354,646✔
2552
        }
459,254✔
2553
    }
4,951,162✔
2554
#endif // LCOV_EXCL_STOP REALM_DEBUG
9,895,392✔
2555
}
9,895,392✔
2556

9,895,392✔
2557
size_t TransformerImpl::transform_remote_changesets(TransformHistory& history, file_ident_type local_file_ident,
4,951,162✔
2558
                                                    version_type current_local_version,
9,895,392✔
2559
                                                    util::Span<Changeset> parsed_changesets,
9,895,392✔
2560
                                                    util::UniqueFunction<bool(const Changeset*)> changeset_applier,
232,088✔
2561
                                                    util::Logger& logger)
459,250✔
2562
{
232,088✔
2563
    REALM_ASSERT(local_file_ident != 0);
459,250✔
2564

418,378✔
2565
    std::vector<Changeset*> our_changesets;
211,712✔
2566

211,712✔
2567
    // p points to the beginning of a range of changesets that share the same
9,082,972✔
2568
    // "base", i.e. are based on the same local version.
9,082,972✔
2569
    auto p = parsed_changesets.begin();
9,082,972✔
2570
    auto parsed_changesets_end = parsed_changesets.end();
418,378✔
2571

232,088✔
2572
    try {
459,250✔
2573
        while (p != parsed_changesets_end) {
948,252✔
2574
            // Find the range of incoming changesets that share the same
244,912✔
2575
            // last_integrated_local_version, which means we can merge them in one go.
244,912✔
2576
            auto same_base_range_end = std::find_if(p + 1, parsed_changesets_end, [&](auto& changeset) {
244,912✔
2577
                return p->last_integrated_remote_version != changeset.last_integrated_remote_version;
489,002!
2578
            });
489,002✔
2579

459,250✔
2580
            version_type begin_version = p->last_integrated_remote_version;
×
2581
            version_type end_version = current_local_version;
×
2582
            for (;;) {
232,088✔
2583
                HistoryEntry history_entry;
459,250✔
2584
                version_type version = history.find_history_entry(begin_version, end_version, history_entry);
459,250✔
2585
                if (version == 0)
228,720✔
2586
                    break; // No more local changesets
228,720✔
2587

228,720✔
2588
                Changeset& our_changeset = get_reciprocal_transform(history, local_file_ident, version,
453,728✔
2589
                                                                    history_entry); // Throws
228,720✔
2590
                our_changesets.push_back(&our_changeset);
453,728✔
2591

453,728✔
2592
                begin_version = version;
2593
            }
2594

2595
            bool must_apply_all = false;
2596

9,895,428✔
2597
            if (!our_changesets.empty()) {
9,895,428✔
2598
                merge_changesets(local_file_ident, &*p, same_base_range_end - p, our_changesets.data(),
9,895,428✔
2599
                                 our_changesets.size(), logger); // Throws
9,856,004✔
2600
                // We need to apply all transformed changesets if at least one reciprocal changeset was modified
9,856,004✔
2601
                // during OT.
9,856,004✔
2602
                must_apply_all = std::any_of(our_changesets.begin(), our_changesets.end(), [](const Changeset* c) {
9,856,004✔
2603
                    return c->is_dirty();
50,158✔
2604
                });
50,158✔
2605
            }
50,158✔
2606

50,158✔
2607
            auto continue_applying = true;
50,158✔
2608
            for (; p != same_base_range_end && continue_applying; ++p) {
9,805,846✔
2609
                // It is safe to stop applying the changesets if:
9,805,846✔
2610
                //      1. There are no reciprocal changesets
9,805,846✔
2611
                //      2. No reciprocal changeset was modified
4,921,906✔
2612
                continue_applying = changeset_applier(p) || must_apply_all;
9,856,004✔
2613
            }
9,856,004✔
2614
            if (!continue_applying) {
9,856,004✔
2615
                break;
9,856,004✔
2616
            }
9,856,004✔
2617

5,638,650✔
2618
            our_changesets.clear(); // deliberately not releasing memory
9,856,004✔
2619
        }
9,856,004✔
2620
    }
9,895,428✔
2621
    catch (...) {
9,895,428✔
2622
        // If an exception was thrown while merging, the transform cache will
2623
        // be polluted. This is a problem since the same cache object is reused
2624
        // by multiple invocations to transform_remote_changesets(), so we must
2625
        // clear the cache before rethrowing.
453,678✔
2626
        //
453,678✔
2627
        // Note that some valid changesets can still cause exceptions to be
453,678✔
2628
        // thrown by the merge algorithm, namely incompatible schema changes.
453,678✔
2629
        m_reciprocal_transform_cache.clear();
9,853,746✔
2630
        throw;
9,853,746✔
2631
    }
83,402✔
2632

83,402✔
2633
    // NOTE: Any exception thrown during flushing *MUST* lead to rollback of
83,402✔
2634
    // the current transaction.
83,402✔
2635
    flush_reciprocal_transform_cache(history); // Throws
83,402✔
2636

9,853,746✔
2637
    return p - parsed_changesets.begin();
453,678✔
2638
}
2639

2640

489,056✔
2641
Changeset& TransformerImpl::get_reciprocal_transform(TransformHistory& history, file_ident_type local_file_ident,
244,930✔
2642
                                                     version_type version, const HistoryEntry& history_entry)
244,930✔
2643
{
489,056✔
2644
    auto& changeset = m_reciprocal_transform_cache[version]; // Throws
489,056✔
2645
    if (changeset.empty()) {
244,930✔
2646
        bool is_compressed = false;
489,056✔
2647
        ChunkedBinaryData data = history.get_reciprocal_transform(version, is_compressed);
489,056✔
2648
        ChunkedBinaryInputStream in{data};
244,930✔
2649
        if (is_compressed) {
489,056✔
2650
            size_t total_size;
489,056✔
2651
            auto decompressed = util::compression::decompress_nonportable_input_stream(in, total_size);
489,056✔
2652
            REALM_ASSERT(decompressed);
489,056✔
2653
            sync::parse_changeset(*decompressed, changeset); // Throws
489,056✔
2654
        }
489,056✔
2655
        else {
2656
            sync::parse_changeset(in, changeset); // Throws
2657
        }
2658

2659
        changeset.version = version;
2660
        changeset.last_integrated_remote_version = history_entry.remote_version;
2661
        changeset.origin_timestamp = history_entry.origin_timestamp;
2662
        file_ident_type origin_file_ident = history_entry.origin_file_ident;
2663
        if (origin_file_ident == 0)
2664
            origin_file_ident = local_file_ident;
2665
        changeset.origin_file_ident = origin_file_ident;
2666
    }
2667
    return changeset;
2668
}
2669

2670

2671
void TransformerImpl::flush_reciprocal_transform_cache(TransformHistory& history)
2672
{
2673
    auto changesets = std::move(m_reciprocal_transform_cache);
2674
    m_reciprocal_transform_cache.clear();
2675
    ChangesetEncoder::Buffer output_buffer;
2676
    for (const auto& [version, changeset] : changesets) {
2677
        if (changeset.is_dirty()) {
2678
            encode_changeset(changeset, output_buffer); // Throws
2679
            BinaryData data{output_buffer.data(), output_buffer.size()};
2680
            history.set_reciprocal_transform(version, data); // Throws
2681
            output_buffer.clear();
2682
        }
2683
    }
2684
}
2685

2686
} // namespace _impl
2687

2688
namespace sync {
2689
std::unique_ptr<Transformer> make_transformer()
2690
{
2691
    return std::make_unique<_impl::TransformerImpl>(); // Throws
2692
}
2693

2694

2695
void parse_remote_changeset(const Transformer::RemoteChangeset& remote_changeset, Changeset& parsed_changeset)
2696
{
2697
    // origin_file_ident = 0 is currently used to indicate an entry of local
2698
    // origin.
2699
    REALM_ASSERT(remote_changeset.origin_file_ident != 0);
2700
    REALM_ASSERT(remote_changeset.remote_version != 0);
2701

2702
    ChunkedBinaryInputStream remote_in{remote_changeset.data};
2703
    parse_changeset(remote_in, parsed_changeset); // Throws
2704

2705
    parsed_changeset.version = remote_changeset.remote_version;
2706
    parsed_changeset.last_integrated_remote_version = remote_changeset.last_integrated_local_version;
2707
    parsed_changeset.origin_timestamp = remote_changeset.origin_timestamp;
2708
    parsed_changeset.origin_file_ident = remote_changeset.origin_file_ident;
2709
    parsed_changeset.original_changeset_size = remote_changeset.original_changeset_size;
2710
}
2711

2712
} // namespace sync
2713
} // namespace realm
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