Commit 1f289bc7 authored by Tristan Cavelier's avatar Tristan Cavelier

Redesigning JIO in order to use 'success' and 'error' callbacks instead of...

Redesigning JIO in order to use 'success' and 'error' callbacks instead of 'onResponse', 'onDone' or 'onFail'.
parent 168cd8d5
/*! JIO - v0.1.0 - 2012-07-24 /*! JIO - v0.1.0 - 2012-07-31
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var jio = (function () { var jio = (function () {
var log = function(){};
// var log = console.log;
var jioException = function(spec, my) { var jioException = function(spec, my) {
var that = {}; var that = {};
...@@ -77,7 +75,6 @@ var storage = function(spec, my) { ...@@ -77,7 +75,6 @@ var storage = function(spec, my) {
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.type = spec.type || ''; priv.type = spec.type || '';
log ('new storage spec: ' + JSON.stringify (spec));
// Methods // // Methods //
that.getType = function() { that.getType = function() {
...@@ -93,12 +90,11 @@ var storage = function(spec, my) { ...@@ -93,12 +90,11 @@ var storage = function(spec, my) {
* @param {object} command The command * @param {object} command The command
*/ */
that.execute = function(command) { that.execute = function(command) {
log ('storage '+that.getType()+' execute(command): ' +
JSON.stringify (command.serialized()));
that.validate(command); that.validate(command);
that.done = command.done; that.success = command.success;
that.fail = command.fail; that.error = command.error;
that.end = command.end; that.retry = command.retry;
that.end = command.end;
command.executeOn(that); command.executeOn(that);
}; };
...@@ -150,9 +146,10 @@ var storage = function(spec, my) { ...@@ -150,9 +146,10 @@ var storage = function(spec, my) {
return ''; return '';
}; };
that.done = function() {}; that.success = function() {};
that.fail = function() {}; that.retry = function() {};
that.end = function() {}; // terminate the current job. that.error = function() {};
that.end = function() {}; // terminate the current job.
return that; return that;
}; };
...@@ -161,7 +158,6 @@ var storageHandler = function(spec, my) { ...@@ -161,7 +158,6 @@ var storageHandler = function(spec, my) {
spec = spec || {}; spec = spec || {};
my = my || {}; my = my || {};
var that = storage( spec, my ); var that = storage( spec, my );
log ('new storageHandler spec: '+JSON.stringify (spec));
that.newCommand = function (method, spec) { that.newCommand = function (method, spec) {
var o = spec || {}; var o = spec || {};
...@@ -175,10 +171,6 @@ var storageHandler = function(spec, my) { ...@@ -175,10 +171,6 @@ var storageHandler = function(spec, my) {
}; };
that.addJob = function (storage,command) { that.addJob = function (storage,command) {
log ('storageHandler ' + that.getType() +
' addJob (storage, command): ' +
JSON.stringify (storage.serialized()) + ', ' +
JSON.stringify (command.serialized()));
my.jobManager.addJob ( job({storage:storage, command:command}, my) ); my.jobManager.addJob ( job({storage:storage, command:command}, my) );
}; };
...@@ -205,17 +197,30 @@ var command = function(spec, my) { ...@@ -205,17 +197,30 @@ var command = function(spec, my) {
priv.path = spec.path || ''; priv.path = spec.path || '';
priv.tried = 0; priv.tried = 0;
priv.option = spec.option || {}; priv.option = spec.option || {};
priv.respond = priv.option.onResponse || function(){}; priv.success = priv.option.success || function (){};
priv.done = priv.option.onDone || function(){}; priv.error = priv.option.error || function (){};
priv.fail = priv.option.onFail || function(){};
priv.retry = function() { priv.retry = function() {
that.setMaxRetry(-1); that.error({status:13,statusText:'Fail Retry',
that.fail({status:0,statusText:'Fail Retry', message:'Impossible to retry.'});
message:'Impossible to retry.'});
}; };
priv.end = function() {}; priv.end = function() {};
priv.on_going = false;
// Methods // // Methods //
/**
* Returns a serialized version of this command.
* Override this function.
* @method serialized
* @return {object} The serialized command.
*/
that.serialized = function() {
return {label:that.getLabel(),
tried:priv.tried,
max_retry:priv.max_retry,
path:priv.path,
option:that.cloneOption()};
};
/** /**
* Returns the label of the command. * Returns the label of the command.
* @method getLabel * @method getLabel
...@@ -253,12 +258,13 @@ var command = function(spec, my) { ...@@ -253,12 +258,13 @@ var command = function(spec, my) {
that.validateState(); that.validateState();
}; };
that.getTried = function() { that.canBeRetried = function () {
return priv.tried; return (priv.option.max_retry === 0 ||
priv.tried < priv.option.max_retry);
}; };
that.setMaxRetry = function(max_retry) { that.getTried = function() {
priv.option.max_retry = max_retry; return priv.tried;
}; };
/** /**
...@@ -266,9 +272,12 @@ var command = function(spec, my) { ...@@ -266,9 +272,12 @@ var command = function(spec, my) {
* @param {object} handler The storage handler. * @param {object} handler The storage handler.
*/ */
that.execute = function(handler) { that.execute = function(handler) {
that.validate(handler); if (!priv.on_going) {
priv.tried ++; that.validate(handler);
handler.execute(that); priv.tried ++;
priv.on_going = true;
handler.execute(that);
}
}; };
/** /**
...@@ -289,49 +298,44 @@ var command = function(spec, my) { ...@@ -289,49 +298,44 @@ var command = function(spec, my) {
} }
}; };
that.done = function(return_value) { that.success = function(return_value) {
log ('command done: ' + JSON.stringify (return_value)); priv.on_going = false;
priv.respond({status:doneStatus(),value:return_value}); priv.success (return_value);
priv.done(return_value);
priv.end(doneStatus()); priv.end(doneStatus());
}; };
that.fail = function(return_error) { that.retry = function (return_error) {
log ('command fail: ' + JSON.stringify (return_error)); priv.on_going = false;
if (priv.option.max_retry === 0 || priv.tried < priv.option.max_retry) { if (that.canBeRetried()) {
priv.retry(); priv.retry();
} else { } else {
priv.respond({status:failStatus(),error:return_error}); that.error (return_error);
priv.fail(return_error);
priv.end(failStatus());
} }
}; };
that.end = function () { that.error = function(return_error) {
priv.end(doneStatus()); priv.on_going = false;
priv.error(return_error);
priv.end(failStatus());
}; };
that.onResponseDo = function (fun) { that.end = function () {
if (fun) { priv.end(doneStatus());
priv.respond = fun;
} else {
return priv.respond;
}
}; };
that.onDoneDo = function (fun) { that.onSuccessDo = function (fun) {
if (fun) { if (fun) {
priv.done = fun; priv.success = fun;
} else { } else {
return priv.done; return priv.success;
} }
}; };
that.onFailDo = function (fun) { that.onErrorDo = function (fun) {
if (fun) { if (fun) {
priv.fail = fun; priv.error = fun;
} else { } else {
return priv.fail; return priv.error;
} }
}; };
...@@ -343,20 +347,6 @@ var command = function(spec, my) { ...@@ -343,20 +347,6 @@ var command = function(spec, my) {
priv.retry = fun; priv.retry = fun;
}; };
/**
* Returns a serialized version of this command.
* Override this function.
* @method serialized
* @return {object} The serialized command.
*/
that.serialized = function() {
return {label:that.getLabel(),
tried:priv.tried,
max_retry:priv.max_retry,
path:priv.path,
option:that.cloneOption()};
};
/** /**
* Is the command can be restored by another JIO : yes. * Is the command can be restored by another JIO : yes.
* @method canBeRestored * @method canBeRestored
...@@ -381,12 +371,10 @@ var command = function(spec, my) { ...@@ -381,12 +371,10 @@ var command = function(spec, my) {
* @return {object} The clone of the command options. * @return {object} The clone of the command options.
*/ */
that.cloneOption = function () { that.cloneOption = function () {
// log ('command cloneOption(): ' + JSON.stringify (priv.option));
var k, o = {}; var k, o = {};
for (k in priv.option) { for (k in priv.option) {
o[k] = priv.option[k]; o[k] = priv.option[k];
} }
// log ('cloneOption result: ' + JSON.stringify (o));
return o; return o;
}; };
...@@ -411,8 +399,8 @@ var getDocumentList = function(spec, my) { ...@@ -411,8 +399,8 @@ var getDocumentList = function(spec, my) {
return false; return false;
}; };
var super_done = that.done; var super_success = that.success;
that.done = function (res) { that.success = function (res) {
var i; var i;
if (res) { if (res) {
for (i = 0; i < res.length; i+= 1) { for (i = 0; i < res.length; i+= 1) {
...@@ -426,7 +414,7 @@ var getDocumentList = function(spec, my) { ...@@ -426,7 +414,7 @@ var getDocumentList = function(spec, my) {
} }
} }
} }
super_done(res); super_success(res);
}; };
return that; return that;
...@@ -450,8 +438,8 @@ var loadDocument = function(spec, my) { ...@@ -450,8 +438,8 @@ var loadDocument = function(spec, my) {
return false; return false;
}; };
var super_done = that.done; var super_success = that.success;
that.done = function (res) { that.success = function (res) {
if (res) { if (res) {
if (typeof res.last_modified !== 'number') { if (typeof res.last_modified !== 'number') {
res.last_modified=new Date(res.last_modified).getTime(); res.last_modified=new Date(res.last_modified).getTime();
...@@ -460,7 +448,7 @@ var loadDocument = function(spec, my) { ...@@ -460,7 +448,7 @@ var loadDocument = function(spec, my) {
res.creation_date=new Date(res.creation_date).getTime(); res.creation_date=new Date(res.creation_date).getTime();
} }
} }
super_done(res); super_success(res);
}; };
return that; return that;
}; };
...@@ -636,7 +624,7 @@ var waitStatus = function(spec, my) { ...@@ -636,7 +624,7 @@ var waitStatus = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.job_id_a = spec.job_id_array || []; priv.job_id_array = spec.job_id_array || [];
priv.threshold = 0; priv.threshold = 0;
// Methods // // Methods //
...@@ -654,13 +642,13 @@ var waitStatus = function(spec, my) { ...@@ -654,13 +642,13 @@ var waitStatus = function(spec, my) {
* @method refreshJobIdArray * @method refreshJobIdArray
*/ */
priv.refreshJobIdArray = function() { priv.refreshJobIdArray = function() {
var tmp_job_id_a = [], i; var tmp_job_id_array = [], i;
for (i = 0; i < priv.job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_array.length; i+= 1) {
if (my.jobManager.jobIdExists(priv.job_id_a[i])) { if (my.jobManager.jobIdExists(priv.job_id_array[i])) {
tmp_job_id_a.push(priv.job_id_a[i]); tmp_job_id_array.push(priv.job_id_array[i]);
} }
} }
priv.job_id_a = tmp_job_id_a; priv.job_id_array = tmp_job_id_array;
}; };
/** /**
...@@ -670,12 +658,12 @@ var waitStatus = function(spec, my) { ...@@ -670,12 +658,12 @@ var waitStatus = function(spec, my) {
*/ */
that.waitForJob = function(job) { that.waitForJob = function(job) {
var i; var i;
for (i = 0; i < priv.job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_array.length; i+= 1) {
if (priv.job_id_a[i] === job.getId()) { if (priv.job_id_array[i] === job.getId()) {
return; return;
} }
} }
priv.job_id_a.push(job.getId()); priv.job_id_array.push(job.getId());
}; };
/** /**
...@@ -684,13 +672,13 @@ var waitStatus = function(spec, my) { ...@@ -684,13 +672,13 @@ var waitStatus = function(spec, my) {
* @param {object} job The job to stop waiting for. * @param {object} job The job to stop waiting for.
*/ */
that.dontWaitForJob = function(job) { that.dontWaitForJob = function(job) {
var i, tmp_job_id_a = []; var i, tmp_job_id_array = [];
for (i = 0; i < priv.job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_array.length; i+= 1) {
if (priv.job_id_a[i] !== job.getId()){ if (priv.job_id_array[i] !== job.getId()){
tmp_job_id_a.push(priv.job_id_a[i]); tmp_job_id_array.push(priv.job_id_array[i]);
} }
} }
priv.job_id_a = tmp_job_id_a; priv.job_id_array = tmp_job_id_array;
}; };
/** /**
...@@ -712,7 +700,7 @@ var waitStatus = function(spec, my) { ...@@ -712,7 +700,7 @@ var waitStatus = function(spec, my) {
that.canStart = function() { that.canStart = function() {
priv.refreshJobIdArray(); priv.refreshJobIdArray();
return (priv.job_id_a.length === 0 && Date.now() >= priv.threshold); return (priv.job_id_array.length === 0 && Date.now() >= priv.threshold);
}; };
that.canRestart = function() { that.canRestart = function() {
return that.canStart(); return that.canStart();
...@@ -721,7 +709,7 @@ var waitStatus = function(spec, my) { ...@@ -721,7 +709,7 @@ var waitStatus = function(spec, my) {
that.serialized = function() { that.serialized = function() {
return {label:that.getLabel(), return {label:that.getLabel(),
waitfortime:priv.threshold, waitfortime:priv.threshold,
waitforjob:priv.job_id_a}; waitforjob:priv.job_id_array};
}; };
/** /**
...@@ -747,8 +735,6 @@ var job = function(spec, my) { ...@@ -747,8 +735,6 @@ var job = function(spec, my) {
priv.storage = spec.storage; priv.storage = spec.storage;
priv.status = initialStatus(); priv.status = initialStatus();
priv.date = new Date(); priv.date = new Date();
log ('new job spec: ' + JSON.stringify (spec) + ', priv: ' +
JSON.stringify (priv));
// Initialize // // Initialize //
if (!priv.storage){ if (!priv.storage){
...@@ -789,7 +775,7 @@ var job = function(spec, my) { ...@@ -789,7 +775,7 @@ var job = function(spec, my) {
* @return {boolean} true if ready, else false. * @return {boolean} true if ready, else false.
*/ */
that.isReady = function() { that.isReady = function() {
if (priv.tried === 0) { if (that.getCommand().getTried() === 0) {
return priv.status.canStart(); return priv.status.canStart();
} else { } else {
return priv.status.canRestart(); return priv.status.canRestart();
...@@ -815,7 +801,6 @@ var job = function(spec, my) { ...@@ -815,7 +801,6 @@ var job = function(spec, my) {
* @param {object} job The job to wait for. * @param {object} job The job to wait for.
*/ */
that.waitForJob = function(job) { that.waitForJob = function(job) {
log ('job waitForJob(job): ' + JSON.stringify (job.serialized()));
if (priv.status.getLabel() !== 'wait') { if (priv.status.getLabel() !== 'wait') {
priv.status = waitStatus({},my); priv.status = waitStatus({},my);
} }
...@@ -839,7 +824,6 @@ var job = function(spec, my) { ...@@ -839,7 +824,6 @@ var job = function(spec, my) {
* @param {number} ms Time to wait in millisecond. * @param {number} ms Time to wait in millisecond.
*/ */
that.waitForTime = function(ms) { that.waitForTime = function(ms) {
log ('job waitForTime(ms): ' + ms);
if (priv.status.getLabel() !== 'wait') { if (priv.status.getLabel() !== 'wait') {
priv.status = waitStatus({},my); priv.status = waitStatus({},my);
} }
...@@ -857,21 +841,18 @@ var job = function(spec, my) { ...@@ -857,21 +841,18 @@ var job = function(spec, my) {
}; };
that.eliminated = function () { that.eliminated = function () {
priv.command.setMaxRetry(-1); priv.command.error ({
log ('job eliminated(): '+JSON.stringify (that.serialized())); status:10,statusText:'Stoped',
priv.command.fail({status:0,statusText:'Stoped', message:'This job has been stoped by another one.'});
message:'This job has been stoped by another one.'});
}; };
that.notAccepted = function () { that.notAccepted = function () {
log ('job notAccepted(): '+JSON.stringify (that.serialized()));
priv.command.setMaxRetry(-1);
priv.command.onEndDo (function () { priv.command.onEndDo (function () {
priv.status = failStatus(); priv.status = failStatus();
my.jobManager.terminateJob (that); my.jobManager.terminateJob (that);
}); });
priv.command.fail ({status:0,statusText:'Not Accepted', priv.command.error ({status:11,statusText:'Not Accepted',
message:'This job is already running.'}); message:'This job is already running.'});
}; };
/** /**
...@@ -880,30 +861,24 @@ var job = function(spec, my) { ...@@ -880,30 +861,24 @@ var job = function(spec, my) {
* @param {object} job The other job. * @param {object} job The other job.
*/ */
that.update = function(job) { that.update = function(job) {
log ('job update(job): ' + JSON.stringify (job.serialized())); priv.command.error ({status:12,statusText:'Replaced',
priv.command.setMaxRetry(-1); message:'Job has been replaced by another one.'});
priv.command.onEndDo(function (status) {
log ('job update on end' + status.getLabel());
});
priv.command.fail({status:0,statusText:'Replaced',
message:'Job has been replaced by another one.'});
priv.date = job.getDate(); priv.date = job.getDate();
priv.command = job.getCommand(); priv.command = job.getCommand();
priv.status = job.getStatus(); priv.status = job.getStatus();
}; };
that.execute = function() { that.execute = function() {
log ('job execute(): ' + JSON.stringify (that.serialized())); if (!that.getCommand().canBeRetried()) {
if (priv.max_retry !== 0 && priv.tried >= priv.max_retry) {
throw tooMuchTriesJobException( throw tooMuchTriesJobException(
{job:that,message:'The job was invoked too much time.'}); {job:that,message:'The job was invoked too much time.'});
} }
if (!that.isReady()) { if (!that.isReady()) {
throw jobNotReadyException({message:'Can not execute this job.'}); throw jobNotReadyException(
{job:that,message:'Can not execute this job.'});
} }
priv.status = onGoingStatus(); priv.status = onGoingStatus();
priv.command.onRetryDo (function() { priv.command.onRetryDo (function() {
log ('command.retry job:' + JSON.stringify (that.serialized()));
var ms = priv.command.getTried(); var ms = priv.command.getTried();
ms = ms*ms*200; ms = ms*ms*200;
if (ms>10000){ if (ms>10000){
...@@ -913,7 +888,6 @@ var job = function(spec, my) { ...@@ -913,7 +888,6 @@ var job = function(spec, my) {
}); });
priv.command.onEndDo (function(status) { priv.command.onEndDo (function(status) {
priv.status = status; priv.status = status;
log ('command.end job:' + JSON.stringify (that.serialized()));
my.jobManager.terminateJob (that); my.jobManager.terminateJob (that);
}); });
priv.command.execute (priv.storage); priv.command.execute (priv.storage);
...@@ -1218,7 +1192,7 @@ var jobManager = (function(spec, my) { ...@@ -1218,7 +1192,7 @@ var jobManager = (function(spec, my) {
priv.restoreOldJioId = function(id) { priv.restoreOldJioId = function(id) {
var jio_date; var jio_date;
jio_date = LocalOrCookieStorage.getItem('jio/id/'+id)||0; jio_date = LocalOrCookieStorage.getItem('jio/id/'+id)||0;
if (jio_date < Date.now() - 10000) { if (jio_date < (Date.now() - 10000)) { // 10 sec
priv.restoreOldJobFromJioId(id); priv.restoreOldJobFromJioId(id);
priv.removeOldJioId(id); priv.removeOldJioId(id);
priv.removeJobArrayFromJioId(id); priv.removeJobArrayFromJioId(id);
...@@ -1249,14 +1223,14 @@ var jobManager = (function(spec, my) { ...@@ -1249,14 +1223,14 @@ var jobManager = (function(spec, my) {
* @param {number} id The jio id. * @param {number} id The jio id.
*/ */
priv.removeOldJioId = function(id) { priv.removeOldJioId = function(id) {
var i, jio_id_a, new_a = []; var i, jio_id_array, new_array = [];
jio_id_a = LocalOrCookieStorage.getItem('jio/id_array')||[]; jio_id_array = LocalOrCookieStorage.getItem('jio/id_array')||[];
for (i = 0; i < jio_id_a.length; i+= 1) { for (i = 0; i < jio_id_array.length; i+= 1) {
if (jio_id_a[i] !== id) { if (jio_id_array[i] !== id) {
new_a.push(jio_id_a[i]); new_array.push(jio_id_array[i]);
} }
} }
LocalOrCookieStorage.setItem('jio/id_array',new_a); LocalOrCookieStorage.setItem('jio/id_array',new_array);
LocalOrCookieStorage.deleteItem('jio/id/'+id); LocalOrCookieStorage.deleteItem('jio/id/'+id);
}; };
...@@ -1401,14 +1375,6 @@ var jobRules = (function(spec, my) { ...@@ -1401,14 +1375,6 @@ var jobRules = (function(spec, my) {
that.none = function() { return 'none'; }; that.none = function() { return 'none'; };
that.default_action = that.none; that.default_action = that.none;
that.default_compare = function(job1,job2) { that.default_compare = function(job1,job2) {
if (job1.getCommand().getPath() === job2.getCommand().getPath() &&
JSON.stringify(job1.getStorage().serialized()) ===
JSON.stringify(job2.getStorage().serialized())) {
log ('same ! ' + job1.getCommand().getPath() + ', ' +
job2.getCommand().getPath() + ', ' +
JSON.stringify (job1.getStorage().serialized())+', '+
JSON.stringify (job2.getStorage().serialized()));
}
return (job1.getCommand().getPath() === job2.getCommand().getPath() && return (job1.getCommand().getPath() === job2.getCommand().getPath() &&
JSON.stringify(job1.getStorage().serialized()) === JSON.stringify(job1.getStorage().serialized()) ===
JSON.stringify(job2.getStorage().serialized())); JSON.stringify(job2.getStorage().serialized()));
...@@ -1670,18 +1636,16 @@ var jobRules = (function(spec, my) { ...@@ -1670,18 +1636,16 @@ var jobRules = (function(spec, my) {
* @param {string} path The document path name. * @param {string} path The document path name.
* @param {string} content The document's content. * @param {string} content The document's content.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
* you want to save this document elsewhere. * you want to save this document elsewhere.
*/ */
that.saveDocument = function(path, content, option, specificstorage) { that.saveDocument = function(path, content, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
jobManager.addJob( jobManager.addJob(
job({storage:(specificstorage? job({storage:(specificstorage?
...@@ -1696,9 +1660,8 @@ var jobRules = (function(spec, my) { ...@@ -1696,9 +1660,8 @@ var jobRules = (function(spec, my) {
* @method loadDocument * @method loadDocument
* @param {string} path The document path name. * @param {string} path The document path name.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* - {boolean} metadata_only Load only document metadata. * - {boolean} metadata_only Load only document metadata.
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
...@@ -1706,9 +1669,8 @@ var jobRules = (function(spec, my) { ...@@ -1706,9 +1669,8 @@ var jobRules = (function(spec, my) {
*/ */
that.loadDocument = function(path, option, specificstorage) { that.loadDocument = function(path, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
option.metadata_only = (option.metadata_only !== undefined? option.metadata_only = (option.metadata_only !== undefined?
option.metadata_only:false); option.metadata_only:false);
...@@ -1725,18 +1687,16 @@ var jobRules = (function(spec, my) { ...@@ -1725,18 +1687,16 @@ var jobRules = (function(spec, my) {
* @method removeDocument * @method removeDocument
* @param {string} path The document path name. * @param {string} path The document path name.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
* you want to save this document elsewhere. * you want to save this document elsewhere.
*/ */
that.removeDocument = function(path, option, specificstorage) { that.removeDocument = function(path, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
jobManager.addJob( jobManager.addJob(
job({storage:(specificstorage? job({storage:(specificstorage?
...@@ -1751,9 +1711,8 @@ var jobRules = (function(spec, my) { ...@@ -1751,9 +1711,8 @@ var jobRules = (function(spec, my) {
* @method getDocumentList * @method getDocumentList
* @param {string} path The folder path. * @param {string} path The folder path.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* - {boolean} metadata_only Load only document metadata * - {boolean} metadata_only Load only document metadata
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
...@@ -1761,9 +1720,8 @@ var jobRules = (function(spec, my) { ...@@ -1761,9 +1720,8 @@ var jobRules = (function(spec, my) {
*/ */
that.getDocumentList = function(path, option, specificstorage) { that.getDocumentList = function(path, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
option.metadata_only = (option.metadata_only !== undefined? option.metadata_only = (option.metadata_only !== undefined?
option.metadata_only:true); option.metadata_only:true);
......
/*! JIO - v0.1.0 - 2012-07-24 /*! JIO - v0.1.0 - 2012-07-31
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var jio=function(){var a=function(){},b=function(a,b){var c={};return a=a||{},b=b||{},c.name="jioException",c.message=a.message||"Unknown Reason.",c.toString=function(){return c.name+": "+c.message},c},c=function(a,c){var d=b(a,c);a=a||{};var e=a.command;return d.name="invalidCommandState",d.toString=function(){return d.name+": "+e.getLabel()+", "+d.message},d},d=function(a,c){var d=b(a,c);a=a||{};var e=a.storage.getType();return d.name="invalidStorage",d.toString=function(){return d.name+": "+'Type "'+e+'", '+d.message},d},e=function(a,c){var d=b(a,c),e=a.type;return d.name="invalidStorageType",d.toString=function(){return d.name+": "+e+", "+d.message},d},f=function(a,c){var d=b(a,c);return d.name="jobNotReadyException",d},g=function(a,c){var d=b(a,c);return d.name="tooMuchTriesJobException",d},h=function(a,c){var d=b(a,c);return d.name="invalidJobException",d},i=function(b,c){var e={};b=b||{},c=c||{};var f={};return f.type=b.type||"",a("new storage spec: "+JSON.stringify(b)),e.getType=function(){return f.type},e.setType=function(a){f.type=a},e.execute=function(b){a("storage "+e.getType()+" execute(command): "+JSON.stringify(b.serialized())),e.validate(b),e.done=b.done,e.fail=b.fail,e.end=b.end,b.executeOn(e)},e.isValid=function(){return!0},e.validate=function(a){var b=e.validateState();if(b)throw d({storage:e,message:b});a.validate(e)},e.serialized=function(){return{type:e.getType()}},e.saveDocument=function(a){throw d({storage:e,message:"Unknown storage."})},e.loadDocument=function(a){e.saveDocument()},e.removeDocument=function(a){e.saveDocument()},e.getDocumentList=function(a){e.saveDocument()},e.validateState=function(){return""},e.done=function(){},e.fail=function(){},e.end=function(){},e},j=function(b,c){b=b||{},c=c||{};var d=i(b,c);return a("new storageHandler spec: "+JSON.stringify(b)),d.newCommand=function(a,b){var d=b||{};return d.label=a,k(d,c)},d.newStorage=function(a){var b=a||{};return y.storage(b,c)},d.addJob=function(b,e){a("storageHandler "+d.getType()+" addJob (storage, command): "+JSON.stringify(b.serialized())+", "+JSON.stringify(e.serialized())),c.jobManager.addJob(v({storage:b,command:e},c))},d},k=function(b,d){var e={};b=b||{},d=d||{};var f={};return f.commandlist={saveDocument:o,loadDocument:m,removeDocument:n,getDocumentList:l},b.label&&f.commandlist[b.label]?(f.label=b.label,delete b.label,f.commandlist[f.label](b,d)):(f.path=b.path||"",f.tried=0,f.option=b.option||{},f.respond=f.option.onResponse||function(){},f.done=f.option.onDone||function(){},f.fail=f.option.onFail||function(){},f.retry=function(){e.setMaxRetry(-1),e.fail({status:0,statusText:"Fail Retry",message:"Impossible to retry."})},f.end=function(){},e.getLabel=function(){return"command"},e.getPath=function(){return f.path},e.getOption=function(a){return f.option[a]},e.validate=function(a){e.validateState()},e.getTried=function(){return f.tried},e.setMaxRetry=function(a){f.option.max_retry=a},e.execute=function(a){e.validate(a),f.tried++,a.execute(e)},e.executeOn=function(a){},e.validateState=function(){if(f.path==="")throw c({command:e,message:"Path is empty"})},e.done=function(b){a("command done: "+JSON.stringify(b)),f.respond({status:q(),value:b}),f.done(b),f.end(q())},e.fail=function(b){a("command fail: "+JSON.stringify(b)),f.option.max_retry===0||f.tried<f.option.max_retry?f.retry():(f.respond({status:r(),error:b}),f.fail(b),f.end(r()))},e.end=function(){f.end(q())},e.onResponseDo=function(a){if(a)f.respond=a;else return f.respond},e.onDoneDo=function(a){if(a)f.done=a;else return f.done},e.onFailDo=function(a){if(a)f.fail=a;else return f.fail},e.onEndDo=function(a){f.end=a},e.onRetryDo=function(a){f.retry=a},e.serialized=function(){return{label:e.getLabel(),tried:f.tried,max_retry:f.max_retry,path:f.path,option:e.cloneOption()}},e.canBeRestored=function(){return!0},e.clone=function(){return k(e.serialized(),d)},e.cloneOption=function(){var a,b={};for(a in f.option)b[a]=f.option[a];return b},e)},l=function(a,b){var c=k(a,b);a=a||{},b=b||{},c.getLabel=function(){return"getDocumentList"},c.executeOn=function(a){a.getDocumentList(c)},c.canBeRestored=function(){return!1};var d=c.done;return c.done=function(a){var b;if(a)for(b=0;b<a.length;b+=1)typeof a[b].last_modified!="number"&&(a[b].last_modified=(new Date(a[b].last_modified)).getTime()),typeof a[b].creation_date!="number"&&(a[b].creation_date=(new Date(a[b].creation_date)).getTime());d(a)},c},m=function(a,b){var c=k(a,b);a=a||{},b=b||{},c.getLabel=function(){return"loadDocument"},c.executeOn=function(a){a.loadDocument(c)},c.canBeRestored=function(){return!1};var d=c.done;return c.done=function(a){a&&(typeof a.last_modified!="number"&&(a.last_modified=(new Date(a.last_modified)).getTime()),typeof a.creation_date!="number"&&(a.creation_date=(new Date(a.creation_date)).getTime())),d(a)},c},n=function(a,b){var c=k(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"removeDocument"},c.executeOn=function(a){a.removeDocument(c)},c},o=function(a,b){var d=k(a,b);a=a||{},b=b||{};var e={};e.content=a.content,d.getLabel=function(){return"saveDocument"},d.getContent=function(){return e.content};var f=d.validate;d.validate=function(a){if(typeof e.content!="string")throw c({command:d,message:"No data to save"});f(a)},d.executeOn=function(a){a.saveDocument(d)};var g=d.serialized;return d.serialized=function(){var a=g();return a.content=e.content,a},d},p=function(a,b){var c={};return a=a||{},b=b||{},c.getLabel=function(){return"job status"},c.canStart=function(){},c.canRestart=function(){},c.serialized=function(){return{label:c.getLabel()}},c.isWaitStatus=function(){return!1},c.isDone=function(){return!1},c},q=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"done"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c.isDone=function(){return!0},c},r=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"fail"},c.canStart=function(){return!1},c.canRestart=function(){return!0},c},s=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"initial"},c.canStart=function(){return!0},c.canRestart=function(){return!0},c},t=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"on going"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},u=function(a,b){var c=p(a,b);a=a||{},b=b||{};var d={};return d.job_id_a=a.job_id_array||[],d.threshold=0,c.getLabel=function(){return"wait"},d.refreshJobIdArray=function(){var a=[],c;for(c=0;c<d.job_id_a.length;c+=1)b.jobManager.jobIdExists(d.job_id_a[c])&&a.push(d.job_id_a[c]);d.job_id_a=a},c.waitForJob=function(a){var b;for(b=0;b<d.job_id_a.length;b+=1)if(d.job_id_a[b]===a.getId())return;d.job_id_a.push(a.getId())},c.dontWaitForJob=function(a){var b,c=[];for(b=0;b<d.job_id_a.length;b+=1)d.job_id_a[b]!==a.getId()&&c.push(d.job_id_a[b]);d.job_id_a=c},c.waitForTime=function(a){d.threshold=Date.now()+a},c.stopWaitForTime=function(){d.threshold=0},c.canStart=function(){return d.refreshJobIdArray(),d.job_id_a.length===0&&Date.now()>=d.threshold},c.canRestart=function(){return c.canStart()},c.serialized=function(){return{label:c.getLabel(),waitfortime:d.threshold,waitforjob:d.job_id_a}},c.isWaitStatus=function(){return!0},c},v=function(b,c){var d={};b=b||{},c=c||{};var e={};e.id=c.jobIdHandler.nextId(),e.command=b.command,e.storage=b.storage,e.status=s(),e.date=new Date,a("new job spec: "+JSON.stringify(b)+", priv: "+JSON.stringify(e));if(!e.storage)throw h({job:d,message:"No storage set"});if(!e.command)throw h({job:d,message:"No command set"});return d.getCommand=function(){return e.command},d.getStatus=function(){return e.status},d.getId=function(){return e.id},d.getStorage=function(){return e.storage},d.getDate=function(){return e.date},d.isReady=function(){return e.tried===0?e.status.canStart():e.status.canRestart()},d.serialized=function(){return{id:e.id,date:e.date.getTime(),status:e.status.serialized(),command:e.command.serialized(),storage:e.storage.serialized()}},d.waitForJob=function(b){a("job waitForJob(job): "+JSON.stringify(b.serialized())),e.status.getLabel()!=="wait"&&(e.status=u({},c)),e.status.waitForJob(b)},d.dontWaitFor=function(a){e.status.getLabel()==="wait"&&e.status.dontWaitForJob(a)},d.waitForTime=function(b){a("job waitForTime(ms): "+b),e.status.getLabel()!=="wait"&&(e.status=u({},c)),e.status.waitForTime(b)},d.stopWaitForTime=function(){e.status.getLabel()==="wait"&&e.status.stopWaitForTime()},d.eliminated=function(){e.command.setMaxRetry(-1),a("job eliminated(): "+JSON.stringify(d.serialized())),e.command.fail({status:0,statusText:"Stoped",message:"This job has been stoped by another one."})},d.notAccepted=function(){a("job notAccepted(): "+JSON.stringify(d.serialized())),e.command.setMaxRetry(-1),e.command.onEndDo(function(){e.status=r(),c.jobManager.terminateJob(d)}),e.command.fail({status:0,statusText:"Not Accepted",message:"This job is already running."})},d.update=function(b){a("job update(job): "+JSON.stringify(b.serialized())),e.command.setMaxRetry(-1),e.command.onEndDo(function(b){a("job update on end"+b.getLabel())}),e.command.fail({status:0,statusText:"Replaced",message:"Job has been replaced by another one."}),e.date=b.getDate(),e.command=b.getCommand(),e.status=b.getStatus()},d.execute=function(){a("job execute(): "+JSON.stringify(d.serialized()));if(e.max_retry!==0&&e.tried>=e.max_retry)throw g({job:d,message:"The job was invoked too much time."});if(!d.isReady())throw f({message:"Can not execute this job."});e.status=t(),e.command.onRetryDo(function(){a("command.retry job:"+JSON.stringify(d.serialized()));var b=e.command.getTried();b=b*b*200,b>1e4&&(b=1e4),d.waitForTime(b)}),e.command.onEndDo(function(b){e.status=b,a("command.end job:"+JSON.stringify(d.serialized())),c.jobManager.terminateJob(d)}),e.command.execute(e.storage)},d},w=function(a,b){var c={};a=a||{},b=b||{};var d=[],e=a.name||"",f=a.announcer||{};return c.add=function(a){d.push(a)},c.remove=function(a){var b,c=[];for(b=0;b<d.length;b+=1)d[b]!==a&&c.push(d[b]);d=c},c.register=function(){f.register(c)},c.unregister=function(){f.unregister(c)},c.trigger=function(a){var b;for(b=0;b<d.length;b++)d[b].apply(null,a)},c},x=function(b,c){var d=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.id=a.id||0,d.interval=400,d.interval_id=null,d.touch=function(){LocalOrCookieStorage.setItem("jio/id/"+d.id,Date.now())},c.setId=function(a){d.id=a},c.setIntervalDelay=function(a){d.interval=a},c.getIntervalDelay=function(){return d.interval},c.start=function(){d.interval_id||(d.touch(),d.interval_id=setInterval(function(){d.touch()},d.interval))},c.stop=function(){d.interval_id!==null&&(clearInterval(d.interval_id),d.interval_id=null)},c}(),e=function(a,b){var c={};a=a||{},b=b||{};var d={};return c.register=function(a){d[a]||(d[a]=w())},c.unregister=function(a){d[a]&&delete d[a]},c.at=function(a){return d[a]},c.on=function(a,b){c.register(a),c.at(a).add(b)},c.trigger=function(a,b){c.at(a).trigger(b)},c}(),f=function(a,b){var c={};a=a||{},b=b||{};var d=0;return c.nextId=function(){return d=d+1,d},c}(),g=function(a,b){var c={};a=a||{},b=b||{};var d="jio/job_array",e={};return e.id=a.id,e.interval_id=null,e.interval=200,e.job_array=[],b.jobManager=c,b.jobIdHandler=f,e.getJobArrayName=function(){return d+"/"+e.id},e.getJobArray=function(){return LocalOrCookieStorage.getItem(e.getJobArrayName())||[]},e.copyJobArrayToLocal=function(){var a=[],b;for(b=0;b<e.job_array.length;b+=1)a.push(e.job_array[b].serialized());LocalOrCookieStorage.setItem(e.getJobArrayName(),a)},e.removeJob=function(a){var b,c=[];for(b=0;b<e.job_array.length;b+=1)e.job_array[b]!==a&&c.push(e.job_array[b]);e.job_array=c,e.copyJobArrayToLocal()},c.setId=function(a){e.id=a},c.start=function(){var a;e.interval_id===null&&(e.interval_id=setInterval(function(){e.restoreOldJio();for(a=0;a<e.job_array.length;a+=1)c.execute(e.job_array[a])},e.interval))},c.stop=function(){e.interval_id!==null&&(clearInterval(e.interval_id),e.interval_id=null,e.job_array.length===0&&LocalOrCookieStorage.deleteItem(e.getJobArrayName()))},e.restoreOldJio=function(){var a,b;e.lastrestore=e.lastrestore||0;if(e.lastrestore>Date.now()-2e3)return;b=LocalOrCookieStorage.getItem("jio/id_array")||[];for(a=0;a<b.length;a+=1)e.restoreOldJioId(b[a]);e.lastrestore=Date.now()},e.restoreOldJioId=function(a){var b;b=LocalOrCookieStorage.getItem("jio/id/"+a)||0,b<Date.now()-1e4&&(e.restoreOldJobFromJioId(a),e.removeOldJioId(a),e.removeJobArrayFromJioId(a))},e.restoreOldJobFromJioId=function(a){var d,e;e=LocalOrCookieStorage.getItem("jio/job_array/"+a)||[];for(d=0;d<e.length;d+=1){var f=k(e[d].command,b);f.canBeRestored()&&c.addJob(v({storage:y.storage(e[d].storage,b),command:f},b))}},e.removeOldJioId=function(a){var b,c,d=[];c=LocalOrCookieStorage.getItem("jio/id_array")||[];for(b=0;b<c.length;b+=1)c[b]!==a&&d.push(c[b]);LocalOrCookieStorage.setItem("jio/id_array",d),LocalOrCookieStorage.deleteItem("jio/id/"+a)},e.removeJobArrayFromJioId=function(a){LocalOrCookieStorage.deleteItem("jio/job_array/"+a)},c.execute=function(a){try{a.execute()}catch(b){switch(b.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw b}}e.copyJobArrayToLocal()},c.jobIdExists=function(a){var b;for(b=0;b<e.job_array.length;b+=1)if(e.job_array[b].getId()===a)return!0;return!1},c.terminateJob=function(a){e.removeJob(a)},c.addJob=function(a){var b=c.validateJobAccordingToJobList(e.job_array,a);e.appendJob(a,b)},c.validateJobAccordingToJobList=function(a,b){var c,d=[];for(c=0;c<a.length;c+=1)d.push(h.validateJobAccordingToJob(a[c],b));return d},e.appendJob=function(a,b){var c;if(e.job_array.length!==b.length)throw new RangeError("Array out of bound");for(c=0;c<b.length;c+=1)if(b[c].action==="dont accept")return a.notAccepted();for(c=0;c<b.length;c+=1)switch(b[c].action){case"eliminate":b[c].job.eliminated(),e.removeJob(b[c].job);break;case"update":b[c].job.update(a),e.copyJobArrayToLocal();return;case"wait":a.waitForJob(b[c].job);break;default:}e.job_array.push(a),e.copyJobArrayToLocal()},c.serialized=function(){var a=[],b,c=e.job_array||[];for(b=0;b<c.length;b+=1)a.push(c[b].serialized());return a},c}(),h=function(b,c){var d={},e={};return e.compare={},e.action={},d.eliminate=function(){return"eliminate"},d.update=function(){return"update"},d.dontAccept=function(){return"dont accept"},d.wait=function(){return"wait"},d.none=function(){return"none"},d.default_action=d.none,d.default_compare=function(b,c){return b.getCommand().getPath()===c.getCommand().getPath()&&JSON.stringify(b.getStorage().serialized())===JSON.stringify(c.getStorage().serialized())&&a("same ! "+b.getCommand().getPath()+", "+c.getCommand().getPath()+", "+JSON.stringify(b.getStorage().serialized())+", "+JSON.stringify(c.getStorage().serialized())),b.getCommand().getPath()===c.getCommand().getPath()&&JSON.stringify(b.getStorage().serialized())===JSON.stringify(c.getStorage().serialized())},e.getAction=function(a,b){var c,f,g;return c=a.getCommand().getLabel(),f=b.getCommand().getLabel(),g=a.getStatus().getLabel()==="on going"?"on going":"not on going",e.action[c]&&e.action[c][g]&&e.action[c][g][f]?e.action[c][g][f](a,b):d.default_action(a,b)},e.canCompare=function(a,b){var c=a.getCommand().getLabel(),f=b.getCommand().getLabel();return e.compare[c]&&e.compare[f]?e.compare[c][f](a,b):d.default_compare(a,b)},d.validateJobAccordingToJob=function(a,b){return e.canCompare(a,b)?{action:e.getAction(a,b),job:a}:{action:d.default_action(a,b),job:a}},d.addActionRule=function(a,b,c,d){var f=b?"on going":"not on going";e.action[a]=e.action[a]||{},e.action[a][f]=e.action[a][f]||{},e.action[a][f][c]=d},d.addCompareRule=function(a,b,c){e.compare[a]=e.compare[a]||{},e.compare[a][b]=c},d.addActionRule("saveDocument",!0,"saveDocument",function(a,b){return a.getCommand().getContent()===b.getCommand().getContent()?d.dontAccept():d.wait()}),d.addActionRule("saveDocument",!0,"loadDocument",d.wait),d.addActionRule("saveDocument",!0,"removeDocument",d.wait),d.addActionRule("saveDocument",!1,"saveDocument",d.update),d.addActionRule("saveDocument",!1,"loadDocument",d.wait),d.addActionRule("saveDocument",!1,"removeDocument",d.eliminate),d.addActionRule("loadDocument",!0,"saveDocument",d.wait),d.addActionRule("loadDocument",!0,"loadDocument",d.dontAccept),d.addActionRule("loadDocument",!0,"removeDocument",d.wait),d.addActionRule("loadDocument",!1,"saveDocument",d.wait),d.addActionRule("loadDocument",!1,"loadDocument",d.update),d.addActionRule("loadDocument",!1,"removeDocument",d.wait),d.addActionRule("removeDocument",!0,"loadDocument",d.dontAccept),d.addActionRule("removeDocument",!0,"removeDocument",d.dontAccept),d.addActionRule("removeDocument",!1,"saveDocument",d.eliminate),d.addActionRule("removeDocument",!1,"loadDocument",d.dontAccept),d.addActionRule("removeDocument",!1,"removeDocument",d.update),d.addActionRule("getDocumentList",!0,"getDocumentList",d.dontAccept),d.addActionRule("getDocumentList",!1,"getDocumentList",d.update),d}(),i={};b=b||{},c=c||{};var j={},p="jio/id_array";return j.id=null,c.jobManager=g,c.jobIdHandler=f,j.storage_spec=b,j.init=function(){if(j.id===null){var a,b=LocalOrCookieStorage.getItem(p)||[];j.id=1;for(a=0;a<b.length;a+=1)b[a]>=j.id&&(j.id=b[a]+1);b.push(j.id),LocalOrCookieStorage.setItem(p,b),d.setId(j.id),g.setId(j.id)}},i.start=function(){j.init(),d.start(),g.start()},i.stop=function(){g.stop()},i.close=function(){d.stop(),g.stop(),j.id=null},i.start(),i.getId=function(){return j.id},i.getJobRules=function(){return h},i.validateStorageDescription=function(a){return y.storage(a,c).isValid()},i.getJobArray=function(){return g.serialized()},i.saveDocument=function(a,b,d,e){d=d||{},d.onResponse=d.onResponse||function(){},d.onDone=d.onDone||function(){},d.onFail=d.onFail||function(){},d.max_retry=d.max_retry||0,g.addJob(v({storage:e?y.storage(e,c):y.storage(j.storage_spec,c),command:o({path:a,content:b,option:d},c)},c))},i.loadDocument=function(a,b,d){b=b||{},b.onResponse=b.onResponse||function(){},b.onDone=b.onDone||function(){},b.onFail=b.onFail||function(){},b.max_retry=b.max_retry||0,b.metadata_only=b.metadata_only!==undefined?b.metadata_only:!1,g.addJob(v({storage:d?y.storage(d,c):y.storage(j.storage_spec,c),command:m({path:a,option:b},c)},c))},i.removeDocument=function(a,b,d){b=b||{},b.onResponse=b.onResponse||function(){},b.onDone=b.onDone||function(){},b.onFail=b.onFail||function(){},b.max_retry=b.max_retry||0,g.addJob(v({storage:d?y.storage(d,c):y.storage(j.storage_spec,c),command:n({path:a,option:b},c)},c))},i.getDocumentList=function(a,b,d){b=b||{},b.onResponse=b.onResponse||function(){},b.onDone=b.onDone||function(){},b.onFail=b.onFail||function(){},b.max_retry=b.max_retry||0,b.metadata_only=b.metadata_only!==undefined?b.metadata_only:!0,g.addJob(v({storage:d?y.storage(d,c):y.storage(j.storage_spec,c),command:l({path:a,option:b},c)},c))},i},y=function(a,b){var c={};a=a||{},b=b||{};var d={base:i,handler:j};return c.storage=function(a,b,c){a=a||{},b=b||{};var f=c||a.type||"base";if(!d[f])throw e({type:f,message:"Storage does not exists."});return d[f](a,b)},c.newJio=function(a){var b=a;return typeof b=="string"&&(b=JSON.parse(b)),b=b||{type:"base"},x(a)},c.addStorageType=function(a,b){b=b||function(){return null};if(d[a])throw e({type:a,message:"Already known."});d[a]=b},c}();return y}(); var jio=function(){var a=function(a,b){var c={};return a=a||{},b=b||{},c.name="jioException",c.message=a.message||"Unknown Reason.",c.toString=function(){return c.name+": "+c.message},c},b=function(b,c){var d=a(b,c);b=b||{};var e=b.command;return d.name="invalidCommandState",d.toString=function(){return d.name+": "+e.getLabel()+", "+d.message},d},c=function(b,c){var d=a(b,c);b=b||{};var e=b.storage.getType();return d.name="invalidStorage",d.toString=function(){return d.name+": "+'Type "'+e+'", '+d.message},d},d=function(b,c){var d=a(b,c),e=b.type;return d.name="invalidStorageType",d.toString=function(){return d.name+": "+e+", "+d.message},d},e=function(b,c){var d=a(b,c);return d.name="jobNotReadyException",d},f=function(b,c){var d=a(b,c);return d.name="tooMuchTriesJobException",d},g=function(b,c){var d=a(b,c);return d.name="invalidJobException",d},h=function(a,b){var d={};a=a||{},b=b||{};var e={};return e.type=a.type||"",d.getType=function(){return e.type},d.setType=function(a){e.type=a},d.execute=function(a){d.validate(a),d.success=a.success,d.error=a.error,d.retry=a.retry,d.end=a.end,a.executeOn(d)},d.isValid=function(){return!0},d.validate=function(a){var b=d.validateState();if(b)throw c({storage:d,message:b});a.validate(d)},d.serialized=function(){return{type:d.getType()}},d.saveDocument=function(a){throw c({storage:d,message:"Unknown storage."})},d.loadDocument=function(a){d.saveDocument()},d.removeDocument=function(a){d.saveDocument()},d.getDocumentList=function(a){d.saveDocument()},d.validateState=function(){return""},d.success=function(){},d.retry=function(){},d.error=function(){},d.end=function(){},d},i=function(a,b){a=a||{},b=b||{};var c=h(a,b);return c.newCommand=function(a,c){var d=c||{};return d.label=a,j(d,b)},c.newStorage=function(a){var c=a||{};return x.storage(c,b)},c.addJob=function(a,c){b.jobManager.addJob(u({storage:a,command:c},b))},c},j=function(a,c){var d={};a=a||{},c=c||{};var e={};return e.commandlist={saveDocument:n,loadDocument:l,removeDocument:m,getDocumentList:k},a.label&&e.commandlist[a.label]?(e.label=a.label,delete a.label,e.commandlist[e.label](a,c)):(e.path=a.path||"",e.tried=0,e.option=a.option||{},e.success=e.option.success||function(){},e.error=e.option.error||function(){},e.retry=function(){d.error({status:13,statusText:"Fail Retry",message:"Impossible to retry."})},e.end=function(){},e.on_going=!1,d.serialized=function(){return{label:d.getLabel(),tried:e.tried,max_retry:e.max_retry,path:e.path,option:d.cloneOption()}},d.getLabel=function(){return"command"},d.getPath=function(){return e.path},d.getOption=function(a){return e.option[a]},d.validate=function(a){d.validateState()},d.canBeRetried=function(){return e.option.max_retry===0||e.tried<e.option.max_retry},d.getTried=function(){return e.tried},d.execute=function(a){e.on_going||(d.validate(a),e.tried++,e.on_going=!0,a.execute(d))},d.executeOn=function(a){},d.validateState=function(){if(e.path==="")throw b({command:d,message:"Path is empty"})},d.success=function(a){e.on_going=!1,e.success(a),e.end(p())},d.retry=function(a){e.on_going=!1,d.canBeRetried()?e.retry():d.error(a)},d.error=function(a){e.on_going=!1,e.error(a),e.end(q())},d.end=function(){e.end(p())},d.onSuccessDo=function(a){if(a)e.success=a;else return e.success},d.onErrorDo=function(a){if(a)e.error=a;else return e.error},d.onEndDo=function(a){e.end=a},d.onRetryDo=function(a){e.retry=a},d.canBeRestored=function(){return!0},d.clone=function(){return j(d.serialized(),c)},d.cloneOption=function(){var a,b={};for(a in e.option)b[a]=e.option[a];return b},d)},k=function(a,b){var c=j(a,b);a=a||{},b=b||{},c.getLabel=function(){return"getDocumentList"},c.executeOn=function(a){a.getDocumentList(c)},c.canBeRestored=function(){return!1};var d=c.success;return c.success=function(a){var b;if(a)for(b=0;b<a.length;b+=1)typeof a[b].last_modified!="number"&&(a[b].last_modified=(new Date(a[b].last_modified)).getTime()),typeof a[b].creation_date!="number"&&(a[b].creation_date=(new Date(a[b].creation_date)).getTime());d(a)},c},l=function(a,b){var c=j(a,b);a=a||{},b=b||{},c.getLabel=function(){return"loadDocument"},c.executeOn=function(a){a.loadDocument(c)},c.canBeRestored=function(){return!1};var d=c.success;return c.success=function(a){a&&(typeof a.last_modified!="number"&&(a.last_modified=(new Date(a.last_modified)).getTime()),typeof a.creation_date!="number"&&(a.creation_date=(new Date(a.creation_date)).getTime())),d(a)},c},m=function(a,b){var c=j(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"removeDocument"},c.executeOn=function(a){a.removeDocument(c)},c},n=function(a,c){var d=j(a,c);a=a||{},c=c||{};var e={};e.content=a.content,d.getLabel=function(){return"saveDocument"},d.getContent=function(){return e.content};var f=d.validate;d.validate=function(a){if(typeof e.content!="string")throw b({command:d,message:"No data to save"});f(a)},d.executeOn=function(a){a.saveDocument(d)};var g=d.serialized;return d.serialized=function(){var a=g();return a.content=e.content,a},d},o=function(a,b){var c={};return a=a||{},b=b||{},c.getLabel=function(){return"job status"},c.canStart=function(){},c.canRestart=function(){},c.serialized=function(){return{label:c.getLabel()}},c.isWaitStatus=function(){return!1},c.isDone=function(){return!1},c},p=function(a,b){var c=o(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"done"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c.isDone=function(){return!0},c},q=function(a,b){var c=o(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"fail"},c.canStart=function(){return!1},c.canRestart=function(){return!0},c},r=function(a,b){var c=o(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"initial"},c.canStart=function(){return!0},c.canRestart=function(){return!0},c},s=function(a,b){var c=o(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"on going"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},t=function(a,b){var c=o(a,b);a=a||{},b=b||{};var d={};return d.job_id_array=a.job_id_array||[],d.threshold=0,c.getLabel=function(){return"wait"},d.refreshJobIdArray=function(){var a=[],c;for(c=0;c<d.job_id_array.length;c+=1)b.jobManager.jobIdExists(d.job_id_array[c])&&a.push(d.job_id_array[c]);d.job_id_array=a},c.waitForJob=function(a){var b;for(b=0;b<d.job_id_array.length;b+=1)if(d.job_id_array[b]===a.getId())return;d.job_id_array.push(a.getId())},c.dontWaitForJob=function(a){var b,c=[];for(b=0;b<d.job_id_array.length;b+=1)d.job_id_array[b]!==a.getId()&&c.push(d.job_id_array[b]);d.job_id_array=c},c.waitForTime=function(a){d.threshold=Date.now()+a},c.stopWaitForTime=function(){d.threshold=0},c.canStart=function(){return d.refreshJobIdArray(),d.job_id_array.length===0&&Date.now()>=d.threshold},c.canRestart=function(){return c.canStart()},c.serialized=function(){return{label:c.getLabel(),waitfortime:d.threshold,waitforjob:d.job_id_array}},c.isWaitStatus=function(){return!0},c},u=function(a,b){var c={};a=a||{},b=b||{};var d={};d.id=b.jobIdHandler.nextId(),d.command=a.command,d.storage=a.storage,d.status=r(),d.date=new Date;if(!d.storage)throw g({job:c,message:"No storage set"});if(!d.command)throw g({job:c,message:"No command set"});return c.getCommand=function(){return d.command},c.getStatus=function(){return d.status},c.getId=function(){return d.id},c.getStorage=function(){return d.storage},c.getDate=function(){return d.date},c.isReady=function(){return c.getCommand().getTried()===0?d.status.canStart():d.status.canRestart()},c.serialized=function(){return{id:d.id,date:d.date.getTime(),status:d.status.serialized(),command:d.command.serialized(),storage:d.storage.serialized()}},c.waitForJob=function(a){d.status.getLabel()!=="wait"&&(d.status=t({},b)),d.status.waitForJob(a)},c.dontWaitFor=function(a){d.status.getLabel()==="wait"&&d.status.dontWaitForJob(a)},c.waitForTime=function(a){d.status.getLabel()!=="wait"&&(d.status=t({},b)),d.status.waitForTime(a)},c.stopWaitForTime=function(){d.status.getLabel()==="wait"&&d.status.stopWaitForTime()},c.eliminated=function(){d.command.error({status:10,statusText:"Stoped",message:"This job has been stoped by another one."})},c.notAccepted=function(){d.command.onEndDo(function(){d.status=q(),b.jobManager.terminateJob(c)}),d.command.error({status:11,statusText:"Not Accepted",message:"This job is already running."})},c.update=function(a){d.command.error({status:12,statusText:"Replaced",message:"Job has been replaced by another one."}),d.date=a.getDate(),d.command=a.getCommand(),d.status=a.getStatus()},c.execute=function(){if(!c.getCommand().canBeRetried())throw f({job:c,message:"The job was invoked too much time."});if(!c.isReady())throw e({job:c,message:"Can not execute this job."});d.status=s(),d.command.onRetryDo(function(){var a=d.command.getTried();a=a*a*200,a>1e4&&(a=1e4),c.waitForTime(a)}),d.command.onEndDo(function(a){d.status=a,b.jobManager.terminateJob(c)}),d.command.execute(d.storage)},c},v=function(a,b){var c={};a=a||{},b=b||{};var d=[],e=a.name||"",f=a.announcer||{};return c.add=function(a){d.push(a)},c.remove=function(a){var b,c=[];for(b=0;b<d.length;b+=1)d[b]!==a&&c.push(d[b]);d=c},c.register=function(){f.register(c)},c.unregister=function(){f.unregister(c)},c.trigger=function(a){var b;for(b=0;b<d.length;b++)d[b].apply(null,a)},c},w=function(a,b){var c=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.id=a.id||0,d.interval=400,d.interval_id=null,d.touch=function(){LocalOrCookieStorage.setItem("jio/id/"+d.id,Date.now())},c.setId=function(a){d.id=a},c.setIntervalDelay=function(a){d.interval=a},c.getIntervalDelay=function(){return d.interval},c.start=function(){d.interval_id||(d.touch(),d.interval_id=setInterval(function(){d.touch()},d.interval))},c.stop=function(){d.interval_id!==null&&(clearInterval(d.interval_id),d.interval_id=null)},c}(),d=function(a,b){var c={};a=a||{},b=b||{};var d={};return c.register=function(a){d[a]||(d[a]=v())},c.unregister=function(a){d[a]&&delete d[a]},c.at=function(a){return d[a]},c.on=function(a,b){c.register(a),c.at(a).add(b)},c.trigger=function(a,b){c.at(a).trigger(b)},c}(),e=function(a,b){var c={};a=a||{},b=b||{};var d=0;return c.nextId=function(){return d=d+1,d},c}(),f=function(a,b){var c={};a=a||{},b=b||{};var d="jio/job_array",f={};return f.id=a.id,f.interval_id=null,f.interval=200,f.job_array=[],b.jobManager=c,b.jobIdHandler=e,f.getJobArrayName=function(){return d+"/"+f.id},f.getJobArray=function(){return LocalOrCookieStorage.getItem(f.getJobArrayName())||[]},f.copyJobArrayToLocal=function(){var a=[],b;for(b=0;b<f.job_array.length;b+=1)a.push(f.job_array[b].serialized());LocalOrCookieStorage.setItem(f.getJobArrayName(),a)},f.removeJob=function(a){var b,c=[];for(b=0;b<f.job_array.length;b+=1)f.job_array[b]!==a&&c.push(f.job_array[b]);f.job_array=c,f.copyJobArrayToLocal()},c.setId=function(a){f.id=a},c.start=function(){var a;f.interval_id===null&&(f.interval_id=setInterval(function(){f.restoreOldJio();for(a=0;a<f.job_array.length;a+=1)c.execute(f.job_array[a])},f.interval))},c.stop=function(){f.interval_id!==null&&(clearInterval(f.interval_id),f.interval_id=null,f.job_array.length===0&&LocalOrCookieStorage.deleteItem(f.getJobArrayName()))},f.restoreOldJio=function(){var a,b;f.lastrestore=f.lastrestore||0;if(f.lastrestore>Date.now()-2e3)return;b=LocalOrCookieStorage.getItem("jio/id_array")||[];for(a=0;a<b.length;a+=1)f.restoreOldJioId(b[a]);f.lastrestore=Date.now()},f.restoreOldJioId=function(a){var b;b=LocalOrCookieStorage.getItem("jio/id/"+a)||0,b<Date.now()-1e4&&(f.restoreOldJobFromJioId(a),f.removeOldJioId(a),f.removeJobArrayFromJioId(a))},f.restoreOldJobFromJioId=function(a){var d,e;e=LocalOrCookieStorage.getItem("jio/job_array/"+a)||[];for(d=0;d<e.length;d+=1){var f=j(e[d].command,b);f.canBeRestored()&&c.addJob(u({storage:x.storage(e[d].storage,b),command:f},b))}},f.removeOldJioId=function(a){var b,c,d=[];c=LocalOrCookieStorage.getItem("jio/id_array")||[];for(b=0;b<c.length;b+=1)c[b]!==a&&d.push(c[b]);LocalOrCookieStorage.setItem("jio/id_array",d),LocalOrCookieStorage.deleteItem("jio/id/"+a)},f.removeJobArrayFromJioId=function(a){LocalOrCookieStorage.deleteItem("jio/job_array/"+a)},c.execute=function(a){try{a.execute()}catch(b){switch(b.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw b}}f.copyJobArrayToLocal()},c.jobIdExists=function(a){var b;for(b=0;b<f.job_array.length;b+=1)if(f.job_array[b].getId()===a)return!0;return!1},c.terminateJob=function(a){f.removeJob(a)},c.addJob=function(a){var b=c.validateJobAccordingToJobList(f.job_array,a);f.appendJob(a,b)},c.validateJobAccordingToJobList=function(a,b){var c,d=[];for(c=0;c<a.length;c+=1)d.push(g.validateJobAccordingToJob(a[c],b));return d},f.appendJob=function(a,b){var c;if(f.job_array.length!==b.length)throw new RangeError("Array out of bound");for(c=0;c<b.length;c+=1)if(b[c].action==="dont accept")return a.notAccepted();for(c=0;c<b.length;c+=1)switch(b[c].action){case"eliminate":b[c].job.eliminated(),f.removeJob(b[c].job);break;case"update":b[c].job.update(a),f.copyJobArrayToLocal();return;case"wait":a.waitForJob(b[c].job);break;default:}f.job_array.push(a),f.copyJobArrayToLocal()},c.serialized=function(){var a=[],b,c=f.job_array||[];for(b=0;b<c.length;b+=1)a.push(c[b].serialized());return a},c}(),g=function(a,b){var c={},d={};return d.compare={},d.action={},c.eliminate=function(){return"eliminate"},c.update=function(){return"update"},c.dontAccept=function(){return"dont accept"},c.wait=function(){return"wait"},c.none=function(){return"none"},c.default_action=c.none,c.default_compare=function(a,b){return a.getCommand().getPath()===b.getCommand().getPath()&&JSON.stringify(a.getStorage().serialized())===JSON.stringify(b.getStorage().serialized())},d.getAction=function(a,b){var e,f,g;return e=a.getCommand().getLabel(),f=b.getCommand().getLabel(),g=a.getStatus().getLabel()==="on going"?"on going":"not on going",d.action[e]&&d.action[e][g]&&d.action[e][g][f]?d.action[e][g][f](a,b):c.default_action(a,b)},d.canCompare=function(a,b){var e=a.getCommand().getLabel(),f=b.getCommand().getLabel();return d.compare[e]&&d.compare[f]?d.compare[e][f](a,b):c.default_compare(a,b)},c.validateJobAccordingToJob=function(a,b){return d.canCompare(a,b)?{action:d.getAction(a,b),job:a}:{action:c.default_action(a,b),job:a}},c.addActionRule=function(a,b,c,e){var f=b?"on going":"not on going";d.action[a]=d.action[a]||{},d.action[a][f]=d.action[a][f]||{},d.action[a][f][c]=e},c.addCompareRule=function(a,b,c){d.compare[a]=d.compare[a]||{},d.compare[a][b]=c},c.addActionRule("saveDocument",!0,"saveDocument",function(a,b){return a.getCommand().getContent()===b.getCommand().getContent()?c.dontAccept():c.wait()}),c.addActionRule("saveDocument",!0,"loadDocument",c.wait),c.addActionRule("saveDocument",!0,"removeDocument",c.wait),c.addActionRule("saveDocument",!1,"saveDocument",c.update),c.addActionRule("saveDocument",!1,"loadDocument",c.wait),c.addActionRule("saveDocument",!1,"removeDocument",c.eliminate),c.addActionRule("loadDocument",!0,"saveDocument",c.wait),c.addActionRule("loadDocument",!0,"loadDocument",c.dontAccept),c.addActionRule("loadDocument",!0,"removeDocument",c.wait),c.addActionRule("loadDocument",!1,"saveDocument",c.wait),c.addActionRule("loadDocument",!1,"loadDocument",c.update),c.addActionRule("loadDocument",!1,"removeDocument",c.wait),c.addActionRule("removeDocument",!0,"loadDocument",c.dontAccept),c.addActionRule("removeDocument",!0,"removeDocument",c.dontAccept),c.addActionRule("removeDocument",!1,"saveDocument",c.eliminate),c.addActionRule("removeDocument",!1,"loadDocument",c.dontAccept),c.addActionRule("removeDocument",!1,"removeDocument",c.update),c.addActionRule("getDocumentList",!0,"getDocumentList",c.dontAccept),c.addActionRule("getDocumentList",!1,"getDocumentList",c.update),c}(),h={};a=a||{},b=b||{};var i={},o="jio/id_array";return i.id=null,b.jobManager=f,b.jobIdHandler=e,i.storage_spec=a,i.init=function(){if(i.id===null){var a,b=LocalOrCookieStorage.getItem(o)||[];i.id=1;for(a=0;a<b.length;a+=1)b[a]>=i.id&&(i.id=b[a]+1);b.push(i.id),LocalOrCookieStorage.setItem(o,b),c.setId(i.id),f.setId(i.id)}},h.start=function(){i.init(),c.start(),f.start()},h.stop=function(){f.stop()},h.close=function(){c.stop(),f.stop(),i.id=null},h.start(),h.getId=function(){return i.id},h.getJobRules=function(){return g},h.validateStorageDescription=function(a){return x.storage(a,b).isValid()},h.getJobArray=function(){return f.serialized()},h.saveDocument=function(a,c,d,e){d=d||{},d.success=d.success||function(){},d.error=d.error||function(){},d.max_retry=d.max_retry||0,f.addJob(u({storage:e?x.storage(e,b):x.storage(i.storage_spec,b),command:n({path:a,content:c,option:d},b)},b))},h.loadDocument=function(a,c,d){c=c||{},c.success=c.success||function(){},c.error=c.error||function(){},c.max_retry=c.max_retry||0,c.metadata_only=c.metadata_only!==undefined?c.metadata_only:!1,f.addJob(u({storage:d?x.storage(d,b):x.storage(i.storage_spec,b),command:l({path:a,option:c},b)},b))},h.removeDocument=function(a,c,d){c=c||{},c.success=c.success||function(){},c.error=c.error||function(){},c.max_retry=c.max_retry||0,f.addJob(u({storage:d?x.storage(d,b):x.storage(i.storage_spec,b),command:m({path:a,option:c},b)},b))},h.getDocumentList=function(a,c,d){c=c||{},c.success=c.success||function(){},c.error=c.error||function(){},c.max_retry=c.max_retry||0,c.metadata_only=c.metadata_only!==undefined?c.metadata_only:!0,f.addJob(u({storage:d?x.storage(d,b):x.storage(i.storage_spec,b),command:k({path:a,option:c},b)},b))},h},x=function(a,b){var c={};a=a||{},b=b||{};var e={base:h,handler:i};return c.storage=function(a,b,c){a=a||{},b=b||{};var f=c||a.type||"base";if(!e[f])throw d({type:f,message:"Storage does not exists."});return e[f](a,b)},c.newJio=function(a){var b=a;return typeof b=="string"&&(b=JSON.parse(b)),b=b||{type:"base"},w(a)},c.addStorageType=function(a,b){b=b||function(){return null};if(e[a])throw d({type:a,message:"Already known."});e[a]=b},c}();return x}();
\ No newline at end of file \ No newline at end of file
...@@ -18,17 +18,30 @@ var command = function(spec, my) { ...@@ -18,17 +18,30 @@ var command = function(spec, my) {
priv.path = spec.path || ''; priv.path = spec.path || '';
priv.tried = 0; priv.tried = 0;
priv.option = spec.option || {}; priv.option = spec.option || {};
priv.respond = priv.option.onResponse || function(){}; priv.success = priv.option.success || function (){};
priv.done = priv.option.onDone || function(){}; priv.error = priv.option.error || function (){};
priv.fail = priv.option.onFail || function(){};
priv.retry = function() { priv.retry = function() {
that.setMaxRetry(-1); that.error({status:13,statusText:'Fail Retry',
that.fail({status:0,statusText:'Fail Retry', message:'Impossible to retry.'});
message:'Impossible to retry.'});
}; };
priv.end = function() {}; priv.end = function() {};
priv.on_going = false;
// Methods // // Methods //
/**
* Returns a serialized version of this command.
* Override this function.
* @method serialized
* @return {object} The serialized command.
*/
that.serialized = function() {
return {label:that.getLabel(),
tried:priv.tried,
max_retry:priv.max_retry,
path:priv.path,
option:that.cloneOption()};
};
/** /**
* Returns the label of the command. * Returns the label of the command.
* @method getLabel * @method getLabel
...@@ -66,12 +79,13 @@ var command = function(spec, my) { ...@@ -66,12 +79,13 @@ var command = function(spec, my) {
that.validateState(); that.validateState();
}; };
that.getTried = function() { that.canBeRetried = function () {
return priv.tried; return (priv.option.max_retry === 0 ||
priv.tried < priv.option.max_retry);
}; };
that.setMaxRetry = function(max_retry) { that.getTried = function() {
priv.option.max_retry = max_retry; return priv.tried;
}; };
/** /**
...@@ -79,9 +93,12 @@ var command = function(spec, my) { ...@@ -79,9 +93,12 @@ var command = function(spec, my) {
* @param {object} handler The storage handler. * @param {object} handler The storage handler.
*/ */
that.execute = function(handler) { that.execute = function(handler) {
that.validate(handler); if (!priv.on_going) {
priv.tried ++; that.validate(handler);
handler.execute(that); priv.tried ++;
priv.on_going = true;
handler.execute(that);
}
}; };
/** /**
...@@ -102,49 +119,44 @@ var command = function(spec, my) { ...@@ -102,49 +119,44 @@ var command = function(spec, my) {
} }
}; };
that.done = function(return_value) { that.success = function(return_value) {
log ('command done: ' + JSON.stringify (return_value)); priv.on_going = false;
priv.respond({status:doneStatus(),value:return_value}); priv.success (return_value);
priv.done(return_value);
priv.end(doneStatus()); priv.end(doneStatus());
}; };
that.fail = function(return_error) { that.retry = function (return_error) {
log ('command fail: ' + JSON.stringify (return_error)); priv.on_going = false;
if (priv.option.max_retry === 0 || priv.tried < priv.option.max_retry) { if (that.canBeRetried()) {
priv.retry(); priv.retry();
} else { } else {
priv.respond({status:failStatus(),error:return_error}); that.error (return_error);
priv.fail(return_error);
priv.end(failStatus());
} }
}; };
that.end = function () { that.error = function(return_error) {
priv.end(doneStatus()); priv.on_going = false;
priv.error(return_error);
priv.end(failStatus());
}; };
that.onResponseDo = function (fun) { that.end = function () {
if (fun) { priv.end(doneStatus());
priv.respond = fun;
} else {
return priv.respond;
}
}; };
that.onDoneDo = function (fun) { that.onSuccessDo = function (fun) {
if (fun) { if (fun) {
priv.done = fun; priv.success = fun;
} else { } else {
return priv.done; return priv.success;
} }
}; };
that.onFailDo = function (fun) { that.onErrorDo = function (fun) {
if (fun) { if (fun) {
priv.fail = fun; priv.error = fun;
} else { } else {
return priv.fail; return priv.error;
} }
}; };
...@@ -156,20 +168,6 @@ var command = function(spec, my) { ...@@ -156,20 +168,6 @@ var command = function(spec, my) {
priv.retry = fun; priv.retry = fun;
}; };
/**
* Returns a serialized version of this command.
* Override this function.
* @method serialized
* @return {object} The serialized command.
*/
that.serialized = function() {
return {label:that.getLabel(),
tried:priv.tried,
max_retry:priv.max_retry,
path:priv.path,
option:that.cloneOption()};
};
/** /**
* Is the command can be restored by another JIO : yes. * Is the command can be restored by another JIO : yes.
* @method canBeRestored * @method canBeRestored
...@@ -194,12 +192,10 @@ var command = function(spec, my) { ...@@ -194,12 +192,10 @@ var command = function(spec, my) {
* @return {object} The clone of the command options. * @return {object} The clone of the command options.
*/ */
that.cloneOption = function () { that.cloneOption = function () {
// log ('command cloneOption(): ' + JSON.stringify (priv.option));
var k, o = {}; var k, o = {};
for (k in priv.option) { for (k in priv.option) {
o[k] = priv.option[k]; o[k] = priv.option[k];
} }
// log ('cloneOption result: ' + JSON.stringify (o));
return o; return o;
}; };
......
...@@ -16,8 +16,8 @@ var getDocumentList = function(spec, my) { ...@@ -16,8 +16,8 @@ var getDocumentList = function(spec, my) {
return false; return false;
}; };
var super_done = that.done; var super_success = that.success;
that.done = function (res) { that.success = function (res) {
var i; var i;
if (res) { if (res) {
for (i = 0; i < res.length; i+= 1) { for (i = 0; i < res.length; i+= 1) {
...@@ -31,7 +31,7 @@ var getDocumentList = function(spec, my) { ...@@ -31,7 +31,7 @@ var getDocumentList = function(spec, my) {
} }
} }
} }
super_done(res); super_success(res);
}; };
return that; return that;
......
...@@ -16,8 +16,8 @@ var loadDocument = function(spec, my) { ...@@ -16,8 +16,8 @@ var loadDocument = function(spec, my) {
return false; return false;
}; };
var super_done = that.done; var super_success = that.success;
that.done = function (res) { that.success = function (res) {
if (res) { if (res) {
if (typeof res.last_modified !== 'number') { if (typeof res.last_modified !== 'number') {
res.last_modified=new Date(res.last_modified).getTime(); res.last_modified=new Date(res.last_modified).getTime();
...@@ -26,7 +26,7 @@ var loadDocument = function(spec, my) { ...@@ -26,7 +26,7 @@ var loadDocument = function(spec, my) {
res.creation_date=new Date(res.creation_date).getTime(); res.creation_date=new Date(res.creation_date).getTime();
} }
} }
super_done(res); super_success(res);
}; };
return that; return that;
}; };
var jio = (function () { var jio = (function () {
var log = function(){};
// var log = console.log;
...@@ -84,18 +84,16 @@ ...@@ -84,18 +84,16 @@
* @param {string} path The document path name. * @param {string} path The document path name.
* @param {string} content The document's content. * @param {string} content The document's content.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
* you want to save this document elsewhere. * you want to save this document elsewhere.
*/ */
that.saveDocument = function(path, content, option, specificstorage) { that.saveDocument = function(path, content, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
jobManager.addJob( jobManager.addJob(
job({storage:(specificstorage? job({storage:(specificstorage?
...@@ -110,9 +108,8 @@ ...@@ -110,9 +108,8 @@
* @method loadDocument * @method loadDocument
* @param {string} path The document path name. * @param {string} path The document path name.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* - {boolean} metadata_only Load only document metadata. * - {boolean} metadata_only Load only document metadata.
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
...@@ -120,9 +117,8 @@ ...@@ -120,9 +117,8 @@
*/ */
that.loadDocument = function(path, option, specificstorage) { that.loadDocument = function(path, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
option.metadata_only = (option.metadata_only !== undefined? option.metadata_only = (option.metadata_only !== undefined?
option.metadata_only:false); option.metadata_only:false);
...@@ -139,18 +135,16 @@ ...@@ -139,18 +135,16 @@
* @method removeDocument * @method removeDocument
* @param {string} path The document path name. * @param {string} path The document path name.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
* you want to save this document elsewhere. * you want to save this document elsewhere.
*/ */
that.removeDocument = function(path, option, specificstorage) { that.removeDocument = function(path, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
jobManager.addJob( jobManager.addJob(
job({storage:(specificstorage? job({storage:(specificstorage?
...@@ -165,9 +159,8 @@ ...@@ -165,9 +159,8 @@
* @method getDocumentList * @method getDocumentList
* @param {string} path The folder path. * @param {string} path The folder path.
* @param {object} option (optional) Contains some options: * @param {object} option (optional) Contains some options:
* - {function} onResponse The callback called when the job is terminated. * - {function} success The callback called when the job has passed.
* - {function} onDone The callback called when the job has passed. * - {function} error The callback called when the job has fail.
* - {function} onFail The callback called when the job has fail.
* - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
* - {boolean} metadata_only Load only document metadata * - {boolean} metadata_only Load only document metadata
* @param {object} specificstorage (optional) A specific storage, only if * @param {object} specificstorage (optional) A specific storage, only if
...@@ -175,9 +168,8 @@ ...@@ -175,9 +168,8 @@
*/ */
that.getDocumentList = function(path, option, specificstorage) { that.getDocumentList = function(path, option, specificstorage) {
option = option || {}; option = option || {};
option.onResponse = option.onResponse || function(){}; option.success = option.success || function(){};
option.onDone = option.onDone || function(){}; option.error = option.error || function(){};
option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
option.metadata_only = (option.metadata_only !== undefined? option.metadata_only = (option.metadata_only !== undefined?
option.metadata_only:true); option.metadata_only:true);
......
...@@ -9,8 +9,6 @@ var job = function(spec, my) { ...@@ -9,8 +9,6 @@ var job = function(spec, my) {
priv.storage = spec.storage; priv.storage = spec.storage;
priv.status = initialStatus(); priv.status = initialStatus();
priv.date = new Date(); priv.date = new Date();
log ('new job spec: ' + JSON.stringify (spec) + ', priv: ' +
JSON.stringify (priv));
// Initialize // // Initialize //
if (!priv.storage){ if (!priv.storage){
...@@ -51,7 +49,7 @@ var job = function(spec, my) { ...@@ -51,7 +49,7 @@ var job = function(spec, my) {
* @return {boolean} true if ready, else false. * @return {boolean} true if ready, else false.
*/ */
that.isReady = function() { that.isReady = function() {
if (priv.tried === 0) { if (that.getCommand().getTried() === 0) {
return priv.status.canStart(); return priv.status.canStart();
} else { } else {
return priv.status.canRestart(); return priv.status.canRestart();
...@@ -77,7 +75,6 @@ var job = function(spec, my) { ...@@ -77,7 +75,6 @@ var job = function(spec, my) {
* @param {object} job The job to wait for. * @param {object} job The job to wait for.
*/ */
that.waitForJob = function(job) { that.waitForJob = function(job) {
log ('job waitForJob(job): ' + JSON.stringify (job.serialized()));
if (priv.status.getLabel() !== 'wait') { if (priv.status.getLabel() !== 'wait') {
priv.status = waitStatus({},my); priv.status = waitStatus({},my);
} }
...@@ -101,7 +98,6 @@ var job = function(spec, my) { ...@@ -101,7 +98,6 @@ var job = function(spec, my) {
* @param {number} ms Time to wait in millisecond. * @param {number} ms Time to wait in millisecond.
*/ */
that.waitForTime = function(ms) { that.waitForTime = function(ms) {
log ('job waitForTime(ms): ' + ms);
if (priv.status.getLabel() !== 'wait') { if (priv.status.getLabel() !== 'wait') {
priv.status = waitStatus({},my); priv.status = waitStatus({},my);
} }
...@@ -119,21 +115,18 @@ var job = function(spec, my) { ...@@ -119,21 +115,18 @@ var job = function(spec, my) {
}; };
that.eliminated = function () { that.eliminated = function () {
priv.command.setMaxRetry(-1); priv.command.error ({
log ('job eliminated(): '+JSON.stringify (that.serialized())); status:10,statusText:'Stoped',
priv.command.fail({status:0,statusText:'Stoped', message:'This job has been stoped by another one.'});
message:'This job has been stoped by another one.'});
}; };
that.notAccepted = function () { that.notAccepted = function () {
log ('job notAccepted(): '+JSON.stringify (that.serialized()));
priv.command.setMaxRetry(-1);
priv.command.onEndDo (function () { priv.command.onEndDo (function () {
priv.status = failStatus(); priv.status = failStatus();
my.jobManager.terminateJob (that); my.jobManager.terminateJob (that);
}); });
priv.command.fail ({status:0,statusText:'Not Accepted', priv.command.error ({status:11,statusText:'Not Accepted',
message:'This job is already running.'}); message:'This job is already running.'});
}; };
/** /**
...@@ -142,30 +135,24 @@ var job = function(spec, my) { ...@@ -142,30 +135,24 @@ var job = function(spec, my) {
* @param {object} job The other job. * @param {object} job The other job.
*/ */
that.update = function(job) { that.update = function(job) {
log ('job update(job): ' + JSON.stringify (job.serialized())); priv.command.error ({status:12,statusText:'Replaced',
priv.command.setMaxRetry(-1); message:'Job has been replaced by another one.'});
priv.command.onEndDo(function (status) {
log ('job update on end' + status.getLabel());
});
priv.command.fail({status:0,statusText:'Replaced',
message:'Job has been replaced by another one.'});
priv.date = job.getDate(); priv.date = job.getDate();
priv.command = job.getCommand(); priv.command = job.getCommand();
priv.status = job.getStatus(); priv.status = job.getStatus();
}; };
that.execute = function() { that.execute = function() {
log ('job execute(): ' + JSON.stringify (that.serialized())); if (!that.getCommand().canBeRetried()) {
if (priv.max_retry !== 0 && priv.tried >= priv.max_retry) {
throw tooMuchTriesJobException( throw tooMuchTriesJobException(
{job:that,message:'The job was invoked too much time.'}); {job:that,message:'The job was invoked too much time.'});
} }
if (!that.isReady()) { if (!that.isReady()) {
throw jobNotReadyException({message:'Can not execute this job.'}); throw jobNotReadyException(
{job:that,message:'Can not execute this job.'});
} }
priv.status = onGoingStatus(); priv.status = onGoingStatus();
priv.command.onRetryDo (function() { priv.command.onRetryDo (function() {
log ('command.retry job:' + JSON.stringify (that.serialized()));
var ms = priv.command.getTried(); var ms = priv.command.getTried();
ms = ms*ms*200; ms = ms*ms*200;
if (ms>10000){ if (ms>10000){
...@@ -175,7 +162,6 @@ var job = function(spec, my) { ...@@ -175,7 +162,6 @@ var job = function(spec, my) {
}); });
priv.command.onEndDo (function(status) { priv.command.onEndDo (function(status) {
priv.status = status; priv.status = status;
log ('command.end job:' + JSON.stringify (that.serialized()));
my.jobManager.terminateJob (that); my.jobManager.terminateJob (that);
}); });
priv.command.execute (priv.storage); priv.command.execute (priv.storage);
......
...@@ -124,7 +124,7 @@ var jobManager = (function(spec, my) { ...@@ -124,7 +124,7 @@ var jobManager = (function(spec, my) {
priv.restoreOldJioId = function(id) { priv.restoreOldJioId = function(id) {
var jio_date; var jio_date;
jio_date = LocalOrCookieStorage.getItem('jio/id/'+id)||0; jio_date = LocalOrCookieStorage.getItem('jio/id/'+id)||0;
if (jio_date < Date.now() - 10000) { if (jio_date < (Date.now() - 10000)) { // 10 sec
priv.restoreOldJobFromJioId(id); priv.restoreOldJobFromJioId(id);
priv.removeOldJioId(id); priv.removeOldJioId(id);
priv.removeJobArrayFromJioId(id); priv.removeJobArrayFromJioId(id);
......
...@@ -12,14 +12,6 @@ var jobRules = (function(spec, my) { ...@@ -12,14 +12,6 @@ var jobRules = (function(spec, my) {
that.none = function() { return 'none'; }; that.none = function() { return 'none'; };
that.default_action = that.none; that.default_action = that.none;
that.default_compare = function(job1,job2) { that.default_compare = function(job1,job2) {
if (job1.getCommand().getPath() === job2.getCommand().getPath() &&
JSON.stringify(job1.getStorage().serialized()) ===
JSON.stringify(job2.getStorage().serialized())) {
log ('same ! ' + job1.getCommand().getPath() + ', ' +
job2.getCommand().getPath() + ', ' +
JSON.stringify (job1.getStorage().serialized())+', '+
JSON.stringify (job2.getStorage().serialized()));
}
return (job1.getCommand().getPath() === job2.getCommand().getPath() && return (job1.getCommand().getPath() === job2.getCommand().getPath() &&
JSON.stringify(job1.getStorage().serialized()) === JSON.stringify(job1.getStorage().serialized()) ===
JSON.stringify(job2.getStorage().serialized())); JSON.stringify(job2.getStorage().serialized()));
......
...@@ -5,7 +5,6 @@ var storage = function(spec, my) { ...@@ -5,7 +5,6 @@ var storage = function(spec, my) {
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.type = spec.type || ''; priv.type = spec.type || '';
log ('new storage spec: ' + JSON.stringify (spec));
// Methods // // Methods //
that.getType = function() { that.getType = function() {
...@@ -21,12 +20,11 @@ var storage = function(spec, my) { ...@@ -21,12 +20,11 @@ var storage = function(spec, my) {
* @param {object} command The command * @param {object} command The command
*/ */
that.execute = function(command) { that.execute = function(command) {
log ('storage '+that.getType()+' execute(command): ' +
JSON.stringify (command.serialized()));
that.validate(command); that.validate(command);
that.done = command.done; that.success = command.success;
that.fail = command.fail; that.error = command.error;
that.end = command.end; that.retry = command.retry;
that.end = command.end;
command.executeOn(that); command.executeOn(that);
}; };
...@@ -78,9 +76,10 @@ var storage = function(spec, my) { ...@@ -78,9 +76,10 @@ var storage = function(spec, my) {
return ''; return '';
}; };
that.done = function() {}; that.success = function() {};
that.fail = function() {}; that.retry = function() {};
that.end = function() {}; // terminate the current job. that.error = function() {};
that.end = function() {}; // terminate the current job.
return that; return that;
}; };
...@@ -2,7 +2,6 @@ var storageHandler = function(spec, my) { ...@@ -2,7 +2,6 @@ var storageHandler = function(spec, my) {
spec = spec || {}; spec = spec || {};
my = my || {}; my = my || {};
var that = storage( spec, my ); var that = storage( spec, my );
log ('new storageHandler spec: '+JSON.stringify (spec));
that.newCommand = function (method, spec) { that.newCommand = function (method, spec) {
var o = spec || {}; var o = spec || {};
...@@ -16,10 +15,6 @@ var storageHandler = function(spec, my) { ...@@ -16,10 +15,6 @@ var storageHandler = function(spec, my) {
}; };
that.addJob = function (storage,command) { that.addJob = function (storage,command) {
log ('storageHandler ' + that.getType() +
' addJob (storage, command): ' +
JSON.stringify (storage.serialized()) + ', ' +
JSON.stringify (command.serialized()));
my.jobManager.addJob ( job({storage:storage, command:command}, my) ); my.jobManager.addJob ( job({storage:storage, command:command}, my) );
}; };
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment