const replayproxy = require('@createvibe/replayproxy');
function performPotentialDangerousTask(chunks) {
// create a random chunk of numbers
const chunk = [];
const len = Math.ceil(Math.random() * 10);
for (let i = 0; i < len; i++) {
chunk.push(Number(Math.random() * 10).toFixed(3));
}
// brute force merge of 10 random numbers in sorted order
chunk.sort((a,b) => (a-b));
chunks.push(chunk);
// chunks.sort((a,b) => (a-b));
// randomly throw an error
if (Math.random() * 4 > 3.5 && chunks.length > 3) {
throw new Error('I make Error!');
}
}
const data = {};
/* do something with data */
data.something = 'some value';
data.array = [6,4,1,4,2,15,26,25,18,11,14,35,25,74,21,7,6,3];
data.array.sort((a,b) => (a-b));
data.array = [data.array];
{
// wrap data with replayproxy
let proxy = replayproxy(data);
// create a breakpoint reference
let breakpoint;
// do dangerous things with data (the proxy)
try {
// do stuff continuously until we get an error
for (;;) {
// pass proxy instead of data
performPotentialDangerousTask(proxy.array);
// create a new breakpoint
breakpoint = proxy.breakpoint();
}
} catch (err) {
console.error(err);
// found an error, rollback the changes to the last breakpoint
console.log('data count before rollbak ' + data.array.length);
console.log('the data being rolled back', data.array[ data.array.length - 1 ]);
// perform rollback to last known breakpoint
proxy.rollback(breakpoint);
console.log('data count after rollback ' + data.array.length);
console.log('the last element of the array has changed', data.array[ data.array.length - 1 ]);
}
// dismiss proxy so GC can do its thing
proxy = null;
}
/* continue working with data instead of proxy */
console.log(data);