2 function debug_dict_keys (msg, o) {
4 for (var k in o) keys.push(k);
5 messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
7 function debug_dict (msg, o) {
8 for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
10 function debug_value (msg, value) {
11 messages.debug ("debug_value: " + msg + " " + value);
13 function debug_query (msg, query) {
14 if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15 else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16 else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17 else messages.debug ("debug_query: " + msg + " query= " + query);
20 // http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript
21 // attach the .equals method to Array's prototype to call it on any array
22 Array.prototype.equals = function (array) {
23 // if the other array is a falsy value, return
27 // compare lengths - can save a lot of time
28 if (this.length != array.length)
31 for (var i = 0, l=this.length; i < l; i++) {
32 // Check if we have nested arrays
33 if (this[i] instanceof Array && array[i] instanceof Array) {
34 // recurse into the nested arrays
35 if (!this[i].equals(array[i]))
38 else if (this[i] != array[i]) {
39 // Warning - two different object instances will never be equal: {x:20} != {x:20}
46 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
47 Object.toType = (function toType(global) {
48 return function(obj) {
52 return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
56 /* ------------------------------------------------------------ */
58 // Constants that should be somehow moved to a plugin.js file
60 var FILTER_REMOVED = 2;
61 var CLEAR_FILTERS = 3;
63 var FIELD_REMOVED = 5;
66 var CLEAR_RECORDS = 8;
69 * event: FIELD_STATE_CHANGED
73 * .state : ???? used to be FIELD_REQUEST_ADD / FIELD_REQUEST_REMOVE
74 * .key : ??? the key fields of the record
75 * .op : the key of the record who has received an update
76 * .value : the new state of the record
78 var FIELD_STATE_CHANGED = 9;
80 var IN_PROGRESS = 101;
81 var DONE = 102; //XXX Should be harmonized with query state
83 /* Update requests related to subqueries */
87 var SET_REMOVED = 202;
92 var FIELD_REQUEST_CHANGE = 301;
93 var FIELD_REQUEST_ADD = 302;
94 var FIELD_REQUEST_REMOVE = 303;
95 var FIELD_REQUEST_ADD_RESET = 304;
96 var FIELD_REQUEST_REMOVE_RESET = 305;
98 // status (XXX Should be deprecated)
99 var FIELD_REQUEST_PENDING = 401;
100 var FIELD_REQUEST_SUCCESS = 402;
101 var FIELD_REQUEST_FAILURE = 403;
102 var STATUS_OKAY = 404;
103 var STATUS_SET_WARNING = 405;
104 var STATUS_ADD_WARNING = 406;
105 var STATUS_REMOVE_WARNING = 407;
106 var STATUS_RESET = 408;
108 /* Requests for query cycle */
109 var RUN_UPDATE = 601;
114 var TYPE_LIST_OF_VALUES = 3;
115 var TYPE_LIST_OF_RECORDS = 4;
117 /******************************************************************************
118 * QUERY STATUS (for manifold events)
119 ******************************************************************************/
121 var STATUS_NONE = 500; // Query has not been started yet
122 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
123 var STATUS_GET_RECEIVED = 502; // Success
124 var STATUS_GET_ERROR = 503; // Error
125 var STATUS_UPDATE_PENDING = 504;
126 var STATUS_UPDATE_IN_PROGRESS = 505;
127 var STATUS_UPDATE_RECEIVED = 506;
128 var STATUS_UPDATE_ERROR = 507;
130 /******************************************************************************
131 * QUERY STATE (for query_store)
132 ******************************************************************************/
134 // XXX Rendundant with query status ?
136 var QUERY_STATE_INIT = 0;
137 var QUERY_STATE_INPROGRESS = 1;
138 var QUERY_STATE_DONE = 2;
140 /******************************************************************************
141 * RECORD STATES (for query_store)
142 ******************************************************************************/
146 var STATE_WARNINGS = 2;
147 var STATE_VISIBLE = 3;
150 var STATE_SET_CHANGE = 0;
151 var STATE_SET_ADD = 1;
152 var STATE_SET_REMOVE = 2;
153 var STATE_SET_CLEAR = 3;
156 var STATE_SET_IN = 0;
157 var STATE_SET_OUT = 1;
158 var STATE_SET_IN_PENDING = 2;
159 var STATE_SET_OUT_PENDING = 3;
160 var STATE_SET_IN_SUCCESS = 4;
161 var STATE_SET_OUT_SUCCESS = 5;
162 var STATE_SET_IN_FAILURE = 6;
163 var STATE_SET_OUT_FAILURE = 7;
164 var STATE_VALUE_CHANGE_PENDING = 8;
165 var STATE_VALUE_CHANGE_SUCCESS = 9;
166 var STATE_VALUE_CHANGE_FAILURE = 10;
168 // STATE_WARNINGS : dict
170 // STATE_VISIBLE : boolean
172 /******************************************************************************
174 ******************************************************************************/
176 var CONSTRAINT_RESERVABLE_LEASE = 0;
178 var CONSTRAINT_RESERVABLE_LEASE_MSG = "Configuration required: this resource needs to be scheduled";
180 // A structure for storing queries
182 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled, domain_query_ext) {
185 if (typeof query == "undefined")
186 throw "Must pass a query in QueryExt constructor";
188 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext;
189 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext;
190 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext;
191 this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null : update_query_orig_ext;
192 this.disabled = (typeof disabled == "undefined") ? false : disabled;
194 // A domain query is a query that is issued to retrieve all possible values for a set
195 // eg. all resources that can be attached to a slice
196 // It is null unless we are a subquery for which a domain query has been issued
197 this.domain_query_ext = (typeof domain_query_ext == "undefined") ? null : domain_query_ext;
199 // Set members to buffer until the domain query is completed
201 this.set_members = [];
203 // The set query is the query for which the domain query has been issued.
204 // It is null unless the query is a domain query
205 this.set_query_ext = (typeof set_query_ext == "undefined") ? null : domain_query_ext;
207 this.query_state = QUERY_STATE_INIT;
209 // Results from a query consists in a dict that maps keys to records
210 this.records = new Hashtable();
212 // Status is a dict that maps keys to record status
213 this.state = new Hashtable();
215 // Filters that impact visibility in the local interface
218 // XXX Until we find a better solution
219 this.num_pending = 0;
220 this.num_unconfigured = 0;
222 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
225 function QueryStore() {
227 this.main_queries = {};
228 this.analyzed_queries = {};
232 this.insert = function(query) {
233 // We expect only main_queries are inserted
235 /* If the query has not been analyzed, then we analyze it */
236 if (query.analyzed_query == null) {
237 query.analyze_subqueries();
240 /* We prepare the update query corresponding to the main query and store both */
241 /* Note: they have the same UUID */
243 // XXX query.change_action() should become deprecated
244 update_query = query.clone();
245 update_query.action = 'update';
246 update_query.analyzed_query.action = 'update';
247 update_query.params = {};
248 update_query_ext = new QueryExt(update_query);
250 /* We remember the original query to be able to reset it */
251 update_query_orig_ext = new QueryExt(update_query.clone());
254 /* We store the main query */
255 query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
256 manifold.query_store.main_queries[query.query_uuid] = query_ext;
257 /* Note: the update query does not have an entry! */
260 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
261 // XXX unless we have no subqueries ???
262 // we will complete with params when records are received... this has to be done by the manager
263 // SET_ADD, SET_REMOVE will change the status of the elements of the set
264 // UPDATE will change also, etc.
265 // XXX We need a proper structure to store this information...
267 // We also need to insert all queries and subqueries from the analyzed_query
268 // XXX We need the root of all subqueries
269 query.iter_subqueries(function(sq, data, parent_query) {
270 var parent_query_ext;
272 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
274 parent_query_ext = null;
276 // XXX parent_query_ext == false
277 // XXX main.subqueries = {} # Normal, we need analyzed_query
278 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
281 /* Let's issue a query for the subquery domain. This query will not need any update etc.
282 eg. for resources in a slice, we also query all resources */
283 var all_fields = manifold.metadata.get_field_names(sq.object);
284 var domain_query = new ManifoldQuery('get', sq.object, 'now', [], {}, all_fields);
285 //var domain_query = new ManifoldQuery('get', sq.object);
287 console.log("Created domain query", domain_query);
288 var domain_query_ext = new QueryExt(domain_query);
290 domain_query_ext.set_query_ext = sq_ext;
291 sq_ext.domain_query_ext = domain_query_ext;
293 // One of these two is useless ?
294 manifold.query_store.main_queries[domain_query.query_uuid] = domain_query_ext;
295 manifold.query_store.analyzed_queries[domain_query.query_uuid] = domain_query_ext;
297 // XXX This query is run before the plugins are initialized and listening
298 manifold.run_query(domain_query);
301 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
304 // XXX We have spurious update queries...
309 this.find_query_ext = function(query_uuid)
311 return this.main_queries[query_uuid];
314 this.find_query = function(query_uuid)
316 return this.find_query_ext(query_uuid).query;
319 this.find_analyzed_query_ext = function(query_uuid)
321 return this.analyzed_queries[query_uuid];
324 this.find_analyzed_query = function(query_uuid)
326 return this.find_analyzed_query_ext(query_uuid).query;
329 this.state_dict_create = function(default_set)
331 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
333 // We cannot use constants in literal definition, so...
334 state_dict[STATE_WARNINGS] = {};
335 state_dict[STATE_SET] = default_set;
336 state_dict[STATE_VISIBLE] = true;
342 this.set_records = function(query_uuid, records, default_set)
344 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
347 var query_ext = this.find_analyzed_query_ext(query_uuid);
348 var record_key = manifold.metadata.get_key(query_ext.query.object);
349 $.each(records, function(i, record) {
350 var key = manifold.metadata.get_key(query_ext.query.object);
351 // ["start_time", "resource", "end_time"]
354 var record_key_value = manifold.record_get_value(record, record_key);
355 query_ext.records.put(record_key_value, record);
357 if (!(query_ext.state.get(record_key_value)))
358 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
362 this.get_records = function(query_uuid)
364 var query_ext = this.find_analyzed_query_ext(query_uuid);
365 return query_ext.records.values();
368 this.get_record = function(query_uuid, record_key)
370 var query_ext = this.find_analyzed_query_ext(query_uuid);
371 return query_ext.records.get(record_key);
374 this.del_record = function(query_uuid, record_key)
376 var query_ext = this.find_analyzed_query_ext(query_uuid);
377 return query_ext.records.remove(record_key);
380 this.del_state = function(query_uuid, record_key)
382 var query_ext = this.find_analyzed_query_ext(query_uuid);
383 return query_ext.state.remove(record_key);
386 this.add_record = function(query_uuid, record, new_state)
388 var query_ext, key, record_key;
389 query_ext = this.find_analyzed_query_ext(query_uuid);
391 if (typeof(record) == 'object') {
392 key = manifold.metadata.get_key(query_ext.query.object);
393 record_key = manifold.record_get_value(record, key);
398 var record_entry = query_ext.records.get(record_key);
400 query_ext.records.put(record_key, record);
402 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
405 this.remove_record = function(query_uuid, record, new_state)
407 var query_ext, key, record_key;
408 query_ext = this.find_analyzed_query_ext(query_uuid);
410 if (typeof(record) == 'object') {
411 key = manifold.metadata.get_key(query_ext.query.object);
412 record_key = manifold.record_get_value(record, key);
417 if ((query_ext.query.object == 'lease') && (new_state == STATE_SET_OUT)) {
418 // Leases that are marked out are in fact leases from other slices
419 // We need to _remove_ leases that we mark as OUT
420 manifold.query_store.del_record(query_uuid, record_key);
421 manifold.query_store.del_state(query_uuid, record_key);
423 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
427 this.iter_records = function(query_uuid, callback)
429 var query_ext = this.find_analyzed_query_ext(query_uuid);
430 query_ext.records.each(callback);
431 //callback = function(record_key, record)
434 this.iter_visible_records = function(query_uuid, callback)
436 var query_ext = this.find_analyzed_query_ext(query_uuid);
437 query_ext.records.each(function(record_key, record) {
438 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
439 callback(record_key, record);
441 //callback = function(record_key, record)
447 this.set_record_state = function(query_uuid, result_key, state, value)
449 var query_ext = this.find_analyzed_query_ext(query_uuid);
450 var state_dict = query_ext.state.get(result_key);
452 state_dict = this.state_dict_create();
454 state_dict[state] = value;
456 query_ext.state.put(result_key, state_dict);
459 this.get_record_state = function(query_uuid, result_key, state)
461 var query_ext = this.find_analyzed_query_ext(query_uuid);
462 var state_dict = query_ext.state.get(result_key);
465 return state_dict[state];
470 this.add_filter = function(query_uuid, filter)
472 var query_ext = this.find_analyzed_query_ext(query_uuid);
473 // XXX When we update a filter
474 query_ext.filters.push(filter);
476 this.apply_filters(query_uuid);
480 this.update_filter = function(query_uuid, filter)
484 this.apply_filters(query_uuid);
487 this.remove_filter = function(query_uuid, filter)
489 var query_ext = this.find_analyzed_query_ext(query_uuid);
490 query_ext.filters = $.grep(query_ext.filters, function(x) {
491 return !(x.equals(filter));
494 this.apply_filters(query_uuid);
497 this.get_filters = function(query_uuid)
499 var query_ext = this.find_analyzed_query_ext(query_uuid);
500 return query_ext.filters;
503 this.recount = function(query_uuid)
506 var is_reserved, is_pending, in_set, is_unconfigured;
508 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
509 query_ext.num_pending = 0;
510 query_ext.num_unconfigured = 0;
512 this.iter_records(query_uuid, function(record_key, record) {
513 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
514 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
516 is_reserved = (record_state == STATE_SET_IN)
517 || (record_state == STATE_SET_OUT_PENDING)
518 || (record_state == STATE_SET_IN_SUCCESS)
519 || (record_state == STATE_SET_OUT_FAILURE);
521 is_pending = (record_state == STATE_SET_IN_PENDING)
522 || (record_state == STATE_SET_OUT_PENDING);
524 in_set = (record_state == STATE_SET_IN) // should not have warnings
525 || (record_state == STATE_SET_IN_PENDING)
526 || (record_state == STATE_SET_IN_SUCCESS)
527 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
529 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
531 /* Let's update num_pending and num_unconfigured at this stage */
533 query_ext.num_pending++;
535 query_ext.num_unconfigured++;
540 this.apply_filters = function(query_uuid)
542 var start = new Date().getTime();
544 // Toggle visibility of records according to the different filters.
547 var filters = this.get_filters(query_uuid);
549 /* Let's update num_pending and num_unconfigured at this stage */
551 // Adapted from querytable._querytable_filter()
553 this.iter_records(query_uuid, function(record_key, record) {
554 var is_reserved, is_pending, in_set, is_unconfigured;
557 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
558 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
560 is_reserved = (record_state == STATE_SET_IN)
561 || (record_state == STATE_SET_OUT_PENDING)
562 || (record_state == STATE_SET_IN_SUCCESS)
563 || (record_state == STATE_SET_OUT_FAILURE);
565 is_pending = (record_state == STATE_SET_IN_PENDING)
566 || (record_state == STATE_SET_OUT_PENDING);
568 in_set = (record_state == STATE_SET_IN) // should not have warnings
569 || (record_state == STATE_SET_IN_PENDING)
570 || (record_state == STATE_SET_IN_SUCCESS)
571 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
573 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
575 // We go through each filter and decide whether it affects the visibility of the record
576 $.each(filters, function(index, filter) {
579 var value = filter[2];
582 /* We do some special handling for the manifold:status filter
585 if (key == 'manifold:status') {
586 if (op != '=' && op != '==') {
587 // Unsupported filter, let's ignore it
588 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
589 return true; // ~ continue
594 // true => ~ continue
596 visible = is_reserved;
599 visible = is_unconfigured;
602 visible = is_pending;
605 return false; // ~ break
608 /* Normal filtering behaviour (according to the record content) follows... */
609 col_value = manifold.record_get_value(record, key);
611 // When the filter does not match, we hide the column by default
612 if (col_value === 'undefined') {
614 return false; // ~ break
617 // XXX This should accept pluggable filtering functions.
620 /* Test whether current filter is compatible with the column */
621 if (op == '=' || op == '==') {
622 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
624 }else if (op == 'included') {
625 $.each(value, function(i,x) {
628 return false; // ~ break
633 }else if (op == '!=') {
634 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
637 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
640 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
642 } else if(op=='<=' || op=='≤') {
643 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
645 } else if(op=='>=' || op=='≥') {
646 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
649 // How to break out of a loop ?
650 alert("filter not supported");
651 return false; // break
656 // Set the visibility status in the query store
657 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
660 var end = new Date().getTime();
661 console.log("APPLY FILTERS took", end - start, "ms");
668 * This namespace holds functions for globally managing query objects
673 /**************************************************************************
675 **************************************************************************/
679 get_type: function(variable) {
680 switch(Object.toType(variable)) {
687 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
688 return TYPE_LIST_OF_RECORDS;
690 return TYPE_LIST_OF_VALUES;
696 * fields: A String instance (field name), or a set of String instances
697 * (field names) # XXX tuple !!
699 * If fields is a String, return the corresponding value.
700 * If fields is a set, return a tuple of corresponding value.
703 * KeyError if at least one of the fields is not found
705 record_get_value: function(record, fields)
707 if (typeof(fields) === 'string') {
708 if (fields.indexOf('.') != -1) {
709 key_subkey = key.split('.', 2);
711 subkey = key_subkey[1];
713 if (record.indexOf(key) == -1) {
716 // Tests if the following is an array (typeof would give object)
717 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
719 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
720 } else if (typeof(record) == 'object') {
722 return manifold.record_get_value(record[key], subkey);
724 console.log('Unknown field');
727 return record[fields];
730 // see. get_map_entries
731 if (fields.length == 1)
732 return manifold.record_get_value(record, fields[0])
734 // Build a new record
736 $.each(fields, function(i, field) {
737 ret[field] = manifold.record_get_value(record, field);
739 ret.hashCode = record.hashCode;
740 ret.equals = record.equals;
742 // this was an array, we want a dictionary
743 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
748 record_hashcode: function(key_fields)
752 for (var i=0; i < key_fields.length; i++)
753 ret += "@@" + this[key_fields[i]];
758 _record_equals: function(self, other, key_fields)
760 for (var i=0; i < key_fields.length; i++) {
761 var this_value = self[key_fields[i]];
762 var other_value = other[key_fields[i]];
764 var this_type = manifold.get_type(this_value);
765 var other_type = manifold.get_type(other_value);
766 if (this_type != other_type)
771 case TYPE_LIST_OF_VALUES:
772 if (this_value != other_value)
776 if (!(_record_equals(this_value, other_value, key_fields)))
779 case TYPE_LIST_OF_RECORDS:
780 if (this_value.length != other_value.length)
782 for (var j = 0; j < this_value.length; j++)
783 if (!(_record_equals(this_value[j], other_value[j], key_fields)))
791 record_equals: function(key_fields)
793 return function(other) {
794 return manifold._record_equals(this, other, key_fields);
798 _in_array: function(element, array, key_fields)
800 if (key_fields.length > 1) {
801 for (var i = 0; i < array.length; i++) {
802 if (manifold._record_equals(element, array[i], key_fields))
807 // XXX TODO If we have a dict, extract the key first
808 return ($.inArray(element, array) != -1);
812 /**************************************************************************
813 * Metadata management
814 **************************************************************************/
818 get_table: function(method) {
819 var table = MANIFOLD_METADATA[method];
820 return (typeof table === 'undefined') ? null : table;
823 get_columns: function(method) {
824 var table = this.get_table(method);
829 return (typeof table.column === 'undefined') ? null : table.column;
832 get_field_names: function(method)
834 var columns = this.get_columns(method);
837 return $.map(columns, function (x) { return x.name });
840 get_key: function(method) {
841 var table = this.get_table(method);
845 return (typeof table.key === 'undefined') ? null : table.key;
849 get_column: function(method, name) {
850 var columns = this.get_columns(method);
854 $.each(columns, function(i, c) {
861 get_type: function(method, name) {
862 var table = this.get_table(method);
866 var match = $.grep(table.column, function(x) { return x.name == name });
867 if (match.length == 0) {
870 return match[0].type;
872 return (typeof table.type === 'undefined') ? null : table.type;
877 /**************************************************************************
879 **************************************************************************/
881 query_store: new QueryStore(),
883 // XXX Remaining functions are deprecated since they are replaced by the query store
886 * Associative array storing the set of queries active on the page
892 * Insert a query in the global hash table associating uuids to queries.
893 * If the query has no been analyzed yet, let's do it.
894 * \fn insert_query(query)
896 * \param ManifoldQuery query Query to be added
898 insert_query : function (query) {
900 manifold.query_store.insert(query);
903 $(document).ready(function() {
904 manifold.run_query(query);
908 if (query.analyzed_query == null) {
909 query.analyze_subqueries();
911 manifold.all_queries[query.query_uuid]=query;
915 * Returns the query associated to a UUID
916 * \fn find_query(query_uuid)
918 * \param string query_uuid The UUID of the query to be returned
920 find_query : function (query_uuid) {
921 return manifold.all_queries[query_uuid];
924 /**************************************************************************
926 **************************************************************************/
928 // trigger a query asynchroneously
929 proxy_url : '/manifold/proxy/json/',
931 // reasonably low-noise, shows manifold requests coming in and out
932 asynchroneous_debug : true,
933 // print our more details on result publication and related callbacks
934 pubsub_debug : false,
937 * \brief We use js function closure to be able to pass the query (array)
938 * to the callback function used when data is received
940 success_closure: function(query, publish_uuid, callback) {
941 return function(data, textStatus) {
942 manifold.asynchroneous_success(data, query, publish_uuid, callback);
946 run_query: function(query, callback)
948 // default value for callback = null
949 if (typeof callback === 'undefined')
952 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
953 query_ext.query_state = QUERY_STATE_INPROGRESS;
955 var query_json = JSON.stringify(query);
957 // Inform plugins about the progress
958 query.iter_subqueries(function (sq) {
959 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
960 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
962 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
966 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
970 // Executes all async. queries - intended for the javascript header to initialize queries
971 // input queries are specified as a list of {'query_uuid': <query_uuid> }
972 // each plugin is responsible for managing its spinner through on_query_in_progress
973 asynchroneous_exec : function (query_exec_tuples) {
975 // Loop through input array, and use publish_uuid to publish back results
976 $.each(query_exec_tuples, function(index, tuple) {
977 var query=manifold.find_query(tuple.query_uuid);
978 var query_json=JSON.stringify (query);
979 var publish_uuid=tuple.publish_uuid;
980 // by default we publish using the same uuid of course
981 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
982 if (manifold.pubsub_debug) {
983 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
986 query.iter_subqueries(function (sq) {
987 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
990 // not quite sure what happens if we send a string directly, as POST data is named..
991 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
992 $.post(manifold.proxy_url, {'json':query_json},
993 manifold.success_closure(query, publish_uuid, tuple.callback));
998 * \brief Forward a query to the manifold backend
999 * \param query (dict) the query to be executed asynchronously
1000 * \param callback (function) the function to be called when the query terminates
1002 forward: function(query, callback) {
1003 var query_json = JSON.stringify(query);
1004 $.post(manifold.proxy_url, {'json': query_json} ,
1005 manifold.success_closure(query, query.query_uuid, callback));
1009 * Returns whether a query expects a unique results.
1010 * This is the case when the filters contain a key of the object
1011 * \fn query_expects_unique_result(query)
1012 * \memberof Manifold
1013 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
1015 query_expects_unique_result: function(query) {
1016 /* XXX we need functions to query metadata */
1017 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
1018 /* TODO requires keys in metadata */
1024 * \fn publish_result(query, results)
1025 * \memberof Manifold
1026 * \param ManifoldQuery query Query which has received results
1027 * \param array results results corresponding to query
1029 publish_result: function(query, result) {
1030 if (typeof result === 'undefined')
1034 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
1035 if (manifold.pubsub_debug)
1036 messages.debug(".. publish_result (1) ");
1038 $.each(result, function(i, record) {
1039 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
1042 if (manifold.pubsub_debug)
1043 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
1044 manifold.raise_record_event(query.query_uuid, DONE);
1045 if (manifold.pubsub_debug)
1046 messages.debug(".. publish_result (3) has used NEW API to say DONE");
1048 // OLD PLUGIN API BELOW
1049 /* Publish an update announce */
1050 var channel="/results/" + query.query_uuid + "/changed";
1051 if (manifold.pubsub_debug)
1052 messages.debug(".. publish_result (4) OLD API on channel" + channel);
1054 $.publish(channel, [result, query]);
1056 if (manifold.pubsub_debug)
1057 messages.debug(".. publish_result (5) END q=" + query.__repr());
1060 store_records: function(query, records) {
1062 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1063 if (query_ext.set_query_ext) {
1064 // We have a domain query
1065 // The results are stored in the corresponding set_query
1066 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1068 } else if (query_ext.domain_query_ext) {
1069 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1070 // Has it a domain query, and has it completed ?
1071 $.each(records, function(i, record) {
1072 var key = manifold.metadata.get_key(query.object);
1073 var record_key = manifold.record_get_value(record, key);
1074 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1078 // We have a normal query
1079 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1084 * Recursively publish result
1085 * \fn publish_result_rec(query, result)
1086 * \memberof Manifold
1087 * \param ManifoldQuery query Query which has received result
1088 * \param array result result corresponding to query
1090 * Note: this function works on the analyzed query
1092 publish_result_rec: function(query, records) {
1093 /* If the result is not unique, only publish the top query;
1094 * otherwise, publish the main object as well as subqueries
1095 * XXX how much recursive are we ?
1097 if (manifold.pubsub_debug)
1098 messages.debug (">>>>> publish_result_rec " + query.object);
1099 if (manifold.query_expects_unique_result(query)) {
1100 /* Also publish subqueries */
1101 $.each(query.subqueries, function(object, subquery) {
1102 manifold.publish_result_rec(subquery, records[0][object]);
1103 /* TODO remove object from result */
1106 if (manifold.pubsub_debug)
1107 messages.debug ("===== publish_result_rec " + query.object);
1109 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1110 query_ext.query_state = QUERY_STATE_DONE;
1112 this.store_records(query, records);
1116 if (query_ext.set_query_ext) {
1117 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1119 pub_query = query_ext.set_query_ext.query;
1120 } else if (query_ext.domain_query_ext) {
1121 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1127 // We can only publish results if the query (and its related domain query) is complete
1128 manifold.publish_result(pub_query, records);
1130 if (manifold.pubsub_debug)
1131 messages.debug ("<<<<< publish_result_rec " + query.object);
1134 setup_update_query: function(query, records)
1136 // We don't prepare an update query if the result has more than 1 entry
1137 if (records.length != 1)
1139 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1141 var record = records[0];
1143 var update_query_ext = query_ext.update_query_ext;
1145 if (!update_query_ext)
1148 var update_query = update_query_ext.query;
1149 var update_query_ext = query_ext.update_query_ext;
1150 var update_query_orig = query_ext.update_query_orig_ext.query;
1152 // Testing whether the result has subqueries (one level deep only)
1153 // iif the query has subqueries
1155 var obj = query.analyzed_query.subqueries;
1156 for (method in obj) {
1157 if (obj.hasOwnProperty(method)) {
1158 var key = manifold.metadata.get_key(method);
1162 var subrecords = record[method];
1165 $.each(subrecords, function (i, subrecord) {
1166 sq_keys.push(manifold.record_get_value(subrecord, key));
1168 update_query.params[method] = sq_keys;
1169 update_query_orig.params[method] = sq_keys.slice();
1175 update_query_ext.disabled = false;
1176 update_query_orig_ext.disabled = false;
1180 process_get_query_records: function(query, records) {
1181 this.setup_update_query(query, records);
1183 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1184 query_ext.query_state = QUERY_STATE_DONE;
1186 /* Publish full results */
1187 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1188 manifold.publish_result_rec(tmp_query, records);
1191 make_records: function(object, records)
1193 $.each(records, function(i, record) {
1194 manifold.make_record(object, record);
1198 make_record: function(object, record)
1200 // To make an object a record, we just add the hash function
1201 var key = manifold.metadata.get_key(object);
1202 record.hashCode = manifold.record_hashcode(key.sort());
1203 record.equals = manifold.record_equals(key);
1205 // Looking after subrecords
1206 for (var field in record) {
1207 var result_value = record[field];
1209 switch (this.get_type(result_value)) {
1211 var subobject = manifold.metadata.get_type(object, field);
1212 // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1213 if (subobject && subobject != 'string')
1214 manifold.make_record(subobject, result_value);
1216 case TYPE_LIST_OF_RECORDS:
1217 var subobject = manifold.metadata.get_type(object, field);
1219 manifold.make_records(subobject, result_value);
1227 * What we need to do when receiving results from an update query:
1228 * - differences between what we had, what we requested, and what we obtained
1229 * . what we had : update_query_orig (simple fields and set fields managed differently)
1230 * . what we requested : update_query
1231 * . what we received : records
1232 * - raise appropriate events
1234 * The normal process is that results similar to Get will be pushed in the
1235 * pubsub mechanism, thus repopulating everything while we only need
1236 * diff's. This means we need to move the publish functionalities in the
1237 * previous 'process_get_query_records' function.
1239 process_update_query_records: function(query, records) {
1240 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1241 var query_uuid = query.query_uuid;
1242 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1243 var update_query = query_ext.main_query_ext.update_query_ext.query;
1244 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1246 // Since we update objects one at a time, we can get the first record
1247 var record = records[0];
1249 // Let's iterate over the object properties
1250 for (var field in record) {
1251 var result_value = record[field];
1252 switch (this.get_type(result_value)) {
1254 // Did we ask for a change ?
1255 var update_value = update_query[field];
1257 // Not requested, if it has changed: OUT OF SYNC
1258 // How we can know ?
1259 // We assume it won't have changed
1263 throw "Internal error";
1269 value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1271 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1275 throw "Not implemented";
1279 case TYPE_LIST_OF_VALUES:
1280 // Same as list of records, but we don't have to extract keys
1282 // The rest of exactly the same (XXX factorize)
1283 var update_keys = update_query_orig.params[field];
1284 var query_keys = update_query.params[field];
1285 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1286 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1289 $.each(added_keys, function(i, key) {
1290 if ($.inArray(key, result_value) == -1) {
1292 request: FIELD_REQUEST_ADD,
1295 status: FIELD_REQUEST_FAILURE,
1299 request: FIELD_REQUEST_ADD,
1302 status: FIELD_REQUEST_SUCCESS,
1305 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1307 $.each(removed_keys, function(i, key) {
1308 if ($.inArray(key, result_keys) == -1) {
1310 request: FIELD_REQUEST_REMOVE,
1313 status: FIELD_REQUEST_SUCCESS,
1317 request: FIELD_REQUEST_REMOVE,
1320 status: FIELD_REQUEST_FAILURE,
1323 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1329 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1330 case TYPE_LIST_OF_RECORDS:
1331 var key, new_state, cur_query_uuid;
1333 cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1335 // example: slice.resource
1336 // - update_query_orig.params.resource = resources in slice before update
1337 // - update_query.params.resource = resource requested in slice
1338 // - keys from field = resources obtained
1340 if (field == 'lease') {
1341 // lease_id has been added to be repeated when
1342 // constructing request rspec. We don't want it for
1344 key = ['start_time', 'end_time', 'resource'];
1346 key = manifold.metadata.get_key(field);
1351 if (key.length > 1) {
1352 throw "Not implemented";
1358 /* XXX should be modified for multiple keys */
1359 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1361 // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1362 // what we had at the begining
1363 var update_keys = update_query_orig.params[field];
1365 var query_keys = update_query.params[field];
1366 // what we added and removed
1367 var added_keys = $.grep(query_keys, function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1368 var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys, key))); });
1370 // Send events related to parent query
1371 $.each(added_keys, function(i, added_key) {
1372 new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1374 // Update record state for children queries
1375 manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1377 // XXX This could be optimized
1378 manifold.query_store.recount(cur_query_uuid);
1380 data = { state: STATE_SET, key : field, op : new_state, value: added_key }
1381 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1383 // Inform subquery also
1385 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1386 // XXX Passing no parameters so that they can redraw everything would
1387 // be more efficient but is currently not supported
1388 // XXX We could also need to inform plugins about nodes IN (not pending) that are no more, etc.
1389 // XXX refactor all this when suppressing update_queries, and relying on state instead !
1391 $.each(removed_keys, function(i, removed_key) {
1392 new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1394 // Update record state for children queries
1395 manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1397 // XXX This could be optimized
1398 manifold.query_store.recount(cur_query_uuid);
1400 data = { state: STATE_SET, key : field, op : new_state, value: removed_key }
1401 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1403 // Inform subquery also
1405 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1412 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1413 this.setup_update_query(query, records);
1415 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1416 query_ext.query_state = QUERY_STATE_DONE;
1419 // Send DONE message to plugins
1420 query.iter_subqueries(function(sq, data, parent_query) {
1421 manifold.raise_record_event(sq.query_uuid, DONE);
1426 process_query_records: function(query, records) {
1427 if (query.action == 'get') {
1428 this.process_get_query_records(query, records);
1429 } else if (query.action == 'update') {
1430 this.process_update_query_records(query, records);
1434 // if set callback is provided it is called
1435 // most of the time publish_uuid will be query.query_uuid
1436 // however in some cases we wish to publish the result under a different uuid
1437 // e.g. an updater wants to publish its result as if from the original (get) query
1438 asynchroneous_success : function (data, query, publish_uuid, callback) {
1439 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1441 var start = new Date();
1442 if (manifold.asynchroneous_debug)
1443 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1445 if (data.code == 2) { // ERROR
1446 // We need to make sense of error codes here
1447 alert("Your session has expired, please log in again");
1448 localStorage.removeItem('user');
1449 window.location="/logout/";
1450 if (manifold.asynchroneous_debug) {
1451 duration=new Date()-start;
1452 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1456 if (data.code == 1) { // WARNING
1457 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1458 // publish error code and text message on a separate channel for whoever is interested
1460 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1464 // If a callback has been specified, we redirect results to it
1467 if (manifold.asynchroneous_debug) {
1468 duration=new Date()-start;
1469 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1474 if (manifold.asynchroneous_debug)
1475 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1477 // once everything is checked we can use the 'value' part of the manifoldresult
1478 var result=data.value;
1480 /* Eventually update the content of related queries (update, etc) */
1481 manifold.make_records(query.object, result);
1482 this.process_query_records(query, result);
1484 /* Publish results: disabled here, done in the previous call */
1485 //tmp_query = manifold.find_query(query.query_uuid);
1486 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1488 if (manifold.asynchroneous_debug) {
1489 duration=new Date()-start;
1490 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1495 /**************************************************************************
1496 * Plugin API helpers
1497 **************************************************************************/
1499 raise_event_handler: function(type, query_uuid, event_type, value) {
1500 if (manifold.pubsub_debug)
1501 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1502 if ((type != 'query') && (type != 'record'))
1503 throw 'Incorrect type for manifold.raise_event()';
1504 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1505 // this should be fixed upstream in manifold I expect
1506 if (query_uuid === undefined) {
1507 messages.warning("undefined query in raise_event_handler");
1511 // notify the change to objects that either listen to this channel specifically,
1512 // or to the wildcard channel
1513 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1515 $.each(channels, function(i, channel) {
1516 if (value === undefined) {
1517 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1518 $('.pubsub').trigger(channel, [event_type]);
1520 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1521 $('.pubsub').trigger(channel, [event_type, value]);
1526 raise_query_event: function(query_uuid, event_type, value) {
1527 manifold.raise_event_handler('query', query_uuid, event_type, value);
1530 raise_record_event: function(query_uuid, event_type, value) {
1531 manifold.raise_event_handler('record', query_uuid, event_type, value);
1535 * Event handler helpers
1537 _get_next_state_add: function(prev_state)
1539 switch (prev_state) {
1541 case STATE_SET_OUT_SUCCESS:
1542 case STATE_SET_IN_FAILURE:
1543 new_state = STATE_SET_IN_PENDING;
1546 case STATE_SET_OUT_PENDING:
1547 new_state = STATE_SET_IN;
1551 case STATE_SET_IN_PENDING:
1552 case STATE_SET_IN_SUCCESS:
1553 case STATE_SET_OUT_FAILURE:
1554 console.log("Inconsistent state: already in");
1560 _get_next_state_remove: function(prev_state)
1562 switch (prev_state) {
1564 case STATE_SET_IN_SUCCESS:
1565 case STATE_SET_OUT_FAILURE:
1566 new_state = STATE_SET_OUT_PENDING;
1569 case STATE_SET_IN_PENDING:
1570 new_state = STATE_SET_OUT;
1574 case STATE_SET_OUT_PENDING:
1575 case STATE_SET_OUT_SUCCESS:
1576 case STATE_SET_IN_FAILURE:
1577 console.log("Inconsistent state: already out");
1583 _grep_active_lease_callback: function(lease_query, resource_key) {
1584 return function(lease_key_lease) {
1585 var state, lease_key, lease;
1587 lease_key = lease_key_lease[0];
1588 lease = lease_key_lease[1];
1590 if (lease['resource'] != resource_key)
1593 state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1596 case STATE_SET_IN_PENDING:
1597 case STATE_SET_IN_SUCCESS:
1598 case STATE_SET_OUT_FAILURE:
1601 case STATE_SET_OUT_PENDING:
1602 case STATE_SET_OUT_SUCCESS:
1603 case STATE_SET_IN_FAILURE:
1609 _enforce_constraints: function(query_ext, record, record_key, event_type)
1613 query = query_ext.query;
1615 switch(query.object) {
1618 // CONSTRAINT_RESERVABLE_LEASE
1620 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1621 // XXX Not always a resource
1622 var is_reservable = (record.exclusive == true);
1623 if (is_reservable) {
1624 var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1626 if (event_type == STATE_SET_ADD) {
1627 // We should have a lease_query associated
1628 var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in options
1629 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1630 // Do we have lease records (in) with this resource
1631 var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, record_key));
1632 if (lease_records.length == 0) {
1634 // XXX Need for a better function to manage warnings
1635 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1636 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1638 // Lease are defined, delete the warning in case it was set previously
1639 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1642 // Remove warnings attached to this resource
1643 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1646 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1649 /* This was redundant */
1650 // manifold.query_store.recount(query.query_uuid);
1652 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1654 state: STATE_WARNINGS,
1659 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1663 var resource_key = record_key.resource;
1664 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1665 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1667 if (event_type == STATE_SET_ADD) {
1668 // A lease is added, it removes the constraint
1669 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1671 // A lease is removed, it might trigger the warning
1672 var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1673 if (lease_records.length == 0) { // XXX redundant cases
1675 // XXX Need for a better function to manage warnings
1676 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1677 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1679 // Lease are defined, delete the warning in case it was set previously
1680 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1685 manifold.query_store.recount(resource_query.query_uuid);
1687 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1689 state: STATE_WARNINGS,
1694 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1698 // -) When a lease is added, it might remove the warning associated to a reservable node
1700 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1701 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1703 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1704 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1706 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1710 _get_query_path: function(query_ext) {
1713 while (sq.parent_query_ext) {
1716 path = sq.query.object + path;
1717 sq = sq.parent_query_ext;
1724 * Handling events raised by plugins
1726 raise_event: function(query_uuid, event_type, data)
1728 var query, query_ext;
1730 // Query uuid has been updated with the key of a new element
1731 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1732 query = query_ext.query;
1734 switch(event_type) {
1736 // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1737 case FIELD_STATE_CHANGED:
1739 // value is an object (request, key, value, status)
1740 // update is only possible is the query is not pending, etc
1741 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1742 // we should map SET_ADD on this...
1744 // 1. Update internal query store about the change in status
1746 // 2. Update the update query
1747 update_query = query_ext.main_query_ext.update_query_ext.query;
1748 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1750 switch(data.state) {
1755 /* Set parameter data.key in the update_query to VALUE */
1756 if (update_query.params[data.key] === undefined)
1757 update_query.params[data.key] = Array();
1758 update_query.params[data.key] = value.value;
1765 var prev_state, new_state;
1766 var main_query, record, new_data, path;
1768 // We only track state in the analyzed query
1769 prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1770 if (prev_state === null)
1771 prev_state = STATE_SET_OUT;
1775 new_state = this._get_next_state_add(prev_state);
1777 /* data.value containts the resource key */
1778 manifold.query_store.add_record(query_uuid, data.value, new_state);
1779 record = manifold.query_store.get_record(query_uuid, data.value);
1780 this._enforce_constraints(query_ext, record, data.value, STATE_SET_ADD);
1782 /* Process update query in parent */
1783 path = this._get_query_path(query_ext);
1784 if (update_query.params[path] === undefined)
1785 update_query.params[path] = Array();
1786 update_query.params[path].push(data.value);
1790 case STATE_SET_REMOVE:
1791 new_state = this._get_next_state_remove(prev_state);
1793 /* data.value contains the resource key */
1794 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1795 record = manifold.query_store.get_record(query_uuid, data.value);
1796 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1798 /* Process update query in parent */
1799 path = this._get_query_path(query_ext);
1800 arr = update_query.params[path];
1802 var key = manifold.metadata.get_key(query.object);
1803 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1804 if (update_query.params[path] === undefined)
1805 update_query.params[path] = Array();
1806 update_query.params[path] = arr;
1810 /* Inform the parent query: important for update */
1817 main_query = query_ext.main_query_ext.query;
1818 manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1819 /* Propagate the event to other plugins subscribed to the query */
1820 manifold.query_store.recount(query_uuid);
1822 manifold.raise_record_event(query_uuid, event_type, new_data);
1827 // 3. Inform others about the change
1828 // a) the main query...
1829 manifold.raise_record_event(query_uuid, event_type, data);
1831 // b) subqueries eventually (dot in the key)
1834 var cur_query = query;
1835 if (cur_query.analyzed_query)
1836 cur_query = cur_query.analyzed_query;
1839 var path_array = data.key.split('.');
1840 var value_key = data.key.split('.');
1841 $.each(path_array, function(i, method) {
1842 cur_query = cur_query.subqueries[method];
1843 value_key.shift(); // XXX check that method is indeed shifted
1845 data.key = value_key;
1847 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1853 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1856 /* QUERY STATE CHANGED */
1861 console.log("FILTER ADDED", data);
1862 /* Update internal record state */
1863 manifold.query_store.add_filter(query_uuid, data);
1865 /* Propagate the message to plugins */
1866 manifold.raise_query_event(query_uuid, event_type, data);
1870 case FILTER_REMOVED:
1871 console.log("FILTER REMOVED", data);
1872 /* Update internal record state */
1873 manifold.query_store.remove_filter(query_uuid, data);
1875 /* Propagate the message to plugins */
1876 manifold.raise_query_event(query_uuid, event_type, data);
1881 main_query = query_ext.main_query_ext.query;
1882 main_update_query = query_ext.main_query_ext.update_query;
1885 // Here we need the full path through all subqueries
1887 // XXX We might need the query name in the QueryExt structure
1888 main_query.select(data);
1890 // XXX When is an update query associated ?
1891 // XXX main_update_query.select(value);
1893 manifold.raise_query_event(query_uuid, event_type, data);
1897 query = query_ext.query;
1898 main_query = query_ext.main_query_ext.query;
1899 main_update_query = query_ext.main_query_ext.update_query;
1900 query.unselect(data);
1901 main_query.unselect(data);
1903 // We need to inform about changes in these queries to the respective plugins
1904 // Note: query & main_query have the same UUID
1905 manifold.raise_query_event(query_uuid, event_type, data);
1908 // We need to inform about changes in these queries to the respective plugins
1909 // Note: query, main_query & update_query have the same UUID
1911 // http://trac.myslice.info/ticket/32
1912 // Avoid multiple calls to the same event
1913 //manifold.raise_query_event(query_uuid, event_type, value);
1915 // We are targeting the same object with get and update
1916 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1917 // NOTE: Editing a subquery == editing a local view on the destination
1919 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1920 // For the time being, we will collect all columns during the first query
1923 /* Publish/subscribe channels for internal use */
1924 get_channel: function(type, query_uuid) {
1925 if ((type !== 'query') && (type != 'record'))
1927 return '/' + type + '/' + query_uuid;
1930 }; // manifold object
1931 /* ------------------------------------------------------------ */
1935 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1936 // https://gist.github.com/661855
1938 $.subscribe = function( channel, selector, data, fn) {
1939 /* borrowed from jQuery */
1940 if ( data == null && fn == null ) {
1943 data = selector = undefined;
1944 } else if ( fn == null ) {
1945 if ( typeof selector === "string" ) {
1946 // ( channel, selector, fn )
1950 // ( channel, data, fn )
1953 selector = undefined;
1958 /* We use an indirection function that will clone the object passed in
1959 * parameter to the subscribe callback
1961 * FIXME currently we only clone query objects which are the only ones
1962 * supported and editable, we might have the same issue with results but
1963 * the page load time will be severely affected...
1965 o.on.apply(o, [channel, selector, data, function() {
1966 for(i = 1; i < arguments.length; i++) {
1967 if ( arguments[i].constructor.name == 'ManifoldQuery' )
1968 arguments[i] = arguments[i].clone();
1970 fn.apply(o, arguments);
1974 $.unsubscribe = function() {
1975 o.off.apply(o, arguments);
1978 $.publish = function() {
1979 o.trigger.apply(o, arguments);
1984 /* ------------------------------------------------------------ */
1986 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1987 //make sure to expose csrf in our outcoming ajax/post requests
1989 beforeSend: function(xhr, settings) {
1990 function getCookie(name) {
1991 var cookieValue = null;
1992 if (document.cookie && document.cookie != '') {
1993 var cookies = document.cookie.split(';');
1994 for (var i = 0; i < cookies.length; i++) {
1995 var cookie = jQuery.trim(cookies[i]);
1996 // Does this cookie string begin with the name we want?
1997 if (cookie.substring(0, name.length + 1) == (name + '=')) {
1998 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
2005 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
2006 // Only send the token to relative URLs i.e. locally.
2007 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));