PatchPack
A binary JsonPatch serializer based on schema. Efficiently encode state object and JsonPatch in to compact byte buffers and then decode them back in to objects on the receiver. Integrates very well with observable state and WebSockets.
Originally it was part of mosx framework, but then it moved to separate package.
Motivation
I was working on an magx game server framework that used WebSockets to syncronize state between server and clients. Syncronization principle is simple: first server sends full state to clients then on every change sends patches in JsonPatch format. I have found the problem that sending a lot of patches without serialization is a waste of bandwidth.
As state's schema is known on server side it can be sent to the clients, then state and each patch can be encoded based on that schema on server side and decoded back on client side. State schema is not static that means it must be also syncronized with clients. This sophisticated approach can significantly reduce patch size and bandwidth usage.
Concept
Installation
npm install --save patchpack
Browser
A browser version of patchpack is also available:
<script src="https://cdn.jsdelivr.net/npm/patchpack@0.4.2/browser/patchpack.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/patchpack@0.4.2/browser/patchpack.js"></script>
Example
/** Server side */ // initial state // create patchpack instance and define schema types console.logencodedStateWithTypes.length// 135 console.logencodedState.length// 60 console.logJSON.stringifystate.length// 165 state.clients = client console.logencodedPatch1.length// 22 console.logJSON.stringifypatch1.length// 72 // generate patch console.logencodedPatch2.length// 5 console.logJSON.stringifypatch2.length// 47
Send encodedStateWithTypes
, encodedPatch1
and encodedPatch2
to Client and decode them:
/** Client side */ console.logdecodedState // {// clients: {// '1': { name: 'Foo', info: '' },// '2': { name: 'Baz', info: 'FooBaz' }// },// objects: [// { id: 1, name: 'Foo' },// { id: 2, name: 'Foo', foo: 'Baz' } ],// foo: { baz: false }// } console.logdecodedPatch1 // {// op: 'add',// path: '/clients/3',// value: { name: 'FooBaz', info: 'test' }// } console.logdecodedPatch2 // { op: 'replace', path: '/foo/baz', value: true }
License
MIT