Commit 3d2ae5e9 authored by Tristan Cavelier's avatar Tristan Cavelier

Improving the new jio, it just doesn't restore older jio instance for now.

parent a9caa60c
...@@ -16,28 +16,27 @@ module.exports = function(grunt) { ...@@ -16,28 +16,27 @@ module.exports = function(grunt) {
src: ['<banner:meta.banner>', src: ['<banner:meta.banner>',
// Wrapper top // Wrapper top
'<file_strip_banner:../../src/<%= pkg.name %>/wrapper.top.js>', '<file_strip_banner:../../src/<%= pkg.name %>/wrapper.top.js>',
// Classes '<file_strip_banner:../../src/<%= pkg.name %>/exceptions.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/storages/storage.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/storages/storageHandler.js>',
// Jio wrapper top
'<file_strip_banner:../../src/<%= pkg.name %>/jio.top.js>',
// Jio Classes
'<file_strip_banner:../../src/<%= pkg.name %>/commands/command.js>', '<file_strip_banner:../../src/<%= pkg.name %>/commands/command.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/commands/getDocumentList.js>', '<file_strip_banner:../../src/<%= pkg.name %>/commands/getDocumentList.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/commands/loadDocument.js>', '<file_strip_banner:../../src/<%= pkg.name %>/commands/loadDocument.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/commands/removeDocument.js>', '<file_strip_banner:../../src/<%= pkg.name %>/commands/removeDocument.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/commands/saveDocument.js>', '<file_strip_banner:../../src/<%= pkg.name %>/commands/saveDocument.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/exceptions.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/jobStatus.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/jobStatus.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/doneStatus.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/doneStatus.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/failStatus.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/failStatus.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/initialStatus.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/initialStatus.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/onGoingStatus.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/onGoingStatus.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/waitStatus.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/status/waitStatus.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/storages/storage.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/storages/storageHandler.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/activityUpdater.js>',
// Jio wrapper top
'<file_strip_banner:../../src/<%= pkg.name %>/jio.top.js>',
// Jio Classes
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/job.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/job.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/announcements/announcement.js>', '<file_strip_banner:../../src/<%= pkg.name %>/announcements/announcement.js>',
// Singletons // Singletons
'<file_strip_banner:../../src/<%= pkg.name %>/activityUpdater.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/announcements/announcer.js>', '<file_strip_banner:../../src/<%= pkg.name %>/announcements/announcer.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/jobIdHandler.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/jobIdHandler.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/jobs/jobManager.js>', '<file_strip_banner:../../src/<%= pkg.name %>/jobs/jobManager.js>',
......
/*! JIO - v0.1.0 - 2012-06-11 /*! JIO - v0.1.0 - 2012-06-12
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var jio = (function () { var jio = (function () {
var jioException = function(spec, my) {
var that = {};
spec = spec || {};
my = my || {};
that.name = 'jioException';
that.message = spec.message || 'Unknown Reason.';
that.toString = function() {
return that.name + ': ' + that.message;
};
return that;
};
var invalidCommandState = function(spec, my) {
var that = jioException(spec, my);
spec = spec || {};
var command = spec.command;
that.name = 'invalidCommandState';
that.toString = function() {
return that.name +': ' +
command.getLabel() + ', ' + that.message;
};
return that;
};
var invalidStorage = function(spec, my) {
var that = jioException(spec, my);
spec = spec || {};
var type = spec.storage.getType();
that.name = 'invalidStorage';
that.toString = function() {
return that.name +': ' +
'Type "'+type + '", ' + that.message;
};
return that;
};
var invalidStorageType = function(spec, my) {
var that = jioException(spec, my);
var type = spec.type;
that.name = 'invalidStorageType';
that.toString = function() {
return that.name +': ' +
type + ', ' + that.message;
};
return that;
};
var jobNotReadyException = function(spec, my) {
var that = jioException(spec, my);
that.name = 'jobNotReadyException';
return that;
};
var tooMuchTriesJobException = function(spec, my) {
var that = jioException(spec, my);
that.name = 'tooMuchTriesJobException';
return that;
};
var invalidJobException = function(spec, my) {
var that = jioException(spec, my);
that.name = 'invalidJobException';
return that;
};
var storage = function(spec, my) {
var that = {};
spec = spec || {};
my = my || {};
// Attributes //
var priv = {};
priv.type = spec.type || '';
// my.jio exists
// Methods //
that.getType = function() {
return priv.type;
};
that.setType = function(type) {
priv.type = type;
};
/**
* Execute the command on this storage.
* @method execute
* @param {object} command The command
*/
that.execute = function(command) {
command.executeOn(that);
};
/**
* Override this function to validate specifications.
* @method isValid
* @return {boolean} true if ok, else false.
*/
that.isValid = function() {
return true;
};
that.validate = function(command) {
command.validate(that);
};
/**
* Returns a serialized version of this storage.
* @method serialized
* @return {object} The serialized storage.
*/
that.serialized = function() {
return {type:that.getType()};
};
that.saveDocument = function(command) {
throw invalidStorage({storage:that,message:'Unknown storage.'});
};
that.loadDocument = function(command) {
that.saveDocument();
};
that.removeDocument = function(command) {
that.saveDocument();
};
that.getDocumentList = function(command) {
that.saveDocument();
};
return that;
};
var storageHandler = function(spec, my) {
var that = storage(spec, my);
spec = spec || {};
my = my || {};
// Attributes //
var priv = {};
priv.storage_a = spec.storagelist || [];
// Methods //
/**
* It is called before the execution.
* Override this function.
* @method beforeExecute
* @param {object} command The command.
* @param {object} option Some options.
*/
that.beforeExecute = function(command,option) {};
/**
* Execute the command according to this storage.
* @method execute
* @param {object} command The command.
* @param {object} option Some options.
*/
that.execute = function(command,option) {
var i;
that.validate(command);
that.beforeExecute(command,option);
for(i = 0; i < priv.storage_a.length; i++) {
priv.storage_a[i].execute(command);
}
that.afterExecute(command,option);
};
/**
* Is is called after the execution.
* Override this function.
* @method afterExecute
* @param {object} command The command.
* @param {object} option Some options.
*/
that.afterExecute = function(command,option) {
that.done();
};
/**
* Returns a serialized version of this storage
* @method serialized
* @return {object} The serialized storage.
*/
that.serialized = function() {
return {type:priv.type,
storagelist:priv.storagelist};
};
return that;
};
var jio = function(spec, my) {
var command = function(spec, my) { var command = function(spec, my) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
my = my || {}; my = my || {};
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.commandlist = {'saveDocument':saveDocument,
'loadDocument':loadDocument,
'removeDocument':removeDocument,
'getDocumentList':getDocumentList};
// creates the good command thanks to his label
if (spec.label && priv.commandlist[spec.label]) {
priv.label = spec.label;
delete spec.label;
return priv.commandlist[priv.label](spec, my);
}
priv.path = spec.path || ''; priv.path = spec.path || '';
priv.tried = 0;
priv.option = spec.option || {}; priv.option = spec.option || {};
priv.respond = priv.option.onResponse || function(){}; priv.respond = priv.option.onResponse || function(){};
priv.done = priv.option.onDone || function(){}; priv.done = priv.option.onDone || function(){};
priv.fail = priv.option.onFail || function(){}; priv.fail = priv.option.onFail || function(){};
priv.retry = function() {
that.setMaxRetry(-1);
that.fail({status:0,statusText:'Fail Retry',
message:'Impossible to retry.'});
};
priv.end = function() {}; priv.end = function() {};
// Methods // // Methods //
...@@ -54,12 +261,21 @@ var command = function(spec, my) { ...@@ -54,12 +261,21 @@ var command = function(spec, my) {
that.validateState(); that.validateState();
}; };
that.getTried = function() {
return priv.tried;
};
that.setMaxRetry = function(max_retry) {
priv.option.max_retry = max_retry;
};
/** /**
* Delegate actual excecution the storage handler. * Delegate actual excecution the storage handler.
* @param {object} handler The storage handler. * @param {object} handler The storage handler.
*/ */
that.execute = function(handler) { that.execute = function(handler) {
that.validate(handler); that.validate(handler);
priv.tried ++;
handler.execute(that); handler.execute(that);
}; };
...@@ -82,22 +298,31 @@ var command = function(spec, my) { ...@@ -82,22 +298,31 @@ var command = function(spec, my) {
}; };
that.done = function(return_value) { that.done = function(return_value) {
console.log ('test'); console.log ('done');
priv.done(return_value); priv.done(return_value);
priv.respond({value:return_value}); priv.respond({status:doneStatus(),value:return_value});
priv.end(); priv.end();
}; };
that.fail = function(return_error) { that.fail = function(return_error) {
priv.fail(return_error); if (priv.option.max_retry === 0 || priv.tried < priv.option.max_retry) {
priv.respond({error:return_error}); priv.retry();
priv.end(); } else {
console.log ('fail');
priv.fail(return_error);
priv.respond({status:failStatus(),error:return_error});
priv.end();
}
}; };
that.onEndDo = function(fun) { that.onEndDo = function(fun) {
priv.end = fun; priv.end = fun;
}; };
that.onRetryDo = function(fun) {
priv.retry = fun;
};
/** /**
* Returns a serialized version of this command. * Returns a serialized version of this command.
* Override this function. * Override this function.
...@@ -106,6 +331,8 @@ var command = function(spec, my) { ...@@ -106,6 +331,8 @@ var command = function(spec, my) {
*/ */
that.serialized = function() { that.serialized = function() {
return {label:that.getLabel(), return {label:that.getLabel(),
tried:priv.tried,
max_retry:priv.max_retry,
path:priv.path, path:priv.path,
option:priv.option}; option:priv.option};
}; };
...@@ -119,7 +346,7 @@ var getDocumentList = function(spec, my) { ...@@ -119,7 +346,7 @@ var getDocumentList = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'getDocumentList'; return 'getDocumentList';
}; };
...@@ -136,7 +363,7 @@ var loadDocument = function(spec, my) { ...@@ -136,7 +363,7 @@ var loadDocument = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'loadDocument'; return 'loadDocument';
}; };
...@@ -153,7 +380,7 @@ var removeDocument = function(spec, my) { ...@@ -153,7 +380,7 @@ var removeDocument = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'removeDocument'; return 'removeDocument';
}; };
...@@ -171,7 +398,7 @@ var saveDocument = function(spec, my) { ...@@ -171,7 +398,7 @@ var saveDocument = function(spec, my) {
// Attributes // // Attributes //
var content = spec.content; var content = spec.content;
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'saveDocument'; return 'saveDocument';
}; };
...@@ -186,80 +413,15 @@ var saveDocument = function(spec, my) { ...@@ -186,80 +413,15 @@ var saveDocument = function(spec, my) {
var super_validate = that.validate; var super_validate = that.validate;
that.validate = function(handler) { that.validate = function(handler) {
if (typeof content !== 'string') { if (typeof content !== 'string') {
throw invalidCommandState({command:that,message:'No data to save'}); throw invalidCommandState({command:that,message:'No data to save'});
} }
super_validate(handler); super_validate(handler);
}; };
that.executeOn = function(storage) {
storage.saveDocument(that);
};
return that;
};
var jioException = function(spec, my) {
var that = {};
spec = spec || {};
my = my || {};
that.name = 'jioException';
that.message = spec.message || 'Unknown Reason.';
that.toString = function() {
return that.name + ': ' + that.message;
};
return that;
};
var invalidCommandState = function(spec, my) {
var that = jioException(spec, my);
spec = spec || {};
var command = spec.command;
that.name = 'invalidCommandState';
that.toString = function() {
return that.name +': ' +
command.getLabel() + ', ' + that.message;
};
return that;
};
var invalidStorage = function(spec, my) {
var that = jioException(spec, my);
spec = spec || {};
var type = spec.storage.getType();
that.name = 'invalidStorage';
that.toString = function() {
return that.name +': ' +
'Type "'+type + '", ' + that.message;
};
return that;
};
var invalidStorageType = function(spec, my) {
var that = jioException(spec, my);
var type = spec.type;
that.name = 'invalidStorageType';
that.toString = function() {
return that.name +': ' +
type + ', ' + that.message;
};
return that;
};
var jobNotReadyException = function(spec, my) {
var that = jioException(spec, my);
that.name = 'jobNotReadyException';
return that;
};
var tooMuchTriesJobException = function(spec, my) { that.executeOn = function(storage) {
var that = jioException(spec, my); storage.saveDocument(that);
that.name = 'tooMuchTriesJobException'; };
return that;
};
var invalidJobException = function(spec, my) {
var that = jioException(spec, my);
that.name = 'invalidJobException';
return that; return that;
}; };
...@@ -318,6 +480,7 @@ var failStatus = function(spec, my) { ...@@ -318,6 +480,7 @@ var failStatus = function(spec, my) {
}; };
return that; return that;
}; };
var initialStatus = function(spec, my) { var initialStatus = function(spec, my) {
var that = jobStatus(spec, my); var that = jobStatus(spec, my);
spec = spec || {}; spec = spec || {};
...@@ -359,215 +522,68 @@ var waitStatus = function(spec, my) { ...@@ -359,215 +522,68 @@ var waitStatus = function(spec, my) {
spec = spec || {}; spec = spec || {};
my = my || {}; my = my || {};
// Attributes // // Attributes //
var job_id_a = spec.job_id_array || []; var priv = {};
var threshold = 0; priv.job_id_a = spec.job_id_array || [];
priv.threshold = 0;
// Methods // // Methods //
that.getLabel = function() { that.getLabel = function() {
return 'wait'; return 'wait';
}; };
priv.refreshJobIdArray = function() {
var tmp_job_id_a = [], i;
for (i = 0; i < priv.job_id_a.length; i+= 1) {
if (jobManager.jobIdExists(priv.job_id_a[i])) {
tmp_job_id_a.push(priv.job_id_a[i]);
}
}
priv.job_id_a = tmp_job_id_a;
};
that.waitForJob = function(job) { that.waitForJob = function(job) {
var i; var i;
for (i = 0; i < job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_a.length; i+= 1) {
if (job_id_a[i] === job.getId()) { if (priv.job_id_a[i] === job.getId()) {
return; return;
} }
} }
job_id_a.push(job.getId()); priv.job_id_a.push(job.getId());
}; };
that.dontWaitForJob = function(job) { that.dontWaitForJob = function(job) {
var i, tmp_job_id_a = []; var i, tmp_job_id_a = [];
for (i = 0; i < job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_a.length; i+= 1) {
if (job_id_a[i] !== job.getId()){ if (priv.job_id_a[i] !== job.getId()){
tmp_job_id_a.push(job_id_a[i]); tmp_job_id_a.push(priv.job_id_a[i]);
} }
} }
job_id_a = tmp_job_id_a; priv.job_id_a = tmp_job_id_a;
}; };
that.waitForTime = function(ms) { that.waitForTime = function(ms) {
threshold = Date.now() + ms; priv.threshold = Date.now() + ms;
}; };
that.stopWaitForTime = function() { that.stopWaitForTime = function() {
threshold = 0; priv.threshold = 0;
}; };
that.canStart = function() { that.canStart = function() {
return (job_id_a.length === 0 && Date.now() >= threshold); priv.refreshJobIdArray();
console.log (priv.job_id_a);
return (priv.job_id_a.length === 0 && Date.now() >= priv.threshold);
}; };
that.canRestart = function() { that.canRestart = function() {
return false; return that.canStart();
}; };
that.serialized = function() { that.serialized = function() {
return {label:that.getLabel(), return {label:that.getLabel(),
waitfortime:threshold, waitfortime:priv.threshold,
waitforjob:job_id_a}; waitforjob:priv.job_id_a};
};
return that;
};
var storage = function(spec, my) {
var that = {};
spec = spec || {};
my = my || {};
// Attributes //
var priv = {};
priv.type = spec.type || '';
// my.jio exists
// Methods //
that.getType = function() {
return priv.type;
};
/**
* Execute the command on this storage.
* @method execute
* @param {object} command The command
*/
that.execute = function(command) {
command.executeOn(that);
};
/**
* Override this function to validate specifications.
* @method isValid
* @return {boolean} true if ok, else false.
*/
that.isValid = function() {
return true;
};
that.validate = function(command) {
command.validate(that);
};
/**
* Returns a serialized version of this storage.
* @method serialized
* @return {object} The serialized storage.
*/
that.serialized = function() {
return {type:that.getType()};
};
that.saveDocument = function(command) {
throw invalidStorage({storage:that,message:'Unknown storage.'});
};
that.loadDocument = function(command) {
that.saveDocument();
};
that.removeDocument = function(command) {
that.saveDocument();
};
that.getDocumentList = function(command) {
that.saveDocument();
};
return that;
};
var storageHandler = function(spec, my) {
var that = storage(spec, my);
spec = spec || {};
my = my || {};
// Attributes //
var priv = {};
priv.storage_a = spec.storagelist || [];
// Methods //
/**
* It is called before the execution.
* Override this function.
* @method beforeExecute
* @param {object} command The command.
* @param {object} option Some options.
*/
that.beforeExecute = function(command,option) {};
/**
* Execute the command according to this storage.
* @method execute
* @param {object} command The command.
* @param {object} option Some options.
*/
that.execute = function(command,option) {
var i;
that.validate(command);
that.beforeExecute(command,option);
for(i = 0; i < priv.storage_a.length; i++) {
priv.storage_a[i].execute(command);
}
that.afterExecute(command,option);
};
/**
* Is is called after the execution.
* Override this function.
* @method afterExecute
* @param {object} command The command.
* @param {object} option Some options.
*/
that.afterExecute = function(command,option) {
that.done();
};
/**
* Returns a serialized version of this storage
* @method serialized
* @return {object} The serialized storage.
*/
that.serialized = function() {
return {type:priv.type,
storagelist:priv.storagelist};
}; };
return that; return that;
}; };
var activityUpdater = (function(spec, my) {
var that = {};
spec = spec || {};
my = my || {};
// Attributes //
var priv = {};
priv.id = spec.id || 0;
priv.interval = 400;
priv.interval_id = null;
// Methods //
priv.touch = function() {
LocalOrCookieStorage.setItem ('jio/id/'+priv.id, Date.now());
};
that.setId = function(id) {
priv.id = id;
};
that.setIntervalDelay = function(ms) {
priv.interval = ms;
};
that.getIntervalDelay = function() {
return priv.interval;
};
that.start = function() {
if (!priv.interval_id) {
priv.touch();
priv.interval_id = setInterval(function() {
priv.touch();
}, priv.interval);
}
};
that.stop = function() {
if (priv.interval_id !== null) {
clearInterval(priv.interval_id);
priv.interval_id = null;
}
};
return that;
}());
var jio = function(spec, my) {
var job = function(spec, my) { var job = function(spec, my) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
...@@ -578,8 +594,6 @@ var job = function(spec, my) { ...@@ -578,8 +594,6 @@ var job = function(spec, my) {
priv.command = spec.command; priv.command = spec.command;
priv.storage = spec.storage; priv.storage = spec.storage;
priv.status = initialStatus(); priv.status = initialStatus();
priv.tried = 0;
priv.max_retry = 0;
priv.date = new Date(); priv.date = new Date();
// Initialize // // Initialize //
...@@ -613,6 +627,10 @@ var job = function(spec, my) { ...@@ -613,6 +627,10 @@ var job = function(spec, my) {
return priv.storage; return priv.storage;
}; };
that.getDate = function() {
return priv.date;
};
/** /**
* Checks if the job is ready. * Checks if the job is ready.
* @method isReady * @method isReady
...@@ -634,8 +652,6 @@ var job = function(spec, my) { ...@@ -634,8 +652,6 @@ var job = function(spec, my) {
that.serialized = function() { that.serialized = function() {
return {id:priv.id, return {id:priv.id,
date:priv.date.getTime(), date:priv.date.getTime(),
tried:priv.tried,
max_retry:priv.max_retry,
status:priv.status.serialized(), status:priv.status.serialized(),
command:priv.command.serialized(), command:priv.command.serialized(),
storage:priv.storage.serialized()}; storage:priv.storage.serialized()};
...@@ -692,7 +708,13 @@ var job = function(spec, my) { ...@@ -692,7 +708,13 @@ 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) {
console.log ('updating');
priv.command.setMaxRetry(-1);
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.status = job.getStatus();
}; };
that.execute = function() { that.execute = function() {
...@@ -704,7 +726,14 @@ var job = function(spec, my) { ...@@ -704,7 +726,14 @@ var job = function(spec, my) {
throw jobNotReadyException({message:'Can not execute this job.'}); throw jobNotReadyException({message:'Can not execute this job.'});
} }
priv.status = onGoingStatus(); priv.status = onGoingStatus();
priv.tried ++; priv.command.onRetryDo (function() {
var ms = priv.command.getTried();
ms = ms*ms*200;
if (ms>10000){
ms = 10000;
}
that.waitForTime(ms);
});
priv.command.onEndDo (function() { priv.command.onEndDo (function() {
jobManager.terminateJob (that); jobManager.terminateJob (that);
}); });
...@@ -754,6 +783,44 @@ var announcement = function(spec, my) { ...@@ -754,6 +783,44 @@ var announcement = function(spec, my) {
return that; return that;
}; };
var activityUpdater = (function(spec, my) {
var that = {};
spec = spec || {};
my = my || {};
// Attributes //
var priv = {};
priv.id = spec.id || 0;
priv.interval = 400;
priv.interval_id = null;
// Methods //
priv.touch = function() {
LocalOrCookieStorage.setItem ('jio/id/'+priv.id, Date.now());
};
that.setId = function(id) {
priv.id = id;
};
that.setIntervalDelay = function(ms) {
priv.interval = ms;
};
that.getIntervalDelay = function() {
return priv.interval;
};
that.start = function() {
if (!priv.interval_id) {
priv.touch();
priv.interval_id = setInterval(function() {
priv.touch();
}, priv.interval);
}
};
that.stop = function() {
if (priv.interval_id !== null) {
clearInterval(priv.interval_id);
priv.interval_id = null;
}
};
return that;
}());
var announcer = (function(spec, my) { var announcer = (function(spec, my) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
...@@ -859,6 +926,7 @@ var jobManager = (function(spec, my) { ...@@ -859,6 +926,7 @@ var jobManager = (function(spec, my) {
var i; var i;
if (priv.interval_id === null) { if (priv.interval_id === null) {
priv.interval_id = setInterval (function() { priv.interval_id = setInterval (function() {
priv.restoreOldJio();
for (i = 0; i < priv.job_a.length; i+= 1) { for (i = 0; i < priv.job_a.length; i+= 1) {
that.execute(priv.job_a[i]); that.execute(priv.job_a[i]);
} }
...@@ -880,6 +948,47 @@ var jobManager = (function(spec, my) { ...@@ -880,6 +948,47 @@ var jobManager = (function(spec, my) {
} }
}; };
priv.restoreOldJio = function() {
var i, jio_id_a;
priv.lastrestore = priv.lastrestore || 0;
if (priv.lastrestore > (Date.now()) - 2000) { return; }
jio_id_a = LocalOrCookieStorage.getItem('jio/id_array')||[];
for (i = 0; i < jio_id_a.length; i+= 1) {
priv.restoreOldJioId(jio_id_a[i]);
}
priv.lastrestore = Date.now();
};
priv.restoreOldJioId = function(id) {
var jio_date;
jio_date = LocalOrCookieStorage.getItem('jio/id/'+id)||0;
if (jio_date < Date.now() - 10000) {
priv.restoreOldJobFromJioId(id);
priv.removeOldJioId(id);
}
};
priv.restoreOldJobFromJioId = function(id) {
var i, jio_job_array;
jio_job_array = LocalOrCookieStorage.getItem('jio/job_array/'+id)||[];
for (i = 0; i < jio_job_array.length; i+= 1) {
that.addJob ( job(
{storage:jioNamespace.storage(jio_job_array[i]),
command:command(jio_job_array[i].command)}));
}
};
priv.removeOldJioId = function(id) {
var i, jio_id_a, new_a = [];
jio_id_a = LocalOrCookieStorage.getItem('jio/id_array')||[];
for (i = 0; i < jio_id_a.length; i+= 1) {
if (jio_id_a[i] !== id) {
new_a.push(jio_id_a[i]);
}
}
LocalOrCookieStorage.setItem('jio/id_array',new_a);
};
/** /**
* Executes a job. * Executes a job.
* @method execute * @method execute
...@@ -898,6 +1007,18 @@ var jobManager = (function(spec, my) { ...@@ -898,6 +1007,18 @@ var jobManager = (function(spec, my) {
priv.copyJobArrayToLocal(); priv.copyJobArrayToLocal();
}; };
that.jobIdExists = function(id) {
var i;
for (i = 0; i < priv.job_a.length; i+= 1) {
if (priv.job_a[i].getId() === id) {
console.log ('found');
return true;
}
}
console.log ('not found');
return false;
};
that.terminateJob = function(job) { that.terminateJob = function(job) {
priv.removeJob(job); priv.removeJob(job);
priv.copyJobArrayToLocal(); priv.copyJobArrayToLocal();
...@@ -906,7 +1027,6 @@ var jobManager = (function(spec, my) { ...@@ -906,7 +1027,6 @@ var jobManager = (function(spec, my) {
that.addJob = function(job) { that.addJob = function(job) {
var result_a = that.validateJobAccordingToJobList (priv.job_a,job); var result_a = that.validateJobAccordingToJobList (priv.job_a,job);
priv.manage (job,result_a); priv.manage (job,result_a);
priv.copyJobArrayToLocal();
}; };
that.validateJobAccordingToJobList = function(job_a,job) { that.validateJobAccordingToJobList = function(job_a,job) {
...@@ -927,16 +1047,19 @@ var jobManager = (function(spec, my) { ...@@ -927,16 +1047,19 @@ var jobManager = (function(spec, my) {
return; return;
} }
} }
console.log ('managing '+JSON.stringify (result_a));
for (i = 0; i < result_a.length; i+= 1) { for (i = 0; i < result_a.length; i+= 1) {
switch (result_a[i].action) { switch (result_a[i].action) {
case 'eliminate': case 'eliminate':
console.log ('eliminating');
that.eliminate(result_a[i].job); that.eliminate(result_a[i].job);
break; break;
case 'replace': case 'update':
job.update(result_a[i].job); result_a[i].job.update(job);
priv.copyJobArrayToLocal(); priv.copyJobArrayToLocal();
return; return;
case 'wait': case 'wait':
console.log ('wait');
job.waitForJob(result_a[i].job); job.waitForJob(result_a[i].job);
break; break;
default: break; default: break;
...@@ -951,13 +1074,16 @@ var jobManager = (function(spec, my) { ...@@ -951,13 +1074,16 @@ var jobManager = (function(spec, my) {
for (i = 0; i < priv.job_a.length; i+= 1) { for (i = 0; i < priv.job_a.length; i+= 1) {
if (priv.job_a[i].getId() !== job.getId()) { if (priv.job_a[i].getId() !== job.getId()) {
tmp_a.push(priv.job_a[i]); tmp_a.push(priv.job_a[i]);
console.log ('add: '+priv.job_a[i].getId()+' -> it is not '+job.getId());
} }
} }
priv.job_a = tmp_a; priv.job_a = tmp_a;
priv.copyJobArrayToLocal();
}; };
return that; return that;
}()); }());
var jobRules = (function(spec, my) { var jobRules = (function(spec, my) {
var that = {}; var that = {};
// Attributes // // Attributes //
...@@ -972,8 +1098,8 @@ var jobRules = (function(spec, my) { ...@@ -972,8 +1098,8 @@ var jobRules = (function(spec, my) {
}; };
priv.default_compare = function(job1,job2) { priv.default_compare = function(job1,job2) {
return (job1.getCommand().getPath() === job2.getCommand().getPath() && return (job1.getCommand().getPath() === job2.getCommand().getPath() &&
JSON.stringify(job1.getStorage()) === JSON.stringify(job1.getStorage().serialized()) ===
JSON.stringify(job2.getStorage())); JSON.stringify(job2.getStorage().serialized()));
}; };
priv.action = { priv.action = {
/* /*
...@@ -1090,7 +1216,7 @@ var jobRules = (function(spec, my) { ...@@ -1090,7 +1216,7 @@ var jobRules = (function(spec, my) {
} }
} }
}; };
priv.default_action = 'none'; priv.default_action = that.none;
// Methods // // Methods //
priv.getAction = function(job1,job2) { priv.getAction = function(job1,job2) {
var j1label, j2label, j1status; var j1label, j2label, j1status;
...@@ -1099,24 +1225,36 @@ var jobRules = (function(spec, my) { ...@@ -1099,24 +1225,36 @@ var jobRules = (function(spec, my) {
j1status = (job1.getStatus().getLabel()==='on going'? j1status = (job1.getStatus().getLabel()==='on going'?
'on going':'not on going'); 'on going':'not on going');
try { try {
console.log (j1label);
console.log (j2label);
console.log (j1status);
return priv.action[j1label][j1status][j2label](job1,job2); return priv.action[j1label][j1status][j2label](job1,job2);
} catch (e) { } catch (e) {
return priv.default_action; if(e.name==='TypeError') {
return priv.default_action(job1,job2);
} else {
throw e;
}
} }
}; };
priv.canCompare = function(job1,job2) { priv.canCompare = function(job1,job2) {
var key = priv.stringifyJobForCompare(job1,job2); var job1label = job1.getCommand().getLabel(),
if (priv.compare[key]) { job2label = job2.getCommand().getLabel();
return priv.compare[key](job1,job2); try {
return priv.compare[job1label][job2label](job1,job2);
} catch(e) {
if (e.name==='TypeError') {
return priv.default_compare(job1,job2);
} else {
throw e;
}
} }
return priv.default_compare(job1,job2);
}; };
that.validateJobAccordingToJob = function(job1,job2) { that.validateJobAccordingToJob = function(job1,job2) {
var key = priv.stringifyJobForAction(job1,job2);
if (priv.canCompare(job1,job2)) { if (priv.canCompare(job1,job2)) {
return {action:priv.getAction(job1,job2),job:job1}; return {action:priv.getAction(job1,job2),job:job1};
} }
return {action:priv.default_action,job:job1}; return {action:priv.default_action(job1,job2),job:job1};
}; };
return that; return that;
...@@ -1199,7 +1337,6 @@ var jobRules = (function(spec, my) { ...@@ -1199,7 +1337,6 @@ var jobRules = (function(spec, my) {
option.onDone = option.onDone || function(){}; option.onDone = option.onDone || function(){};
option.onFail = option.onFail || function(){}; option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
console.log ('add job save: ' + JSON.stringify (priv.storage.serialized()));
jobManager.addJob( jobManager.addJob(
job({storage:(specificstorage? job({storage:(specificstorage?
jioNamespace.storage(specificstorage): jioNamespace.storage(specificstorage):
...@@ -1315,9 +1452,9 @@ var jioNamespace = (function(spec, my) { ...@@ -1315,9 +1452,9 @@ var jioNamespace = (function(spec, my) {
spec = spec || {}; spec = spec || {};
var type = spec.type || 'base'; var type = spec.type || 'base';
if (!storage_type_o[type]) { if (!storage_type_o[type]) {
throw invalidStorageType({type:type}); throw invalidStorageType({type:type,
message:'Storage does not exists.'});
} }
console.log ('create storage: ' + JSON.stringify (spec) + JSON.stringify (my));
return storage_type_o[type](spec, my); return storage_type_o[type](spec, my);
}; };
...@@ -1337,7 +1474,6 @@ var jioNamespace = (function(spec, my) { ...@@ -1337,7 +1474,6 @@ var jioNamespace = (function(spec, my) {
storage = JSON.parse (storage); storage = JSON.parse (storage);
} }
storage = storage || {type:'base'}; storage = storage || {type:'base'};
console.log ('new jio: storage: ' + JSON.stringify (spec));
return jio(spec); return jio(spec);
}; };
...@@ -1353,7 +1489,6 @@ var jioNamespace = (function(spec, my) { ...@@ -1353,7 +1489,6 @@ var jioNamespace = (function(spec, my) {
throw invalidStorageType({type:type,message:'Already known.'}); throw invalidStorageType({type:type,message:'Already known.'});
} }
storage_type_o[type] = constructor; storage_type_o[type] = constructor;
console.log ('adding: '+type);
}; };
return that; return that;
......
/*! JIO - v0.1.0 - 2012-06-11 /*! JIO - v0.1.0 - 2012-06-12
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var jio=function(){var a=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.path=a.path||"",d.option=a.option||{},d.respond=d.option.onResponse||function(){},d.done=d.option.onDone||function(){},d.fail=d.option.onFail||function(){},d.end=function(){},c.getLabel=function(){return"command"},c.getPath=function(){return d.path},c.getOption=function(a){return d.option[a]},c.validate=function(a){c.validateState()},c.execute=function(a){c.validate(a),a.execute(c)},c.executeOn=function(a){},c.validateState=function(){if(d.path==="")throw g({command:c,message:"Path is empty"})},c.done=function(a){console.log("test"),d.done(a),d.respond({value:a}),d.end()},c.fail=function(a){d.fail(a),d.respond({error:a}),d.end()},c.onEndDo=function(a){d.end=a},c.serialized=function(){return{label:c.getLabel(),path:d.path,option:d.option}},c},b=function(b,c){var d=a(b,c);return b=b||{},c=c||{},d.label=function(){return"getDocumentList"},d.executeOn=function(a){a.getDocumentList(d)},d},c=function(b,c){var d=a(b,c);return b=b||{},c=c||{},d.label=function(){return"loadDocument"},d.executeOn=function(a){a.loadDocument(d)},d},d=function(b,c){var d=a(b,c);return b=b||{},c=c||{},d.label=function(){return"removeDocument"},d.executeOn=function(a){a.removeDocument(d)},d},e=function(b,c){var d=a(b,c);b=b||{},c=c||{};var e=b.content;d.label=function(){return"saveDocument"},d.getContent=function(){return e};var f=d.validate;return d.validate=function(a){if(typeof e!="string")throw g({command:d,message:"No data to save"});f(a)},d.executeOn=function(a){a.saveDocument(d)},d},f=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},g=function(a,b){var c=f(a,b);a=a||{};var d=a.command;return c.name="invalidCommandState",c.toString=function(){return c.name+": "+d.getLabel()+", "+c.message},c},h=function(a,b){var c=f(a,b);a=a||{};var d=a.storage.getType();return c.name="invalidStorage",c.toString=function(){return c.name+": "+'Type "'+d+'", '+c.message},c},i=function(a,b){var c=f(a,b),d=a.type;return c.name="invalidStorageType",c.toString=function(){return c.name+": "+d+", "+c.message},c},j=function(a,b){var c=f(a,b);return c.name="jobNotReadyException",c},k=function(a,b){var c=f(a,b);return c.name="tooMuchTriesJobException",c},l=function(a,b){var c=f(a,b);return c.name="invalidJobException",c},m=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},n=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"done"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},o=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"fail"},c.canStart=function(){return!1},c.canRestart=function(){return!0},c},p=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"initial"},c.canStart=function(){return!0},c.canRestart=function(){return!0},c},q=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"on going"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},r=function(a,b){var c=m(a,b);a=a||{},b=b||{};var d=a.job_id_array||[],e=0;return c.getLabel=function(){return"wait"},c.waitForJob=function(a){var b;for(b=0;b<d.length;b+=1)if(d[b]===a.getId())return;d.push(a.getId())},c.dontWaitForJob=function(a){var b,c=[];for(b=0;b<d.length;b+=1)d[b]!==a.getId()&&c.push(d[b]);d=c},c.waitForTime=function(a){e=Date.now()+a},c.stopWaitForTime=function(){e=0},c.canStart=function(){return d.length===0&&Date.now()>=e},c.canRestart=function(){return!1},c.serialized=function(){return{label:c.getLabel(),waitfortime:e,waitforjob:d}},c},s=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.type=a.type||"",c.getType=function(){return d.type},c.execute=function(a){a.executeOn(c)},c.isValid=function(){return!0},c.validate=function(a){a.validate(c)},c.serialized=function(){return{type:c.getType()}},c.saveDocument=function(a){throw h({storage:c,message:"Unknown storage."})},c.loadDocument=function(a){c.saveDocument()},c.removeDocument=function(a){c.saveDocument()},c.getDocumentList=function(a){c.saveDocument()},c},t=function(a,b){var c=s(a,b);a=a||{},b=b||{};var d={};return d.storage_a=a.storagelist||[],c.beforeExecute=function(a,b){},c.execute=function(a,b){var e;c.validate(a),c.beforeExecute(a,b);for(e=0;e<d.storage_a.length;e++)d.storage_a[e].execute(a);c.afterExecute(a,b)},c.afterExecute=function(a,b){c.done()},c.serialized=function(){return{type:d.type,storagelist:d.storagelist}},c},u=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}(),v=function(a,f){var g=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.id=m.nextId(),d.command=a.command,d.storage=a.storage,d.status=p(),d.tried=0,d.max_retry=0,d.date=new Date,function(){if(!d.storage)throw l({job:c,message:"No storage set"});if(!d.command)throw l({job:c,message:"No command set"})}(),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.isReady=function(){return d.tried===0?d.status.canStart():d.status.canRestart()},c.serialized=function(){return{id:d.id,date:d.date.getTime(),tried:d.tried,max_retry:d.max_retry,status:d.status.serialized(),command:d.command.serialized(),storage:d.storage.serialized()}},c.waitForJob=function(a){d.status.getLabel()!=="wait"&&(d.status=r()),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=r()),d.status.waitForTime(a)},c.stopWaitForTime=function(){d.status.getLabel()==="wait"&&d.status.stopWaitForTime()},c.update=function(a){d.date=a.getDate()},c.execute=function(){if(d.max_retry!==0&&d.tried>=d.max_retry)throw k({job:c,message:"The job was invoked too much time."});if(!c.isReady())throw j({message:"Can not execute this job."});d.status=q(),d.tried++,d.command.onEndDo(function(){n.terminateJob(c)}),d.command.execute(d.storage)},c},h=function(a,b){var c={};a=a||{},b=b||{};var d=[],e=a.name||"";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(){i.register(c)},c.unregister=function(){i.unregister(c)},c.trigger=function(a){var b;for(b=0;b<d.length;b++)d[b].apply(null,a)},c},i=function(a,b){var c={};a=a||{},b=b||{};var d={};return c.register=function(a){d[a]||(d[a]=h())},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}(),m=function(a,b){var c={};a=a||{},b=b||{};var d=0;return c.nextId=function(){return d=d+1,d},c}(),n=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_a=[],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_a.length;b+=1)a.push(e.job_a[b].serialized());LocalOrCookieStorage.setItem(e.getJobArrayName(),a)},e.removeJob=function(a){var b,c=[];for(b=0;b<e.job_a.length;b+=1)e.job_a[b]!==a&&c.push(e.job_a[b]);e.job_a=c,e.copyJobArrayToLocal()},c.setId=function(a){e.id=a},c.start=function(){var a;e.interval_id===null&&(e.interval_id=setInterval(function(){for(a=0;a<e.job_a.length;a+=1)c.execute(e.job_a[a])},e.interval))},c.stop=function(){e.interval_id!==null&&(clearInterval(e.interval_id),e.interval_id=null,e.job_a.length===0&&LocalOrCookieStorage.deleteItem(e.getJobArrayName()))},c.execute=function(a){try{a.execute()}catch(b){switch(b.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw b}}e.copyJobArrayToLocal()},c.terminateJob=function(a){e.removeJob(a),e.copyJobArrayToLocal()},c.addJob=function(a){var b=c.validateJobAccordingToJobList(e.job_a,a);e.manage(a,b),e.copyJobArrayToLocal()},c.validateJobAccordingToJobList=function(a,b){var c,d=[];for(c=0;c<a.length;c+=1)d.push(o.validateJobAccordingToJob(a[c],b));return d},e.manage=function(a,b){var d;if(e.job_a.length!==b.length)throw new RangeError("Array out of bound");for(d=0;d<b.length;d+=1)if(b[d].action==="dont accept")return;for(d=0;d<b.length;d+=1)switch(b[d].action){case"eliminate":c.eliminate(b[d].job);break;case"replace":a.update(b[d].job),e.copyJobArrayToLocal();return;case"wait":a.waitForJob(b[d].job);break;default:}e.job_a.push(a),e.copyJobArrayToLocal()},c.eliminate=function(a){var b,c=[];for(b=0;b<e.job_a.length;b+=1)e.job_a[b].getId()!==a.getId()&&c.push(e.job_a[b]);e.job_a=c},c}(),o=function(a,b){var c={},d={};return 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"},d.compare={},d.default_compare=function(a,b){return a.getCommand().getPath()===b.getCommand().getPath()&&JSON.stringify(a.getStorage())===JSON.stringify(b.getStorage())},d.action={saveDocument:{"on going":{saveDocument:function(a,b){return a.getCommand().getContent()===b.getCommand().getContent()?c.dontAccept():c.wait()},loadDocument:c.wait,removeDocument:c.wait,getDocumentList:c.none},"not on going":{saveDocument:c.update,loadDocument:c.wait,removeDocument:c.eliminate,getDocumentList:c.none}},loadDocument:{"on going":{saveDocument:c.wait,loadDocument:c.dontAccept,removeDocument:c.wait,getDocumentList:c.none},"not on going":{saveDocument:c.wait,loadDocument:c.update,removeDocument:c.wait,getDocumentList:c.none}},removeDocument:{"on going":{saveDocument:c.wait,loadDocument:c.dontAccept,removeDocument:c.dontAccept,getDocumentList:c.none},"not on going":{saveDocument:c.eliminate,loadDocument:c.dontAccept,removeDocument:c.update,getDocumentList:c.none}},getDocumentList:{"on going":{saveDocument:c.none,loadDocument:c.none,removeDocument:c.none,getDocumentList:c.dontAccept},"not on going":{saveDocument:c.none,loadDocument:c.none,removeDocument:c.none,getDocumentList:c.update}}},d.default_action="none",d.getAction=function(a,b){var c,e,f;c=a.getCommand().getLabel(),e=b.getCommand().getLabel(),f=a.getStatus().getLabel()==="on going"?"on going":"not on going";try{return d.action[c][f][e](a,b)}catch(g){return d.default_action}},d.canCompare=function(a,b){var c=d.stringifyJobForCompare(a,b);return d.compare[c]?d.compare[c](a,b):d.default_compare(a,b)},c.validateJobAccordingToJob=function(a,b){var c=d.stringifyJobForAction(a,b);return d.canCompare(a,b)?{action:d.getAction(a,b),job:a}:{action:d.default_action,job:a}},c}(),s={};a=a||{},f=f||{};var t={},v="jio/id_array";return t.id=1,t.storage=w.storage(a,s),function(){var a,b=LocalOrCookieStorage.getItem(v)||[];for(a=0;a<b.length;a+=1)b[a]>=t.id&&(t.id=b[a]+1);b.push(t.id),LocalOrCookieStorage.setItem(v,b)}(),function(){u.setId(t.id),u.start(),n.setId(t.id),n.start()}(),s.start=function(){n.start()},s.stop=function(){n.stop()},s.getId=function(){return t.id},s.validateStorageDescription=function(a){return w.storage(a.type)(a).isValid()},s.saveDocument=function(a,b,c,d){c=c||{},c.onResponse=c.onResponse||function(){},c.onDone=c.onDone||function(){},c.onFail=c.onFail||function(){},c.max_retry=c.max_retry||0,console.log("add job save: "+JSON.stringify(t.storage.serialized())),n.addJob(g({storage:d?w.storage(d):t.storage,command:e({path:a,content:b,option:c})}))},s.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,n.addJob(g({storage:d?w.storage(d):t.storage,command:c({path:a,option:b})}))},s.removeDocument=function(a,b,c){b=b||{},b.onResponse=b.onResponse||function(){},b.onDone=b.onDone||function(){},b.onFail=b.onFail||function(){},b.max_retry=b.max_retry||0,n.addJob(g({storage:c?w.storage(c):t.storage,command:d({path:a,option:b})}))},s.getDocumentList=function(a,c,d){c=c||{},c.onResponse=c.onResponse||function(){},c.onDone=c.onDone||function(){},c.onFail=c.onFail||function(){},c.max_retry=c.max_retry||0,c.metadata_only=c.metadata_only!==undefined?c.metadata_only:!0,n.addJob(g({storage:d?w.storage(d):t.storage,command:b({path:a,option:c})}))},s},w=function(a,b){var c={};a=a||{},b=b||{};var d={base:s,handler:t};return c.storage=function(a,b){a=a||{};var c=a.type||"base";if(!d[c])throw i({type:c});return console.log("create storage: "+JSON.stringify(a)+JSON.stringify(b)),d[c](a,b)},c.newJio=function(a){var b=a;return typeof b=="string"&&(b=JSON.parse(b)),b=b||{type:"base"},console.log("new jio: storage: "+JSON.stringify(a)),v(a)},c.addStorageType=function(a,b){b=b||function(){return null};if(d[a])throw i({type:a,message:"Already known."});d[a]=b,console.log("adding: "+a)},c}();return w}(); 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){a.executeOn(d)},d.isValid=function(){return!0},d.validate=function(a){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},i=function(a,b){var c=h(a,b);a=a||{},b=b||{};var d={};return d.storage_a=a.storagelist||[],c.beforeExecute=function(a,b){},c.execute=function(a,b){var e;c.validate(a),c.beforeExecute(a,b);for(e=0;e<d.storage_a.length;e++)d.storage_a[e].execute(a);c.afterExecute(a,b)},c.afterExecute=function(a,b){c.done()},c.serialized=function(){return{type:d.type,storagelist:d.storagelist}},c},j=function(a,c){var d=function(a,c){var d={};a=a||{},c=c||{};var e={};return e.commandlist={saveDocument:l,loadDocument:i,removeDocument:j,getDocumentList:h},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.respond=e.option.onResponse||function(){},e.done=e.option.onDone||function(){},e.fail=e.option.onFail||function(){},e.retry=function(){d.setMaxRetry(-1),d.fail({status:0,statusText:"Fail Retry",message:"Impossible to retry."})},e.end=function(){},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.getTried=function(){return e.tried},d.setMaxRetry=function(a){e.option.max_retry=a},d.execute=function(a){d.validate(a),e.tried++,a.execute(d)},d.executeOn=function(a){},d.validateState=function(){if(e.path==="")throw b({command:d,message:"Path is empty"})},d.done=function(a){console.log("done"),e.done(a),e.respond({status:n(),value:a}),e.end()},d.fail=function(a){e.option.max_retry===0||e.tried<e.option.max_retry?e.retry():(console.log("fail"),e.fail(a),e.respond({status:o(),error:a}),e.end())},d.onEndDo=function(a){e.end=a},d.onRetryDo=function(a){e.retry=a},d.serialized=function(){return{label:d.getLabel(),tried:e.tried,max_retry:e.max_retry,path:e.path,option:e.option}},d)},h=function(a,b){var c=d(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"getDocumentList"},c.executeOn=function(a){a.getDocumentList(c)},c},i=function(a,b){var c=d(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"loadDocument"},c.executeOn=function(a){a.loadDocument(c)},c},j=function(a,b){var c=d(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"removeDocument"},c.executeOn=function(a){a.removeDocument(c)},c},l=function(a,c){var e=d(a,c);a=a||{},c=c||{};var f=a.content;e.getLabel=function(){return"saveDocument"},e.getContent=function(){return f};var g=e.validate;return e.validate=function(a){if(typeof f!="string")throw b({command:e,message:"No data to save"});g(a)},e.executeOn=function(a){a.saveDocument(e)},e},m=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},n=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"done"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},o=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"fail"},c.canStart=function(){return!1},c.canRestart=function(){return!0},c},p=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"initial"},c.canStart=function(){return!0},c.canRestart=function(){return!0},c},q=function(a,b){var c=m(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"on going"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},r=function(a,b){var c=m(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=[],b;for(b=0;b<d.job_id_a.length;b+=1)x.jobIdExists(d.job_id_a[b])&&a.push(d.job_id_a[b]);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(),console.log(d.job_id_a),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},s=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.id=w.nextId(),d.command=a.command,d.storage=a.storage,d.status=p(),d.date=new Date,function(){if(!d.storage)throw g({job:c,message:"No storage set"});if(!d.command)throw g({job:c,message:"No command set"})}(),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 d.tried===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=r()),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=r()),d.status.waitForTime(a)},c.stopWaitForTime=function(){d.status.getLabel()==="wait"&&d.status.stopWaitForTime()},c.update=function(a){console.log("updating"),d.command.setMaxRetry(-1),d.command.fail({status:0,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(d.max_retry!==0&&d.tried>=d.max_retry)throw f({job:c,message:"The job was invoked too much time."});if(!c.isReady())throw e({message:"Can not execute this job."});d.status=q(),d.command.onRetryDo(function(){var a=d.command.getTried();a=a*a*200,a>1e4&&(a=1e4),c.waitForTime(a)}),d.command.onEndDo(function(){x.terminateJob(c)}),d.command.execute(d.storage)},c},t=function(a,b){var c={};a=a||{},b=b||{};var d=[],e=a.name||"";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(){v.register(c)},c.unregister=function(){v.unregister(c)},c.trigger=function(a){var b;for(b=0;b<d.length;b++)d[b].apply(null,a)},c},u=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}(),v=function(a,b){var c={};a=a||{},b=b||{};var d={};return c.register=function(a){d[a]||(d[a]=t())},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}(),w=function(a,b){var c={};a=a||{},b=b||{};var d=0;return c.nextId=function(){return d=d+1,d},c}(),x=function(a,b){var c={};a=a||{},b=b||{};var e="jio/job_array",f={};return f.id=a.id,f.interval_id=null,f.interval=200,f.job_a=[],f.getJobArrayName=function(){return e+"/"+f.id},f.getJobArray=function(){return LocalOrCookieStorage.getItem(f.getJobArrayName())||[]},f.copyJobArrayToLocal=function(){var a=[],b;for(b=0;b<f.job_a.length;b+=1)a.push(f.job_a[b].serialized());LocalOrCookieStorage.setItem(f.getJobArrayName(),a)},f.removeJob=function(a){var b,c=[];for(b=0;b<f.job_a.length;b+=1)f.job_a[b]!==a&&c.push(f.job_a[b]);f.job_a=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_a.length;a+=1)c.execute(f.job_a[a])},f.interval))},c.stop=function(){f.interval_id!==null&&(clearInterval(f.interval_id),f.interval_id=null,f.job_a.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.restoreOldJobFromJioId=function(a){var b,e;e=LocalOrCookieStorage.getItem("jio/job_array/"+a)||[];for(b=0;b<e.length;b+=1)c.addJob(s({storage:k.storage(e[b]),command:d(e[b].command)}))},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)},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_a.length;b+=1)if(f.job_a[b].getId()===a)return console.log("found"),!0;return console.log("not found"),!1},c.terminateJob=function(a){f.removeJob(a),f.copyJobArrayToLocal()},c.addJob=function(a){var b=c.validateJobAccordingToJobList(f.job_a,a);f.manage(a,b)},c.validateJobAccordingToJobList=function(a,b){var c,d=[];for(c=0;c<a.length;c+=1)d.push(y.validateJobAccordingToJob(a[c],b));return d},f.manage=function(a,b){var d;if(f.job_a.length!==b.length)throw new RangeError("Array out of bound");for(d=0;d<b.length;d+=1)if(b[d].action==="dont accept")return;console.log("managing "+JSON.stringify(b));for(d=0;d<b.length;d+=1)switch(b[d].action){case"eliminate":console.log("eliminating"),c.eliminate(b[d].job);break;case"update":b[d].job.update(a),f.copyJobArrayToLocal();return;case"wait":console.log("wait"),a.waitForJob(b[d].job);break;default:}f.job_a.push(a),f.copyJobArrayToLocal()},c.eliminate=function(a){var b,c=[];for(b=0;b<f.job_a.length;b+=1)f.job_a[b].getId()!==a.getId()&&(c.push(f.job_a[b]),console.log("add: "+f.job_a[b].getId()+" -> it is not "+a.getId()));f.job_a=c,f.copyJobArrayToLocal()},c}(),y=function(a,b){var c={},d={};return 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"},d.compare={},d.default_compare=function(a,b){return a.getCommand().getPath()===b.getCommand().getPath()&&JSON.stringify(a.getStorage().serialized())===JSON.stringify(b.getStorage().serialized())},d.action={saveDocument:{"on going":{saveDocument:function(a,b){return a.getCommand().getContent()===b.getCommand().getContent()?c.dontAccept():c.wait()},loadDocument:c.wait,removeDocument:c.wait,getDocumentList:c.none},"not on going":{saveDocument:c.update,loadDocument:c.wait,removeDocument:c.eliminate,getDocumentList:c.none}},loadDocument:{"on going":{saveDocument:c.wait,loadDocument:c.dontAccept,removeDocument:c.wait,getDocumentList:c.none},"not on going":{saveDocument:c.wait,loadDocument:c.update,removeDocument:c.wait,getDocumentList:c.none}},removeDocument:{"on going":{saveDocument:c.wait,loadDocument:c.dontAccept,removeDocument:c.dontAccept,getDocumentList:c.none},"not on going":{saveDocument:c.eliminate,loadDocument:c.dontAccept,removeDocument:c.update,getDocumentList:c.none}},getDocumentList:{"on going":{saveDocument:c.none,loadDocument:c.none,removeDocument:c.none,getDocumentList:c.dontAccept},"not on going":{saveDocument:c.none,loadDocument:c.none,removeDocument:c.none,getDocumentList:c.update}}},d.default_action=c.none,d.getAction=function(a,b){var c,e,f;c=a.getCommand().getLabel(),e=b.getCommand().getLabel(),f=a.getStatus().getLabel()==="on going"?"on going":"not on going";try{return console.log(c),console.log(e),console.log(f),d.action[c][f][e](a,b)}catch(g){if(g.name==="TypeError")return d.default_action(a,b);throw g}},d.canCompare=function(a,b){var c=a.getCommand().getLabel(),e=b.getCommand().getLabel();try{return d.compare[c][e](a,b)}catch(f){if(f.name==="TypeError")return d.default_compare(a,b);throw f}},c.validateJobAccordingToJob=function(a,b){return d.canCompare(a,b)?{action:d.getAction(a,b),job:a}:{action:d.default_action(a,b),job:a}},c}(),z={};a=a||{},c=c||{};var A={},B="jio/id_array";return A.id=1,A.storage=k.storage(a,z),function(){var a,b=LocalOrCookieStorage.getItem(B)||[];for(a=0;a<b.length;a+=1)b[a]>=A.id&&(A.id=b[a]+1);b.push(A.id),LocalOrCookieStorage.setItem(B,b)}(),function(){u.setId(A.id),u.start(),x.setId(A.id),x.start()}(),z.start=function(){x.start()},z.stop=function(){x.stop()},z.getId=function(){return A.id},z.validateStorageDescription=function(a){return k.storage(a.type)(a).isValid()},z.saveDocument=function(a,b,c,d){c=c||{},c.onResponse=c.onResponse||function(){},c.onDone=c.onDone||function(){},c.onFail=c.onFail||function(){},c.max_retry=c.max_retry||0,x.addJob(s({storage:d?k.storage(d):A.storage,command:l({path:a,content:b,option:c})}))},z.loadDocument=function(a,b,c){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,x.addJob(s({storage:c?k.storage(c):A.storage,command:i({path:a,option:b})}))},z.removeDocument=function(a,b,c){b=b||{},b.onResponse=b.onResponse||function(){},b.onDone=b.onDone||function(){},b.onFail=b.onFail||function(){},b.max_retry=b.max_retry||0,x.addJob(s({storage:c?k.storage(c):A.storage,command:j({path:a,option:b})}))},z.getDocumentList=function(a,b,c){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,x.addJob(s({storage:c?k.storage(c):A.storage,command:h({path:a,option:b})}))},z},k=function(a,b){var c={};a=a||{},b=b||{};var e={base:h,handler:i};return c.storage=function(a,b){a=a||{};var c=a.type||"base";if(!e[c])throw d({type:c,message:"Storage does not exists."});return e[c](a,b)},c.newJio=function(a){var b=a;return typeof b=="string"&&(b=JSON.parse(b)),b=b||{type:"base"},j(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 k}();
\ No newline at end of file \ No newline at end of file
...@@ -17,37 +17,29 @@ ...@@ -17,37 +17,29 @@
that.saveDocument = function (command) { that.saveDocument = function (command) {
// Tells us that the document is saved. // Tells us that the document is saved.
// wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
command.done(); command.done();
}, 100); }, 100);
}; // end saveDocument }; // end saveDocument
that.loadDocument = function () { that.loadDocument = function (command) {
// Returns a document object containing all information of the // Returns a document object containing all information of the
// document and its content. // document and its content.
// document object is {'name':string,'content':string,
// 'creation_date':date,'last_modified':date}
// wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
var doc = { var doc = {
'name': 'file', 'name': 'file',
'content': 'content', 'content': 'content',
'creation_date': 10000, 'creation_date': 10000,
'last_modified': 15000}; 'last_modified': 15000};
that.done(doc); command.done(doc);
}, 100); }, 100);
}; // end loadDocument }; // end loadDocument
that.getDocumentList = function () { that.getDocumentList = function (command) {
// It returns a document array containing all the user documents // It returns a document array containing all the user documents
// with/but their content. // with/but their content.
// the list is [object,object] -> object = {'name':string,
// 'last_modified':date,'creation_date':date}
setTimeout(function () { setTimeout(function () {
var list = [ var list = [
{'name':'file', {'name':'file',
...@@ -63,216 +55,182 @@ ...@@ -63,216 +55,182 @@
delete list[0].content; delete list[0].content;
delete list[1].content; delete list[1].content;
} }
that.done(list); command.done(list);
}, 100); }, 100);
}; // end getDocumentList }; // end getDocumentList
that.removeDocument = function () { that.removeDocument = function (command) {
// Remove a document from the storage. // Remove a document from the storage.
setTimeout (function () { setTimeout (function () {
that.done(); command.done();
}, 100); }, 100);
}; };
return that; return that;
}; },
// end Dummy Storage All Ok // end Dummy Storage All Ok
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// // Dummy Storage 2 : all fail // Dummy Storage 2 : all fail
// newDummyStorageAllFail = function ( spec, my ) { newDummyStorageAllFail = function ( spec, my ) {
// var that = Jio.newBaseStorage( spec, my ); var that = Jio.storage( {type:'base'}, my );
// that.checkNameAvailability = function () { that.setType('dummyallfail');
// // Fails to check [job.userName].
that.saveDocument = function (command) {
// // wait a little in order to simulate asynchronous operation // Tells us that the document is not saved.
// setTimeout(function () {
// that.fail({status:0,statusText:'Unknown Error', setTimeout (function () {
// message:'Unknown error.'}); command.fail({status:0,statusText:'Unknown Error',
// }, 100); message:'Unknown error.'});
// }; // end userNameAvailable }, 100);
}; // end saveDocument
// that.saveDocument = function () {
// // Tells us that the document is not saved. that.loadDocument = function (command) {
// Returns a document object containing nothing.
// // wait a little in order to simulate asynchronous saving
// setTimeout (function () { setTimeout(function () {
// that.fail({status:0,statusText:'Unknown Error', command.fail({status:0,statusText:'Unknown Error',
// message:'Unknown error.'}); message:'Unknown error.'});
// }, 100); }, 100);
// }; // end saveDocument }; // end loadDocument
// that.loadDocument = function () { that.getDocumentList = function (command) {
// // Returns a document object containing nothing. // It returns nothing.
// // document object is {'name':string,'content':string, setTimeout(function () {
// // 'creation_date':date,'last_modified':date} command.fail({status:0,statusText:'Unknown Error',
message:'Unknown error.'});
// // wait a little in order to simulate asynchronous operation }, 100);
// setTimeout(function () { }; // end getDocumentList
// that.fail({status:0,statusText:'Unknown Error',
// message:'Unknown error.'}); that.removeDocument = function (command) {
// }, 100); // Remove a document from the storage.
// }; // end loadDocument
setTimeout (function () {
// that.getDocumentList = function () { command.fail({status:0,statusText:'Unknown Error',
// // It returns nothing. message:'Unknown error.'});
}, 100);
// // the list is [object,object] -> object = {'name':string, };
// // 'last_modified':date,'creation_date':date} return that;
},
// setTimeout(function () { // end Dummy Storage All Fail
// that.fail({status:0,statusText:'Unknown Error', ////////////////////////////////////////////////////////////////////////////
// message:'Unknown error.'});
// }, 100); ////////////////////////////////////////////////////////////////////////////
// }; // end getDocumentList // Dummy Storage 3 : all not found
newDummyStorageAllNotFound = function ( spec, my ) {
// that.removeDocument = function () { var that = Jio.storage( {type:'base'}, my );
// // Remove a document from the storage.
that.setType('dummyallnotfound');
// // returns {'status':string,'message':string,'isRemoved':boolean}
// // in the jobendcallback arguments. that.saveDocument = function (command) {
// Document does not exists yet, create it.
// setTimeout (function () {
// that.fail({status:0,statusText:'Unknown Error', setTimeout (function () {
// message:'Unknown error.'}); command.done();
// }, 100); }, 100);
// }; }; // end saveDocument
// return that;
// }, that.loadDocument = function (command) {
// // end Dummy Storage All Fail // Returns a document object containing nothing.
// ////////////////////////////////////////////////////////////////////////////
setTimeout(function () {
// //////////////////////////////////////////////////////////////////////////// command.fail({status:404,statusText:'Not Found',
// // Dummy Storage 3 : all not found message:'Document "'+ command.getPath() +
// newDummyStorageAllNotFound = function ( spec, my ) { '" not found.'});
// var that = Jio.newBaseStorage( spec, my ); }, 100);
}; // end loadDocument
// that.checkNameAvailability = function () {
// // [job.userName] not found, so the name is available. that.getDocumentList = function (command) {
// It returns nothing.
// // wait a little in order to simulate asynchronous operation
// setTimeout(function () { setTimeout(function () {
// that.done(true); command.fail({status:404,statusText:'Not Found',
// }, 100); message:'User list not found.'});
// }; // end userNameAvailable }, 100);
}; // end getDocumentList
// that.saveDocument = function () {
// // Document does not exists yet, create it. that.removeDocument = function (command) {
// Remove a document from the storage.
// // wait a little in order to simulate asynchronous saving
// setTimeout (function () { setTimeout (function () {
// that.done(); command.done();
// }, 100); }, 100);
// }; // end saveDocument };
return that;
// that.loadDocument = function () { },
// // Returns a document object containing nothing. // end Dummy Storage All Not Found
////////////////////////////////////////////////////////////////////////////
// // document object is {'name':string,'content':string,
// // 'creation_date':date,'last_modified':date} ////////////////////////////////////////////////////////////////////////////
// Dummy Storage 4 : all 3 tries
// // wait a little in order to simulate asynchronous operation newDummyStorageAll3Tries = function ( spec, my ) {
// setTimeout(function () { var that = Jio.storage( {type:'base'}, my ), priv = {};
// that.fail({status:404,statusText:'Not Found',
// message:'Document "'+ that.getFileName() + that.setType('dummyall3tries');
// '" not found.'});
// }, 100); priv.doJob = function (if_ok_return) {
// }; // end loadDocument // wait a little in order to simulate asynchronous operation
setTimeout(function () {
// that.getDocumentList = function () { priv.Try3OKElseFail (priv.command.getTried(),if_ok_return);
// // It returns nothing. }, 100);
};
// // the list is [object,object] -> object = {'name':string, priv.Try3OKElseFail = function (tries,if_ok_return) {
// // 'last_modified':date,'creation_date':date} if ( tries === 3 ) {
return priv.command.done(if_ok_return);
// setTimeout(function () { }
// that.fail({status:404,statusText:'Not Found', if ( tries < 3 ) {
// message:'User list not found.'}); return priv.command.fail(
// }, 100); {message:'' + (3 - tries) + ' tries left.'});
// }; // end getDocumentList }
if ( tries > 3 ) {
// that.removeDocument = function () { return priv.command.fail({message:'Too much tries.'});
// // Remove a document from the storage. }
};
// // returns {'status':string,'message':string,'isRemoved':boolean}
// // in the jobendcallback arguments. that.saveDocument = function (command) {
priv.command = command;
// setTimeout (function () { priv.doJob ();
// that.done(); }; // end saveDocument
// }, 100);
// }; that.loadDocument = function (command) {
// return that; priv.command = command;
// }, priv.doJob ({
// // end Dummy Storage All Not Found 'content': 'content2',
// //////////////////////////////////////////////////////////////////////////// 'name': 'file',
'creation_date': 11000,
// //////////////////////////////////////////////////////////////////////////// 'last_modified': 17000
// // Dummy Storage 4 : all 3 tries });
// newDummyStorageAll3Tries = function ( spec, my ) { }; // end loadDocument
// var that = Jio.newBaseStorage( spec, my ), priv = {};
that.getDocumentList = function (command) {
// priv.doJob = function (if_ok_return) { priv.command = command;
// // wait a little in order to simulate asynchronous operation priv.doJob([{'name':'file',
// setTimeout(function () { 'creation_date':10000,
// priv.Try3OKElseFail (that.cloneJob().tries,if_ok_return); 'last_modified':15000},
// }, 100); {'name':'memo',
// }; 'creation_date':20000,
// priv.Try3OKElseFail = function (tries,if_ok_return) { 'last_modified':25000}
// if ( tries === 3 ) { ]);
// return that.done(if_ok_return); }; // end getDocumentList
// }
// if ( tries < 3 ) { that.removeDocument = function (command) {
// return that.fail({message:'' + (3 - tries) + ' tries left.'}); priv.command = command;
// } priv.doJob();
// if ( tries > 3 ) { }; // end removeDocument
// return that.fail({message:'Too much tries.'});
// } return that;
// }; };
// end Dummy Storage All 3 Tries
// that.checkNameAvailability = function () { ////////////////////////////////////////////////////////////////////////////
// priv.doJob (true);
// }; // end userNameAvailable
// that.saveDocument = function () {
// priv.doJob ();
// }; // end saveDocument
// that.loadDocument = function () {
// priv.doJob ({
// 'content': 'content2',
// 'name': 'file',
// 'creation_date': 11000,
// 'last_modified': 17000
// });
// }; // end loadDocument
// that.getDocumentList = function () {
// priv.doJob([{'name':'file',
// 'creation_date':10000,
// 'last_modified':15000},
// {'name':'memo',
// 'creation_date':20000,
// 'last_modified':25000}
// ]);
// }; // end getDocumentList
// that.removeDocument = function () {
// priv.doJob();
// }; // end removeDocument
// return that;
// };
// // end Dummy Storage All 3 Tries
// ////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio // add key to storageObjectType of global jio
Jio.addStorageType('dummyallok', newDummyStorageAllOk); Jio.addStorageType('dummyallok', newDummyStorageAllOk);
// Jio.addStorageType('dummyallfail', newDummyStorageAllFail); Jio.addStorageType('dummyallfail', newDummyStorageAllFail);
// Jio.addStorageType('dummyallnotfound', newDummyStorageAllNotFound); Jio.addStorageType('dummyallnotfound', newDummyStorageAllNotFound);
// Jio.addStorageType('dummyall3tries', newDummyStorageAll3Tries); Jio.addStorageType('dummyall3tries', newDummyStorageAll3Tries);
}; };
......
...@@ -4,11 +4,28 @@ var command = function(spec, my) { ...@@ -4,11 +4,28 @@ var command = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.commandlist = {'saveDocument':saveDocument,
'loadDocument':loadDocument,
'removeDocument':removeDocument,
'getDocumentList':getDocumentList};
// creates the good command thanks to his label
if (spec.label && priv.commandlist[spec.label]) {
priv.label = spec.label;
delete spec.label;
return priv.commandlist[priv.label](spec, my);
}
priv.path = spec.path || ''; priv.path = spec.path || '';
priv.tried = 0;
priv.option = spec.option || {}; priv.option = spec.option || {};
priv.respond = priv.option.onResponse || function(){}; priv.respond = priv.option.onResponse || function(){};
priv.done = priv.option.onDone || function(){}; priv.done = priv.option.onDone || function(){};
priv.fail = priv.option.onFail || function(){}; priv.fail = priv.option.onFail || function(){};
priv.retry = function() {
that.setMaxRetry(-1);
that.fail({status:0,statusText:'Fail Retry',
message:'Impossible to retry.'});
};
priv.end = function() {}; priv.end = function() {};
// Methods // // Methods //
...@@ -49,12 +66,21 @@ var command = function(spec, my) { ...@@ -49,12 +66,21 @@ var command = function(spec, my) {
that.validateState(); that.validateState();
}; };
that.getTried = function() {
return priv.tried;
};
that.setMaxRetry = function(max_retry) {
priv.option.max_retry = max_retry;
};
/** /**
* Delegate actual excecution the storage handler. * Delegate actual excecution the storage handler.
* @param {object} handler The storage handler. * @param {object} handler The storage handler.
*/ */
that.execute = function(handler) { that.execute = function(handler) {
that.validate(handler); that.validate(handler);
priv.tried ++;
handler.execute(that); handler.execute(that);
}; };
...@@ -77,22 +103,31 @@ var command = function(spec, my) { ...@@ -77,22 +103,31 @@ var command = function(spec, my) {
}; };
that.done = function(return_value) { that.done = function(return_value) {
console.log ('test'); console.log ('done');
priv.done(return_value); priv.done(return_value);
priv.respond({status:doneStatus(),value:return_value}); priv.respond({status:doneStatus(),value:return_value});
priv.end(); priv.end();
}; };
that.fail = function(return_error) { that.fail = function(return_error) {
priv.fail(return_error); if (priv.option.max_retry === 0 || priv.tried < priv.option.max_retry) {
priv.respond({status:failStatus(),error:return_error}); priv.retry();
priv.end(); } else {
console.log ('fail');
priv.fail(return_error);
priv.respond({status:failStatus(),error:return_error});
priv.end();
}
}; };
that.onEndDo = function(fun) { that.onEndDo = function(fun) {
priv.end = fun; priv.end = fun;
}; };
that.onRetryDo = function(fun) {
priv.retry = fun;
};
/** /**
* Returns a serialized version of this command. * Returns a serialized version of this command.
* Override this function. * Override this function.
...@@ -101,6 +136,8 @@ var command = function(spec, my) { ...@@ -101,6 +136,8 @@ var command = function(spec, my) {
*/ */
that.serialized = function() { that.serialized = function() {
return {label:that.getLabel(), return {label:that.getLabel(),
tried:priv.tried,
max_retry:priv.max_retry,
path:priv.path, path:priv.path,
option:priv.option}; option:priv.option};
}; };
......
...@@ -4,7 +4,7 @@ var getDocumentList = function(spec, my) { ...@@ -4,7 +4,7 @@ var getDocumentList = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'getDocumentList'; return 'getDocumentList';
}; };
......
...@@ -4,7 +4,7 @@ var loadDocument = function(spec, my) { ...@@ -4,7 +4,7 @@ var loadDocument = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'loadDocument'; return 'loadDocument';
}; };
......
...@@ -4,7 +4,7 @@ var removeDocument = function(spec, my) { ...@@ -4,7 +4,7 @@ var removeDocument = function(spec, my) {
my = my || {}; my = my || {};
// Attributes // // Attributes //
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'removeDocument'; return 'removeDocument';
}; };
......
...@@ -5,7 +5,7 @@ var saveDocument = function(spec, my) { ...@@ -5,7 +5,7 @@ var saveDocument = function(spec, my) {
// Attributes // // Attributes //
var content = spec.content; var content = spec.content;
// Methods // // Methods //
that.label = function() { that.getLabel = function() {
return 'saveDocument'; return 'saveDocument';
}; };
......
...@@ -75,7 +75,6 @@ ...@@ -75,7 +75,6 @@
option.onDone = option.onDone || function(){}; option.onDone = option.onDone || function(){};
option.onFail = option.onFail || function(){}; option.onFail = option.onFail || function(){};
option.max_retry = option.max_retry || 0; option.max_retry = option.max_retry || 0;
console.log ('add job save: ' + JSON.stringify (priv.storage.serialized()));
jobManager.addJob( jobManager.addJob(
job({storage:(specificstorage? job({storage:(specificstorage?
jioNamespace.storage(specificstorage): jioNamespace.storage(specificstorage):
......
...@@ -18,9 +18,9 @@ var jioNamespace = (function(spec, my) { ...@@ -18,9 +18,9 @@ var jioNamespace = (function(spec, my) {
spec = spec || {}; spec = spec || {};
var type = spec.type || 'base'; var type = spec.type || 'base';
if (!storage_type_o[type]) { if (!storage_type_o[type]) {
throw invalidStorageType({type:type}); throw invalidStorageType({type:type,
message:'Storage does not exists.'});
} }
console.log ('create storage: ' + JSON.stringify (spec) + JSON.stringify (my));
return storage_type_o[type](spec, my); return storage_type_o[type](spec, my);
}; };
...@@ -40,7 +40,6 @@ var jioNamespace = (function(spec, my) { ...@@ -40,7 +40,6 @@ var jioNamespace = (function(spec, my) {
storage = JSON.parse (storage); storage = JSON.parse (storage);
} }
storage = storage || {type:'base'}; storage = storage || {type:'base'};
console.log ('new jio: storage: ' + JSON.stringify (spec));
return jio(spec); return jio(spec);
}; };
...@@ -56,7 +55,6 @@ var jioNamespace = (function(spec, my) { ...@@ -56,7 +55,6 @@ var jioNamespace = (function(spec, my) {
throw invalidStorageType({type:type,message:'Already known.'}); throw invalidStorageType({type:type,message:'Already known.'});
} }
storage_type_o[type] = constructor; storage_type_o[type] = constructor;
console.log ('adding: '+type);
}; };
return that; return that;
......
...@@ -8,8 +8,6 @@ var job = function(spec, my) { ...@@ -8,8 +8,6 @@ var job = function(spec, my) {
priv.command = spec.command; priv.command = spec.command;
priv.storage = spec.storage; priv.storage = spec.storage;
priv.status = initialStatus(); priv.status = initialStatus();
priv.tried = 0;
priv.max_retry = 0;
priv.date = new Date(); priv.date = new Date();
// Initialize // // Initialize //
...@@ -43,6 +41,10 @@ var job = function(spec, my) { ...@@ -43,6 +41,10 @@ var job = function(spec, my) {
return priv.storage; return priv.storage;
}; };
that.getDate = function() {
return priv.date;
};
/** /**
* Checks if the job is ready. * Checks if the job is ready.
* @method isReady * @method isReady
...@@ -64,8 +66,6 @@ var job = function(spec, my) { ...@@ -64,8 +66,6 @@ var job = function(spec, my) {
that.serialized = function() { that.serialized = function() {
return {id:priv.id, return {id:priv.id,
date:priv.date.getTime(), date:priv.date.getTime(),
tried:priv.tried,
max_retry:priv.max_retry,
status:priv.status.serialized(), status:priv.status.serialized(),
command:priv.command.serialized(), command:priv.command.serialized(),
storage:priv.storage.serialized()}; storage:priv.storage.serialized()};
...@@ -122,7 +122,13 @@ var job = function(spec, my) { ...@@ -122,7 +122,13 @@ 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) {
console.log ('updating');
priv.command.setMaxRetry(-1);
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.status = job.getStatus();
}; };
that.execute = function() { that.execute = function() {
...@@ -134,7 +140,14 @@ var job = function(spec, my) { ...@@ -134,7 +140,14 @@ var job = function(spec, my) {
throw jobNotReadyException({message:'Can not execute this job.'}); throw jobNotReadyException({message:'Can not execute this job.'});
} }
priv.status = onGoingStatus(); priv.status = onGoingStatus();
priv.tried ++; priv.command.onRetryDo (function() {
var ms = priv.command.getTried();
ms = ms*ms*200;
if (ms>10000){
ms = 10000;
}
that.waitForTime(ms);
});
priv.command.onEndDo (function() { priv.command.onEndDo (function() {
jobManager.terminateJob (that); jobManager.terminateJob (that);
}); });
......
...@@ -53,6 +53,7 @@ var jobManager = (function(spec, my) { ...@@ -53,6 +53,7 @@ var jobManager = (function(spec, my) {
var i; var i;
if (priv.interval_id === null) { if (priv.interval_id === null) {
priv.interval_id = setInterval (function() { priv.interval_id = setInterval (function() {
priv.restoreOldJio();
for (i = 0; i < priv.job_a.length; i+= 1) { for (i = 0; i < priv.job_a.length; i+= 1) {
that.execute(priv.job_a[i]); that.execute(priv.job_a[i]);
} }
...@@ -74,6 +75,47 @@ var jobManager = (function(spec, my) { ...@@ -74,6 +75,47 @@ var jobManager = (function(spec, my) {
} }
}; };
priv.restoreOldJio = function() {
var i, jio_id_a;
priv.lastrestore = priv.lastrestore || 0;
if (priv.lastrestore > (Date.now()) - 2000) { return; }
jio_id_a = LocalOrCookieStorage.getItem('jio/id_array')||[];
for (i = 0; i < jio_id_a.length; i+= 1) {
priv.restoreOldJioId(jio_id_a[i]);
}
priv.lastrestore = Date.now();
};
priv.restoreOldJioId = function(id) {
var jio_date;
jio_date = LocalOrCookieStorage.getItem('jio/id/'+id)||0;
if (jio_date < Date.now() - 10000) {
priv.restoreOldJobFromJioId(id);
priv.removeOldJioId(id);
}
};
priv.restoreOldJobFromJioId = function(id) {
var i, jio_job_array;
jio_job_array = LocalOrCookieStorage.getItem('jio/job_array/'+id)||[];
for (i = 0; i < jio_job_array.length; i+= 1) {
that.addJob ( job(
{storage:jioNamespace.storage(jio_job_array[i]),
command:command(jio_job_array[i].command)}));
}
};
priv.removeOldJioId = function(id) {
var i, jio_id_a, new_a = [];
jio_id_a = LocalOrCookieStorage.getItem('jio/id_array')||[];
for (i = 0; i < jio_id_a.length; i+= 1) {
if (jio_id_a[i] !== id) {
new_a.push(jio_id_a[i]);
}
}
LocalOrCookieStorage.setItem('jio/id_array',new_a);
};
/** /**
* Executes a job. * Executes a job.
* @method execute * @method execute
...@@ -92,6 +134,18 @@ var jobManager = (function(spec, my) { ...@@ -92,6 +134,18 @@ var jobManager = (function(spec, my) {
priv.copyJobArrayToLocal(); priv.copyJobArrayToLocal();
}; };
that.jobIdExists = function(id) {
var i;
for (i = 0; i < priv.job_a.length; i+= 1) {
if (priv.job_a[i].getId() === id) {
console.log ('found');
return true;
}
}
console.log ('not found');
return false;
};
that.terminateJob = function(job) { that.terminateJob = function(job) {
priv.removeJob(job); priv.removeJob(job);
priv.copyJobArrayToLocal(); priv.copyJobArrayToLocal();
...@@ -100,7 +154,6 @@ var jobManager = (function(spec, my) { ...@@ -100,7 +154,6 @@ var jobManager = (function(spec, my) {
that.addJob = function(job) { that.addJob = function(job) {
var result_a = that.validateJobAccordingToJobList (priv.job_a,job); var result_a = that.validateJobAccordingToJobList (priv.job_a,job);
priv.manage (job,result_a); priv.manage (job,result_a);
priv.copyJobArrayToLocal();
}; };
that.validateJobAccordingToJobList = function(job_a,job) { that.validateJobAccordingToJobList = function(job_a,job) {
...@@ -121,16 +174,19 @@ var jobManager = (function(spec, my) { ...@@ -121,16 +174,19 @@ var jobManager = (function(spec, my) {
return; return;
} }
} }
console.log ('managing '+JSON.stringify (result_a));
for (i = 0; i < result_a.length; i+= 1) { for (i = 0; i < result_a.length; i+= 1) {
switch (result_a[i].action) { switch (result_a[i].action) {
case 'eliminate': case 'eliminate':
console.log ('eliminating');
that.eliminate(result_a[i].job); that.eliminate(result_a[i].job);
break; break;
case 'replace': case 'update':
job.update(result_a[i].job); result_a[i].job.update(job);
priv.copyJobArrayToLocal(); priv.copyJobArrayToLocal();
return; return;
case 'wait': case 'wait':
console.log ('wait');
job.waitForJob(result_a[i].job); job.waitForJob(result_a[i].job);
break; break;
default: break; default: break;
...@@ -145,10 +201,12 @@ var jobManager = (function(spec, my) { ...@@ -145,10 +201,12 @@ var jobManager = (function(spec, my) {
for (i = 0; i < priv.job_a.length; i+= 1) { for (i = 0; i < priv.job_a.length; i+= 1) {
if (priv.job_a[i].getId() !== job.getId()) { if (priv.job_a[i].getId() !== job.getId()) {
tmp_a.push(priv.job_a[i]); tmp_a.push(priv.job_a[i]);
console.log ('add: '+priv.job_a[i].getId()+' -> it is not '+job.getId());
} }
} }
priv.job_a = tmp_a; priv.job_a = tmp_a;
priv.copyJobArrayToLocal();
}; };
return that; return that;
}()); }());
\ No newline at end of file
...@@ -12,8 +12,8 @@ var jobRules = (function(spec, my) { ...@@ -12,8 +12,8 @@ var jobRules = (function(spec, my) {
}; };
priv.default_compare = function(job1,job2) { priv.default_compare = function(job1,job2) {
return (job1.getCommand().getPath() === job2.getCommand().getPath() && return (job1.getCommand().getPath() === job2.getCommand().getPath() &&
JSON.stringify(job1.getStorage()) === JSON.stringify(job1.getStorage().serialized()) ===
JSON.stringify(job2.getStorage())); JSON.stringify(job2.getStorage().serialized()));
}; };
priv.action = { priv.action = {
/* /*
...@@ -130,7 +130,7 @@ var jobRules = (function(spec, my) { ...@@ -130,7 +130,7 @@ var jobRules = (function(spec, my) {
} }
} }
}; };
priv.default_action = 'none'; priv.default_action = that.none;
// Methods // // Methods //
priv.getAction = function(job1,job2) { priv.getAction = function(job1,job2) {
var j1label, j2label, j1status; var j1label, j2label, j1status;
...@@ -139,24 +139,36 @@ var jobRules = (function(spec, my) { ...@@ -139,24 +139,36 @@ var jobRules = (function(spec, my) {
j1status = (job1.getStatus().getLabel()==='on going'? j1status = (job1.getStatus().getLabel()==='on going'?
'on going':'not on going'); 'on going':'not on going');
try { try {
console.log (j1label);
console.log (j2label);
console.log (j1status);
return priv.action[j1label][j1status][j2label](job1,job2); return priv.action[j1label][j1status][j2label](job1,job2);
} catch (e) { } catch (e) {
return priv.default_action; if(e.name==='TypeError') {
return priv.default_action(job1,job2);
} else {
throw e;
}
} }
}; };
priv.canCompare = function(job1,job2) { priv.canCompare = function(job1,job2) {
var key = priv.stringifyJobForCompare(job1,job2); var job1label = job1.getCommand().getLabel(),
if (priv.compare[key]) { job2label = job2.getCommand().getLabel();
return priv.compare[key](job1,job2); try {
return priv.compare[job1label][job2label](job1,job2);
} catch(e) {
if (e.name==='TypeError') {
return priv.default_compare(job1,job2);
} else {
throw e;
}
} }
return priv.default_compare(job1,job2);
}; };
that.validateJobAccordingToJob = function(job1,job2) { that.validateJobAccordingToJob = function(job1,job2) {
var key = priv.stringifyJobForAction(job1,job2);
if (priv.canCompare(job1,job2)) { if (priv.canCompare(job1,job2)) {
return {action:priv.getAction(job1,job2),job:job1}; return {action:priv.getAction(job1,job2),job:job1};
} }
return {action:priv.default_action,job:job1}; return {action:priv.default_action(job1,job2),job:job1};
}; };
return that; return that;
......
...@@ -15,4 +15,4 @@ var failStatus = function(spec, my) { ...@@ -15,4 +15,4 @@ var failStatus = function(spec, my) {
return true; return true;
}; };
return that; return that;
}; };
\ No newline at end of file
...@@ -3,50 +3,63 @@ var waitStatus = function(spec, my) { ...@@ -3,50 +3,63 @@ var waitStatus = function(spec, my) {
spec = spec || {}; spec = spec || {};
my = my || {}; my = my || {};
// Attributes // // Attributes //
var job_id_a = spec.job_id_array || []; var priv = {};
var threshold = 0; priv.job_id_a = spec.job_id_array || [];
priv.threshold = 0;
// Methods // // Methods //
that.getLabel = function() { that.getLabel = function() {
return 'wait'; return 'wait';
}; };
priv.refreshJobIdArray = function() {
var tmp_job_id_a = [], i;
for (i = 0; i < priv.job_id_a.length; i+= 1) {
if (jobManager.jobIdExists(priv.job_id_a[i])) {
tmp_job_id_a.push(priv.job_id_a[i]);
}
}
priv.job_id_a = tmp_job_id_a;
};
that.waitForJob = function(job) { that.waitForJob = function(job) {
var i; var i;
for (i = 0; i < job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_a.length; i+= 1) {
if (job_id_a[i] === job.getId()) { if (priv.job_id_a[i] === job.getId()) {
return; return;
} }
} }
job_id_a.push(job.getId()); priv.job_id_a.push(job.getId());
}; };
that.dontWaitForJob = function(job) { that.dontWaitForJob = function(job) {
var i, tmp_job_id_a = []; var i, tmp_job_id_a = [];
for (i = 0; i < job_id_a.length; i+= 1) { for (i = 0; i < priv.job_id_a.length; i+= 1) {
if (job_id_a[i] !== job.getId()){ if (priv.job_id_a[i] !== job.getId()){
tmp_job_id_a.push(job_id_a[i]); tmp_job_id_a.push(priv.job_id_a[i]);
} }
} }
job_id_a = tmp_job_id_a; priv.job_id_a = tmp_job_id_a;
}; };
that.waitForTime = function(ms) { that.waitForTime = function(ms) {
threshold = Date.now() + ms; priv.threshold = Date.now() + ms;
}; };
that.stopWaitForTime = function() { that.stopWaitForTime = function() {
threshold = 0; priv.threshold = 0;
}; };
that.canStart = function() { that.canStart = function() {
return (job_id_a.length === 0 && Date.now() >= threshold); priv.refreshJobIdArray();
console.log (priv.job_id_a);
return (priv.job_id_a.length === 0 && Date.now() >= priv.threshold);
}; };
that.canRestart = function() { that.canRestart = function() {
return false; return that.canStart();
}; };
that.serialized = function() { that.serialized = function() {
return {label:that.getLabel(), return {label:that.getLabel(),
waitfortime:threshold, waitfortime:priv.threshold,
waitforjob:job_id_a}; waitforjob:priv.job_id_a};
}; };
return that; return that;
......
...@@ -136,103 +136,126 @@ test ('All tests', function () { ...@@ -136,103 +136,126 @@ test ('All tests', function () {
// It is simple tests, but they will be used by replicate storage later // It is simple tests, but they will be used by replicate storage later
// for sync operation. // for sync operation.
var o = {}, clock = this.sandbox.useFakeTimers(), var o = {}; o.t = this; o.clock = o.t.sandbox.useFakeTimers();
mytest = function (message,method,retmethod,value){ o.spy = function(res,value,message) {
o.f = function (result) { o.f = function(result) {
deepEqual (result,value,message); if (res === 'status') {
deepEqual (result.status.getLabel(),value,message);
} else {
deepEqual (result.value,value,message);
}
}; };
this.spy(o,'f'); o.t.spy(o,'f');
o.jio[method]({'user_name':'Dummy','name':'file', };
'content':'content','onResponse':o.f, o.tick = function (tick) {
'max_tries':1}); o.clock.tick(tick || 1000);
clock.tick(510);
if (!o.f.calledOnce) { if (!o.f.calledOnce) {
ok(false, 'no response / too much results'); ok(false, 'no response / too much results');
} }
}; };
// All Ok Dummy Storage // All Ok Dummy Storage
o.jio = JIO.newJio({'type':'dummyallok','user_name':'Dummy', o.jio = JIO.newJio({'type':'dummyallok'});
'applicationname':'jiotests'}); // save
o.f = function (result) { o.spy('status','done','dummyallok saving');
deepEqual (result,undefined,''); o.jio.saveDocument('file','content',{onResponse:o.f,max_retry:1});
}; o.tick();
this.spy(o,'f'); // load
o.jio.saveDocument('file','content',{onDone:o.f}); o.spy('value',{name:'file',content:'content',last_modified:15000,
clock.tick(1000); creation_date:10000},'dummyallok loading');
if (!o.f.calledOnce) { o.jio.loadDocument('file',{onResponse:o.f,max_retry:1});
ok(false, 'no response / too much results'); o.tick();
} // remove
// mytest('save document OK','saveDocument','status','done'); o.spy('status','done','dummyallok removing');
// mytest('load document OK','loadDocument','return_value', o.jio.removeDocument('file',{onResponse:o.f,max_retry:1});
// {'name':'file','content':'content', o.tick();
// 'last_modified':15000,'creation_date':10000}); // get list
// mytest('get document list OK','getDocumentList','return_value', o.spy ('value',[{name:'file',content:'filecontent',last_modified:15000,
// [{'name':'file','creation_date':10000,'last_modified':15000}, creation_date:10000},
// {'name':'memo','creation_date':20000,'last_modified':25000}]); {name:'memo',content:'memocontent',last_modified:25000,
// mytest('remove document OK','removeDocument','status','done'); creation_date:20000}],'dummyallok getting list');
// o.jio.stop(); o.jio.getDocumentList('.',{onResponse:o.f,metadata_only:false,max_retry:1});
o.tick();
// // All Fail Dummy Storage o.jio.stop();
// o.jio = JIO.newJio({'type':'dummyallfail','user_name':'Dummy'},
// {'ID':'jiotests'}); // All Fail Dummy Storage
// mytest('save document FAIL','saveDocument','status','fail'); o.jio = JIO.newJio({'type':'dummyallfail'});
// mytest('load document FAIL','loadDocument','status','fail'); // save
// mytest('get document list FAIL','getDocumentList','status','fail'); o.spy ('status','fail','dummyallfail saving');
// mytest('remove document FAIL','removeDocument','status','fail'); o.jio.saveDocument('file','content',{onResponse:o.f,max_retry:1});
// o.jio.stop(); o.tick();
// load
// // All Not Found Dummy Storage o.spy ('status','fail','dummyallfail loading');
// o.jio = JIO.newJio({'type':'dummyallnotfound','user_name':'Dummy'}, o.jio.loadDocument('file',{onResponse:o.f,max_retry:1});
// {'ID':'jiotests'}); o.tick();
// mytest('save document NOT FOUND','saveDocument','status','done'); // remove
// mytest('load document NOT FOUND','loadDocument','status','fail'); o.spy ('status','fail','dummyallfail removing');
// mytest('get document list NOT FOUND','getDocumentList','status','fail'); o.jio.removeDocument('file',{onResponse:o.f,max_retry:1});
// mytest('remove document NOT FOUND','removeDocument','status','done'); o.tick();
// get list
o.spy ('status','fail','dummyallfail getting list');
o.jio.getDocumentList('.',{onResponse:o.f,max_retry:1});
o.tick();
o.jio.stop();
// All Not Found Dummy Storage
o.jio = JIO.newJio({'type':'dummyallnotfound'});
// save
o.spy('status','done','dummyallnotfound saving');
o.jio.saveDocument('file','content',{onResponse:o.f,max_retry:1});
o.tick();
// load
o.spy('status','fail','dummyallnotfound loading');
o.jio.loadDocument('file',{onResponse:o.f,max_retry:1});
o.tick();
// remove
o.spy('status','done','dummyallnotfound removing');
o.jio.removeDocument('file',{onResponse:o.f,max_retry:1});
o.tick();
// get list
o.spy('status','fail','dummyallnotfound getting list');
o.jio.getDocumentList ('.',{onResponse:o.f,max_retry:1});
o.tick();
o.jio.stop(); o.jio.stop();
}); });
module ( 'Jio Job Managing' ); module ( 'Jio Job Managing' );
test ('Simple Job Elimination', function () { test ('Simple Job Elimination', function () {
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {}, id = 0;
o.f1 = this.spy(); o.f2 = this.spy(); o.f1 = this.spy(); o.f2 = this.spy();
o.jio = JIO.newJio({'type':'dummyallok','user_name':'dummy'}, o.jio = JIO.newJio({type:'dummyallok',applicationname:'jiotests'});
{'ID':'jiotests'}); id = o.jio.getId();
id = o.jio.getID(); o.jio.saveDocument('file','content',{onResponse:o.f1,max_retry:1});
o.jio.saveDocument({'name':'file','content':'content', ok(LocalOrCookieStorage.getItem('jio/job_array/'+id)[0],
'onResponse':o.f1,'max_tries':1});
ok(LocalOrCookieStorage.getItem('jio/job_object/'+id)['1'],
'job creation'); 'job creation');
clock.tick(10); o.jio.removeDocument('file',{onResponse:o.f2,max_retry:1});
o.jio.removeDocument({'name':'file','content':'content', o.tmp = LocalOrCookieStorage.getItem('jio/job_array/'+id)[0];
'onResponse':o.f2,'max_tries':1}); console.log (localStorage);
o.tmp = LocalOrCookieStorage.getItem('jio/job_object/'+id)['1']; deepEqual(o.tmp.command.label,'removeDocument','job elimination');
ok(!o.tmp || o.tmp.status === 'fail','job elimination');
}); });
test ('Simple Job Replacement', function () { test ('Simple Job Replacement', function () {
// Test if the second job write over the first one // Test if the second job write over the first one
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {};
o.clock = this.sandbox.useFakeTimers();
o.id = 0;
o.f1 = function (result) { o.f1 = function (result) {
o.status = result.status; o.status = result.status.getLabel();
}; };
this.spy(o,'f1'); this.spy(o,'f1');
o.f2 = this.spy(); o.f2 = this.spy();
o.jio = JIO.newJio({'type':'dummyallok','user_name':'dummy'}, o.jio = JIO.newJio({type:'dummyallok',applicationname:'jiotests'});
{'ID':'jiotests'}); o.id = o.jio.getId();
id = o.jio.getID(); o.jio.saveDocument('file','content',{onResponse:o.f1,max_retry:1});
o.jio.saveDocument({'name':'file','content':'content', o.clock.tick(10);
'onResponse':o.f1,'max_tries':1}); o.jio.saveDocument('file','content',{onResponse:o.f2,max_retry:1});
clock.tick(10);
o.jio.saveDocument({'name':'file','content':'content',
'onResponse':o.f2,'max_tries':1});
deepEqual(LocalOrCookieStorage.getItem( deepEqual(LocalOrCookieStorage.getItem(
'jio/job_object/'+id)['1'].date,10, 'jio/job_array/'+o.id)[0].date,10,
'The first job date have to be equal to the second job date.'); 'The first job date have to be equal to the second job date.');
clock.tick(500); o.clock.tick(1000);
deepEqual([o.f1.calledOnce,o.status],[true,'fail'], deepEqual([o.f1.calledOnce,o.status],[true,'fail'],
'callback for the first save request -> result fail'); 'callback for the first save request -> result fail');
ok(o.f2.calledOnce,'second callback is called once'); ok(o.f2.calledOnce,'second callback is called once');
...@@ -243,30 +266,31 @@ test ('Simple Job Replacement', function () { ...@@ -243,30 +266,31 @@ test ('Simple Job Replacement', function () {
test ('Simple Job Waiting', function () { test ('Simple Job Waiting', function () {
// Test if the second job doesn't erase the first on going one // Test if the second job doesn't erase the first on going one
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {};
o.clock = this.sandbox.useFakeTimers();
o.id = 0;
o.f3 = this.spy(); o.f4 = this.spy(); o.f3 = this.spy(); o.f4 = this.spy();
o.jio = JIO.newJio({'type':'dummyallok','user_name':'dummy'}, o.jio = JIO.newJio({type:'dummyallok',applicationname:'jiotests'});
{'ID':'jiotests'}); o.id = o.jio.getId();
id = o.jio.getID(); o.jio.saveDocument('file','content',{onResponse:o.f3,max_retry:1});
o.jio.saveDocument({'name':'file','content':'content', console.log (LocalOrCookieStorage.getItem ('jio/job_array/'+o.id));
'onResponse':o.f3,'max_tries':1}); o.clock.tick(200);
clock.tick(200); console.log (LocalOrCookieStorage.getItem ('jio/job_array/'+o.id));
o.jio.saveDocument({'name':'file','content':'content', o.jio.saveDocument('file','content1',{onResponse:o.f4,max_retry:1});
'onResponse':o.f4,'max_tries':1}); console.log (LocalOrCookieStorage.getItem ('jio/job_array/'+o.id));
ok(LocalOrCookieStorage.getItem( o.tmp0 = LocalOrCookieStorage.getItem('jio/job_array/'+o.id)[0];
'jio/job_object/'+id)['2'] && o.tmp1 = LocalOrCookieStorage.getItem('jio/job_array/'+o.id)[1];
LocalOrCookieStorage.getItem( ok(o.tmp1 && o.tmp0.status.label === 'on going',
'jio/job_object/'+id)['1'].status === 'on_going',
'The second job must not overwrite the first on going one.'); 'The second job must not overwrite the first on going one.');
ok(LocalOrCookieStorage.getItem( console.log (LocalOrCookieStorage.getItem ('jio/job_array/'+o.id));
'jio/job_object/'+id)['2'].status === 'wait' && ok(o.tmp1.status.label === 'wait' &&
LocalOrCookieStorage.getItem( o.tmp1.status.waitforjob &&
'jio/job_object/'+id)['2'].waiting_for && JSON.stringify(o.tmp1.status.waitforjob) ===
JSON.stringify (LocalOrCookieStorage.getItem( JSON.stringify ([1]),
'jio/job_object/'+id)['2'].waiting_for.job_id_array) === '["1"]',
'The second job must be waiting for the first to end'); 'The second job must be waiting for the first to end');
clock.tick(500); o.clock.tick(1000);
console.log (LocalOrCookieStorage.getItem ('jio/job_array/'+o.id));
ok(o.f3.calledOnce,'first request passed'); ok(o.f3.calledOnce,'first request passed');
ok(o.f4.calledOnce,'restore waiting job'); ok(o.f4.calledOnce,'restore waiting job');
o.jio.stop(); o.jio.stop();
...@@ -278,19 +302,41 @@ test ('Simple Time Waiting' , function () { ...@@ -278,19 +302,41 @@ test ('Simple Time Waiting' , function () {
var o = {}, clock = this.sandbox.useFakeTimers(), id = 0; var o = {}, clock = this.sandbox.useFakeTimers(), id = 0;
o.f = function (result) { o.f = function (result) {
o.res = (result.status === 'done'); o.res = (result.status.getLabel() === 'done');
}; };
this.spy(o,'f'); this.spy(o,'f');
o.jio = JIO.newJio({'type':'dummyall3tries','user_name':'dummy'}, o.jio = JIO.newJio({type:'dummyall3tries',applicationname:'jiotests'});
{'ID':'jiotests'}); o.jio.saveDocument('file','content',{onResponse:o.f,max_retry:3});
o.jio.saveDocument({'name':'file','content':'content',
'onResponse':o.f,'max_tries':3});
clock.tick(100000); clock.tick(100000);
ok(o.f.calledOnce,'callback called once.'); ok(o.f.calledOnce,'callback called once.');
ok(o.res,'job done.'); ok(o.res,'job done.');
o.jio.stop(); o.jio.stop();
}); });
module ( 'Jio Restore');
test ('Restore old Jio', function() {
var o = {};
o.clock = this.sandbox.useFakeTimers();
o.f = function(result) {
ok(false,'must never be called!');
};
o.clock.tick(10000000);
this.spy(o,'f');
o.jio = JIO.newJio({type:'dummyall3tries',applicationname:'jiotests'});
o.id = o.jio.getId();
o.jio.saveDocument('file','content',{onResponse:o.f,max_retry:3});
o.clock.tick(1000);
o.jio.stop();
o.jio = JIO.newJio({type:'dummyallok',applicationname:'jiotests'});
o.clock.tick(10000); // 10 sec
console.log (localStorage);
deepEqual(LocalOrCookieStorage.getItem('jio/job_array/'+o.id),null,
'job array list must be empty');
deepEqual(LocalOrCookieStorage.getItem('jio/job_array/'+o.jio.getId()),[],
'ee');
});
module ( 'Jio LocalStorage' ); module ( 'Jio LocalStorage' );
test ('Check name availability', function () { test ('Check name availability', function () {
......
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