Open fire opened 1 month ago
import jsondiffpatch from 'jsondiffpatch';
// Initialize the diff/patch engine
const diffPatch = jsondiffpatch.create();
// Simulate client and server documents as JSON objects
let clientDoc = {
title: "Original Title",
content: "Initial content",
comments: [{ id: 1, text: "First comment" }]
};
let serverDoc = {
title: "Original Title",
content: "Initial content",
comments: [{ id: 1, text: "First comment" }]
};
// Shadow copies on client and server
let clientShadow = JSON.parse(JSON.stringify(clientDoc));
let serverShadow = JSON.parse(JSON.stringify(serverDoc));
// Function to simulate client making an edit
function clientMakesEdit(newDoc) {
clientDoc = newDoc;
const diff = diffPatch.diff(clientShadow, clientDoc);
clientShadow = JSON.parse(JSON.stringify(clientDoc)); // Update client shadow to latest doc
return diff;
}
// Function to apply changes on the server
function applyChangesOnServer(diff) {
serverDoc = diffPatch.patch(serverDoc, diff);
serverShadow = JSON.parse(JSON.stringify(serverDoc)); // Update server shadow
return diffPatch.diff(serverShadow, serverDoc); // Diff for client update
}
// Client edits the document
const clientDiff = clientMakesEdit({
title: "Updated Title",
content: "Revised content",
comments: [{ id: 1, text: "Edited first comment" }, { id: 2, text: "Second comment" }]
});
// Server applies the changes and prepares the update for the client
const serverDiff = applyChangesOnServer(clientDiff);
// Apply server changes to client
clientDoc = diffPatch.patch(clientDoc, serverDiff);
console.log("Final Client Doc:", clientDoc);
console.log("Final Server Doc:", serverDoc);
Originally we start with a list of properties and we send the index of the properties to overwrite.
In the new design we start with a json array of properties and we generate a json diff patch.
Differential Synchronization Explained
Differential Synchronization (DS) is a method for synchronizing data across multiple devices or services in real-time. It is particularly useful in applications where multiple users interact with the same data simultaneously, such as collaborative editing tools.
Core Components of Differential Synchronization:
Workflow: