SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Efficient Client Communication with 
Differential Synchronization and JSON Patch 
By Brian Cavalier and Craig Walls 
© 2014 SpringOne 2GX. All rights reserved. Do not distribute without permission.
What’s the problem with REST?
Nothing, REST is awesome
What’s the problem with 
how we typically use REST in practice?
Agenda 
• Motivation 
• Differential Synchronization (DS) 
• JSON Patch 
• DS + JSON Patch 
• DS w/Spring and JavaScript 
• The future
What’s the problem with 
how we typically use REST in practice?
Isn’t “typical REST” good enough? 
• “Typical REST”: 1 request per entity per operation type 
• create 2 entities, update 3, delete 1 = 6 requests 
• Expensive for mobile: connection latency, battery, data ($$$) 
• Doesn’t exploit return payload
Motivation: Goals 
• More efficient data transfer 
• More efficient use of mobile radios, networks and batteries 
• Take advantage of WebSocket & messaging 
• Data synchronization with multiple clients 
• Offline / disconnected
How can we 
get data from a Spring back-end all the way to 
the pixels more efficiently?
Differential Synchronization
Differential Sync 
• Algorithm for syncing N copies of a document 
• Potentially supports any kind of document/data 
• As long as diff & patch algorithms are available 
• Text, DOM, JSON 
• Nice properties 
• Efficient: Transfer only differences 
• Symmetrical: same algorithm at each node 
• Recoverable: disconnected/offline clients, lost messages 
• Published by Neil Fraser in 2009 
• https://neil.fraser.name/writing/sync/
Differential Sync 
doc shadow doc 
diff 
diff 
patch 
patch 
live 
edits 
live 
edits
Differential Sync 
doc shadow shadow doc 
diff 
diff 
patch 
patch 
live 
edits 
live 
edits
Differential Sync 
• Cooperative synchronization loop 
• Distributed or local 
• Uses diff & patch algorithms
JSON Patch
JSON Patch 
• JSON-formatted Patch for structured documents 
• RFC 6902, plus related JSON Pointer RFC 6901 
• https://tools.ietf.org/html/rfc6902 
• https://tools.ietf.org/html/rfc6901 
• Suitable for sending via HTTP Patch 
• Defines operations, format, algorithm, and mime type 
• application/json-patch+json 
• Can coexist w/handlers at same url via Content-Type routing 
• Does not define diff algorithm 
• Sensible requirement: patch(diff(a, b), a) === b
JSON Patch 
json! 
[{"value":"a"},{"value":"b"},{"value":"c"}]! 
+ 
patch! 
[{"op":"add","path":"/3","value":{"value":"d"}},! 
{“op":"remove","path":"/1"}]! 
= 
new json! 
[{"value":"a"},{"value":"c"},{"value":"d"}]
JSON Patch 
json! 
{"name":{"first":"Brian","last":"Cavalier"},"occupation":"JavaScript 
Engineer"}! 
+ 
patch! 
[{"op":"replace","path":"/occupation","value":"JavaScript Ranger"}]! 
= 
new json! 
{"name":{"first":"Brian","last":"Cavalier"},"occupation":"JavaScript 
Ranger"}
JSON Patch 
• Moves the operation type inside request payload 
• create 2 entities, update 3, delete 1 = 1 request 
• Moves the identifier inside request payload 
• Potentially patch many entity types in a single request 
• Patches are atomic 
• If any part of a patch fails, whole patch must fail (as per RFC) 
• Think: data integrity
“Typical REST” 
POST /todos {“description”: “Try JSON Patch”, “complete”: false} 
PUT /todos/1 {“description”: “…”, “complete”: true} 
PATCH /todos/2 {“complete”: true} 
DELETE /todos/3
JSON Patch 
PATCH /todos [ 
{“op”: “add”, “path”: “-“, “value”: { “description”: “Try JSON 
Patch”, “complete”: true}}, 
{“op”: “replace”, “path”: “/1”, “value”: { “description”: “…”, 
“complete”: true}}, 
{“op”: “replace”, “path”: “/2/complete”, “value”: true}}, 
{“op”: “remove”, “path”: “/3”}} 
]
“Typical REST” 
POST /person { “name”: “Brian” } 
PUT /todos/1 { “description”: “…”, “complete”: true } 
PATCH /meetings/2 { “agenda”: “…” } 
DELETE /todos/3
Pie in the sky JSON Patch 
PATCH / [ 
{“op”: “add”, “path”: “/person/-“, “value”: { “name”: “Brian” }}, 
{“op”: “replace”, “path”: “/todos/1”, “value”: { “description”: 
“…”, “complete”: true }}, 
{“op”: “replace”, “path”: “/meetings/2/agenda”, “value”: “…” }}, 
{“op”: “remove”, “path”: “/todos/3” }} 
]
JSON Patch 
• Reduce requests 
• “Typical” REST: 
• # Requests = Entity type x Operation type 
• JSON Patch + HTTP Patch 
• # Requests = 1 
• Reduce payload size: Transfer only deltas
Demo
Introducing jiff.js 
• JavaScript library for JSON diff & patch 
• https://github.com/cujojs/jiff 
• Diffs arbitrary JSON or JavaScript object graphs 
• inc. objects containing arrays containing objects containing… 
• Patches arbitrary JSON or JavaScript object graphs atomically 
• Supports advanced features: inverse patches, rebase, contextual 
(“smart”) patching
jiff.js 
var jiff = require(‘jiff’); 
var rest = require(‘rest’); 
! 
var changedData = jiff.clone(data); 
! 
// … data changes via user interactions 
! 
var patch = jiff.diff(data, changedData); 
! 
rest({ method: ‘PATCH’, entity: patch });
Hmmmm …. 
Differential synchronization requires diff and patch algorithms 
JSON Patch defines a patch format and algorithm
Differential Sync + JSON Patch 
What if we put these two things together to synchronize 
structured data?
Differential Sync 
JSON Patch 
data 
model shadow data 
shadow model 
diff 
diff 
patch 
patch 
changes changes 
JSON Patch 
Spring Server 
Client 
(web browser, 
phone, etc.)
Demo
Differential Synchronization in Server-Side Spring
Applying JSON Patch to the Java-based Domain
Path to SpEL 
JSON Patch Path SpEL 
/0 [0] 
/complete .complete 
/1/description [1].description 
/clients/3/address/zip .clients[3].address.zip
Challenges with JSON Patch and Java 
• How do you “remove” or “move” a property? 
• How do you “move” a list item to a different index? 
• How do you “add” a list item to a specific index? 
• How do you avoid saving the entire list when patching a list? 
• How do you delete an item as the result of a “delete” op? 
• What if a “remove” is only intended for a particular view?
Introducing Spring Sync 
• GitHub: http://github.com/spring-projects/spring-sync 
• Maven/Gradle: org.springframework.sync:spring-sync:0.5.0.BUILD-SNAPSHOT 
• JsonPatch 
• Applies a JSON Patch to a Java object graph 
• DiffSync 
• Applies Differential Synchronization algorithm (leveraging JsonPatch) 
• DiffSyncController 
• Handles PATCH requests for “application/json-patch+json” 
• Returns a JSON Patch to update client 
• @EnableDifferentialSynchronization
Enabling Spring Sync 
@Configuration 
@EnableDifferentialSynchronization 
public class DiffSyncConfig extends DiffSyncConfigurerAdapter { 
! 
@Autowired 
private PagingAndSortingRepository<Todo, Long> repo; 
@Override 
public void addPersistenceCallbacks( 
PersistenceCallbackRegistry registry) { 
! 
registry.addPersistenceCallback( 
new JpaPersistenceCallback<Todo>(repo, Todo.class)); 
! 
} 
}
Differential Synchronization in JavaScript
Differential Sync in JavaScript 
DOM User 
Interface 
patch patch 
JavaScript objects, 
arrays, etc 
Network 
patch patch 
Spring Server
Differential Sync in JavaScript 
• Synchronize from the Spring data model to the pixels 
• Decouple change frequency from communication frequency: 
• fast sync = responsive, but network/resource intense 
• slow sync = slower UI updates, but less network/resource 
intense 
• Current Status 
• Incubator JavaScript implementation based on cujojs/jiff.js
When you have a system based on patches, 
you can do some interesting things
Streaming changes w/WebSocket 
42
Demo
Patch Algebra 
44
Patch Algebra 
• Inverse patches 
• think Undo & Redo with no application specific logic 
• Merge and Rebase 
• Apply parallel changes from multiple parties without locking 
• jiff.js supports inverse, rebase
Demo
Challenges 
• DS in an Entity-oriented world 
• What constitutes a document? 
• Each participant must maintain a shadow copy of the document 
• Lists and arrays are tricky 
• Conflict resolution (not a big deal in practice?) 
• Hypothesis: Conflicts no more likely to occur than REST 
• DS in itself does not solve conflict resolution, but neither does 
REST
Today 
• Spring Sync 
• http://github.com/spring-projects/spring-sync 
• org.springframework.sync:spring-sync:0.5.0.BUILD-SNAPSHOT 
• JSON Patch + diff in JavaScript 
• https://github.com/cujojs/jiff 
• Experimental Spring support for Differential Sync and JSON 
Patch over HTTP Patch 
• https://github.com/royclarkson/spring-rest-todos
The Future 
• Continue evolution of Spring Sync and JavaScript DS 
implementations 
• Further Integrate with Spring ecosystem 
• Messaging & WebSocket 
• Smart patching 
• Offline/disconnected client support 
• Guidance (when to use it, how to tune it, etc.)

Contenu connexe

Tendances

Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
Michael Girouard
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
MongoDB
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
mfrancis
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 

Tendances (20)

AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
 
MongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkMongoDB's New Aggregation framework
MongoDB's New Aggregation framework
 
The JSON REST API for WordPress
The JSON REST API for WordPressThe JSON REST API for WordPress
The JSON REST API for WordPress
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
MongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in BavariaMongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in Bavaria
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Replacing Oracle with MongoDB for a templating application at the Bavarian go...
Replacing Oracle with MongoDB for a templating application at the Bavarian go...Replacing Oracle with MongoDB for a templating application at the Bavarian go...
Replacing Oracle with MongoDB for a templating application at the Bavarian go...
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
 
Developing node-mdb: a Node.js - based clone of SimpleDB
Developing node-mdb: a Node.js - based clone of SimpleDBDeveloping node-mdb: a Node.js - based clone of SimpleDB
Developing node-mdb: a Node.js - based clone of SimpleDB
 
Develop webservice in PHP
Develop webservice in PHPDevelop webservice in PHP
Develop webservice in PHP
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...
WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...
WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsers
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 

En vedette

Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
Masoud Kalali
 

En vedette (6)

Handle complex POST/PATCH requests in RESTful API
Handle complex POST/PATCH requests in RESTful APIHandle complex POST/PATCH requests in RESTful API
Handle complex POST/PATCH requests in RESTful API
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Rest api titouan benoit
Rest api   titouan benoitRest api   titouan benoit
Rest api titouan benoit
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
 
Druid @ branch
Druid @ branch Druid @ branch
Druid @ branch
 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
 

Similaire à Differential Sync and JSON Patch @ SpringOne2GX 2014

Node.js and couchbase Full Stack JSON - Munich NoSQL
Node.js and couchbase   Full Stack JSON - Munich NoSQLNode.js and couchbase   Full Stack JSON - Munich NoSQL
Node.js and couchbase Full Stack JSON - Munich NoSQL
Philipp Fehre
 
Webdevcon Keynote hh-2012-09-18
Webdevcon Keynote hh-2012-09-18Webdevcon Keynote hh-2012-09-18
Webdevcon Keynote hh-2012-09-18
Pierre Joye
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 

Similaire à Differential Sync and JSON Patch @ SpringOne2GX 2014 (20)

Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Puppet – Make stateful apps easier than stateless
Puppet – Make stateful apps easier than statelessPuppet – Make stateful apps easier than stateless
Puppet – Make stateful apps easier than stateless
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
SQL to NoSQL: Top 6 Questions
SQL to NoSQL: Top 6 QuestionsSQL to NoSQL: Top 6 Questions
SQL to NoSQL: Top 6 Questions
 
SQL Server 2016 JSON
SQL Server 2016 JSONSQL Server 2016 JSON
SQL Server 2016 JSON
 
Node.js and couchbase Full Stack JSON - Munich NoSQL
Node.js and couchbase   Full Stack JSON - Munich NoSQLNode.js and couchbase   Full Stack JSON - Munich NoSQL
Node.js and couchbase Full Stack JSON - Munich NoSQL
 
Building Tomorrow's Web Services
Building Tomorrow's Web ServicesBuilding Tomorrow's Web Services
Building Tomorrow's Web Services
 
Webdevcon Keynote hh-2012-09-18
Webdevcon Keynote hh-2012-09-18Webdevcon Keynote hh-2012-09-18
Webdevcon Keynote hh-2012-09-18
 
Intro to CakePHP
Intro to CakePHPIntro to CakePHP
Intro to CakePHP
 
FOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBFOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDB
 
Data encoding and Metadata for Streams
Data encoding and Metadata for StreamsData encoding and Metadata for Streams
Data encoding and Metadata for Streams
 
Node.js
Node.jsNode.js
Node.js
 
Grokking TechTalk 9 - Building a realtime & offline editing service from scra...
Grokking TechTalk 9 - Building a realtime & offline editing service from scra...Grokking TechTalk 9 - Building a realtime & offline editing service from scra...
Grokking TechTalk 9 - Building a realtime & offline editing service from scra...
 
TypeScript and SharePoint Framework
TypeScript and SharePoint FrameworkTypeScript and SharePoint Framework
TypeScript and SharePoint Framework
 
REST easy with API Platform
REST easy with API PlatformREST easy with API Platform
REST easy with API Platform
 
Plone FSR
Plone FSRPlone FSR
Plone FSR
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Scalable Architectures - Microsoft Finland DevDays 2014
Scalable Architectures - Microsoft Finland DevDays 2014Scalable Architectures - Microsoft Finland DevDays 2014
Scalable Architectures - Microsoft Finland DevDays 2014
 
Grokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with CouchbaseGrokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with Couchbase
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Differential Sync and JSON Patch @ SpringOne2GX 2014

  • 1. Efficient Client Communication with Differential Synchronization and JSON Patch By Brian Cavalier and Craig Walls © 2014 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  • 2. What’s the problem with REST?
  • 4. What’s the problem with how we typically use REST in practice?
  • 5. Agenda • Motivation • Differential Synchronization (DS) • JSON Patch • DS + JSON Patch • DS w/Spring and JavaScript • The future
  • 6. What’s the problem with how we typically use REST in practice?
  • 7. Isn’t “typical REST” good enough? • “Typical REST”: 1 request per entity per operation type • create 2 entities, update 3, delete 1 = 6 requests • Expensive for mobile: connection latency, battery, data ($$$) • Doesn’t exploit return payload
  • 8. Motivation: Goals • More efficient data transfer • More efficient use of mobile radios, networks and batteries • Take advantage of WebSocket & messaging • Data synchronization with multiple clients • Offline / disconnected
  • 9. How can we get data from a Spring back-end all the way to the pixels more efficiently?
  • 11. Differential Sync • Algorithm for syncing N copies of a document • Potentially supports any kind of document/data • As long as diff & patch algorithms are available • Text, DOM, JSON • Nice properties • Efficient: Transfer only differences • Symmetrical: same algorithm at each node • Recoverable: disconnected/offline clients, lost messages • Published by Neil Fraser in 2009 • https://neil.fraser.name/writing/sync/
  • 12. Differential Sync doc shadow doc diff diff patch patch live edits live edits
  • 13. Differential Sync doc shadow shadow doc diff diff patch patch live edits live edits
  • 14. Differential Sync • Cooperative synchronization loop • Distributed or local • Uses diff & patch algorithms
  • 16. JSON Patch • JSON-formatted Patch for structured documents • RFC 6902, plus related JSON Pointer RFC 6901 • https://tools.ietf.org/html/rfc6902 • https://tools.ietf.org/html/rfc6901 • Suitable for sending via HTTP Patch • Defines operations, format, algorithm, and mime type • application/json-patch+json • Can coexist w/handlers at same url via Content-Type routing • Does not define diff algorithm • Sensible requirement: patch(diff(a, b), a) === b
  • 17. JSON Patch json! [{"value":"a"},{"value":"b"},{"value":"c"}]! + patch! [{"op":"add","path":"/3","value":{"value":"d"}},! {“op":"remove","path":"/1"}]! = new json! [{"value":"a"},{"value":"c"},{"value":"d"}]
  • 18. JSON Patch json! {"name":{"first":"Brian","last":"Cavalier"},"occupation":"JavaScript Engineer"}! + patch! [{"op":"replace","path":"/occupation","value":"JavaScript Ranger"}]! = new json! {"name":{"first":"Brian","last":"Cavalier"},"occupation":"JavaScript Ranger"}
  • 19. JSON Patch • Moves the operation type inside request payload • create 2 entities, update 3, delete 1 = 1 request • Moves the identifier inside request payload • Potentially patch many entity types in a single request • Patches are atomic • If any part of a patch fails, whole patch must fail (as per RFC) • Think: data integrity
  • 20. “Typical REST” POST /todos {“description”: “Try JSON Patch”, “complete”: false} PUT /todos/1 {“description”: “…”, “complete”: true} PATCH /todos/2 {“complete”: true} DELETE /todos/3
  • 21. JSON Patch PATCH /todos [ {“op”: “add”, “path”: “-“, “value”: { “description”: “Try JSON Patch”, “complete”: true}}, {“op”: “replace”, “path”: “/1”, “value”: { “description”: “…”, “complete”: true}}, {“op”: “replace”, “path”: “/2/complete”, “value”: true}}, {“op”: “remove”, “path”: “/3”}} ]
  • 22. “Typical REST” POST /person { “name”: “Brian” } PUT /todos/1 { “description”: “…”, “complete”: true } PATCH /meetings/2 { “agenda”: “…” } DELETE /todos/3
  • 23. Pie in the sky JSON Patch PATCH / [ {“op”: “add”, “path”: “/person/-“, “value”: { “name”: “Brian” }}, {“op”: “replace”, “path”: “/todos/1”, “value”: { “description”: “…”, “complete”: true }}, {“op”: “replace”, “path”: “/meetings/2/agenda”, “value”: “…” }}, {“op”: “remove”, “path”: “/todos/3” }} ]
  • 24. JSON Patch • Reduce requests • “Typical” REST: • # Requests = Entity type x Operation type • JSON Patch + HTTP Patch • # Requests = 1 • Reduce payload size: Transfer only deltas
  • 25. Demo
  • 26. Introducing jiff.js • JavaScript library for JSON diff & patch • https://github.com/cujojs/jiff • Diffs arbitrary JSON or JavaScript object graphs • inc. objects containing arrays containing objects containing… • Patches arbitrary JSON or JavaScript object graphs atomically • Supports advanced features: inverse patches, rebase, contextual (“smart”) patching
  • 27. jiff.js var jiff = require(‘jiff’); var rest = require(‘rest’); ! var changedData = jiff.clone(data); ! // … data changes via user interactions ! var patch = jiff.diff(data, changedData); ! rest({ method: ‘PATCH’, entity: patch });
  • 28. Hmmmm …. Differential synchronization requires diff and patch algorithms JSON Patch defines a patch format and algorithm
  • 29. Differential Sync + JSON Patch What if we put these two things together to synchronize structured data?
  • 30. Differential Sync JSON Patch data model shadow data shadow model diff diff patch patch changes changes JSON Patch Spring Server Client (web browser, phone, etc.)
  • 31. Demo
  • 32. Differential Synchronization in Server-Side Spring
  • 33. Applying JSON Patch to the Java-based Domain
  • 34. Path to SpEL JSON Patch Path SpEL /0 [0] /complete .complete /1/description [1].description /clients/3/address/zip .clients[3].address.zip
  • 35. Challenges with JSON Patch and Java • How do you “remove” or “move” a property? • How do you “move” a list item to a different index? • How do you “add” a list item to a specific index? • How do you avoid saving the entire list when patching a list? • How do you delete an item as the result of a “delete” op? • What if a “remove” is only intended for a particular view?
  • 36. Introducing Spring Sync • GitHub: http://github.com/spring-projects/spring-sync • Maven/Gradle: org.springframework.sync:spring-sync:0.5.0.BUILD-SNAPSHOT • JsonPatch • Applies a JSON Patch to a Java object graph • DiffSync • Applies Differential Synchronization algorithm (leveraging JsonPatch) • DiffSyncController • Handles PATCH requests for “application/json-patch+json” • Returns a JSON Patch to update client • @EnableDifferentialSynchronization
  • 37. Enabling Spring Sync @Configuration @EnableDifferentialSynchronization public class DiffSyncConfig extends DiffSyncConfigurerAdapter { ! @Autowired private PagingAndSortingRepository<Todo, Long> repo; @Override public void addPersistenceCallbacks( PersistenceCallbackRegistry registry) { ! registry.addPersistenceCallback( new JpaPersistenceCallback<Todo>(repo, Todo.class)); ! } }
  • 39. Differential Sync in JavaScript DOM User Interface patch patch JavaScript objects, arrays, etc Network patch patch Spring Server
  • 40. Differential Sync in JavaScript • Synchronize from the Spring data model to the pixels • Decouple change frequency from communication frequency: • fast sync = responsive, but network/resource intense • slow sync = slower UI updates, but less network/resource intense • Current Status • Incubator JavaScript implementation based on cujojs/jiff.js
  • 41. When you have a system based on patches, you can do some interesting things
  • 43. Demo
  • 45. Patch Algebra • Inverse patches • think Undo & Redo with no application specific logic • Merge and Rebase • Apply parallel changes from multiple parties without locking • jiff.js supports inverse, rebase
  • 46. Demo
  • 47. Challenges • DS in an Entity-oriented world • What constitutes a document? • Each participant must maintain a shadow copy of the document • Lists and arrays are tricky • Conflict resolution (not a big deal in practice?) • Hypothesis: Conflicts no more likely to occur than REST • DS in itself does not solve conflict resolution, but neither does REST
  • 48. Today • Spring Sync • http://github.com/spring-projects/spring-sync • org.springframework.sync:spring-sync:0.5.0.BUILD-SNAPSHOT • JSON Patch + diff in JavaScript • https://github.com/cujojs/jiff • Experimental Spring support for Differential Sync and JSON Patch over HTTP Patch • https://github.com/royclarkson/spring-rest-todos
  • 49. The Future • Continue evolution of Spring Sync and JavaScript DS implementations • Further Integrate with Spring ecosystem • Messaging & WebSocket • Smart patching • Offline/disconnected client support • Guidance (when to use it, how to tune it, etc.)