Skip to content

Commit

Permalink
Handle local changes correctly when receiving snapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
hackerwins committed Jul 11, 2024
1 parent 1cd4140 commit 6466e1e
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/document/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,14 @@ export class Document<T, P extends Indexable = Indexable> {
this.localChanges.shift();
}

// NOTE(hackerwins): If the document has local changes, we need to apply
// them after applying the snapshot. We need to treat the local changes
// as remote changes because the application should apply the local
// changes to their own document.
if (pack.hasSnapshot()) {
this.applyChanges(this.localChanges, OpSource.Remote);
}

// 03. Update the checkpoint.
this.checkpoint = this.checkpoint.forward(pack.getCheckpoint());

Expand Down
25 changes: 25 additions & 0 deletions test/integration/client_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -838,4 +838,29 @@ describe.sequential('Client', function () {

vi.unstubAllGlobals();
});

it('Should handle local changes correctly when receiving snapshot', async ({
task,
}) => {
type TestDoc = { counter: Counter };
await withTwoClientsAndDocuments<TestDoc>(async (c1, d1, c2, d2) => {
d1.update((r) => (r.counter = new Counter(yorkie.IntType, 0)));
await c1.sync();
await c2.sync();

// 01. c1 increases the counter for creating snapshot.
for (let i = 0; i < 500; i++) {
d1.update((r) => r.counter.increase(1));
}
await c1.sync();

// 02. c2 receives the snapshot and increases the counter simultaneously.
c2.sync();
d2.update((r) => r.counter.increase(1));

await c2.sync();
await c1.sync();
assert.equal(d1.toSortedJSON(), d2.toSortedJSON());
}, task.name);
});
});
4 changes: 2 additions & 2 deletions test/integration/snapshot_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ describe('Snapshot', function () {
await c1.sync();
await c2.sync();

// 01. Updates 700 changes over snapshot threshold by c1.
for (let idx = 0; idx < 700; idx++) {
// 01. Updates 500 changes over snapshot threshold by c1.
for (let idx = 0; idx < 500; idx++) {
d1.update((root) => {
root.k1.edit(idx, idx, 'x');
});
Expand Down

0 comments on commit 6466e1e

Please sign in to comment.