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.fields = [];
247 update_query.analyzed_query.action = 'update';
248 update_query.params = {};
249 update_query_ext = new QueryExt(update_query);
251 /* We remember the original query to be able to reset it */
252 update_query_orig_ext = new QueryExt(update_query.clone());
255 /* We store the main query */
256 query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
257 manifold.query_store.main_queries[query.query_uuid] = query_ext;
258 /* Note: the update query does not have an entry! */
261 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
262 // XXX unless we have no subqueries ???
263 // we will complete with params when records are received... this has to be done by the manager
264 // SET_ADD, SET_REMOVE will change the status of the elements of the set
265 // UPDATE will change also, etc.
266 // XXX We need a proper structure to store this information...
268 // We also need to insert all queries and subqueries from the analyzed_query
269 // XXX We need the root of all subqueries
270 query.iter_subqueries(function(sq, data, parent_query) {
271 var parent_query_ext;
273 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
275 parent_query_ext = null;
277 // XXX parent_query_ext == false
278 // XXX main.subqueries = {} # Normal, we need analyzed_query
279 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
282 /* Let's issue a query for the subquery domain. This query will not need any update etc.
283 eg. for resources in a slice, we also query all resources */
284 var all_fields = manifold.metadata.get_field_names(sq.object);
285 var domain_query = new ManifoldQuery('get', sq.object, 'now', [], {}, all_fields);
286 //var domain_query = new ManifoldQuery('get', sq.object);
288 console.log("Created domain query", domain_query);
289 var domain_query_ext = new QueryExt(domain_query);
291 domain_query_ext.set_query_ext = sq_ext;
292 sq_ext.domain_query_ext = domain_query_ext;
294 // One of these two is useless ?
295 manifold.query_store.main_queries[domain_query.query_uuid] = domain_query_ext;
296 manifold.query_store.analyzed_queries[domain_query.query_uuid] = domain_query_ext;
298 // XXX This query is run before the plugins are initialized and listening
299 manifold.run_query(domain_query);
302 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
305 // XXX We have spurious update queries...
310 this.find_query_ext = function(query_uuid)
312 return this.main_queries[query_uuid];
315 this.find_query = function(query_uuid)
317 return this.find_query_ext(query_uuid).query;
320 this.find_analyzed_query_ext = function(query_uuid)
322 return this.analyzed_queries[query_uuid];
325 this.find_analyzed_query = function(query_uuid)
327 return this.find_analyzed_query_ext(query_uuid).query;
330 this.state_dict_create = function(default_set)
332 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
334 // We cannot use constants in literal definition, so...
335 state_dict[STATE_WARNINGS] = {};
336 state_dict[STATE_SET] = default_set;
337 state_dict[STATE_VISIBLE] = true;
343 this.set_records = function(query_uuid, records, default_set)
345 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
348 var key, object, query_ext, record_key;
350 query_ext = this.find_analyzed_query_ext(query_uuid);
351 object = query_ext.query.object;
352 if (object.indexOf(':') != -1) {
353 object = object.split(':')[1];
355 record_key = manifold.metadata.get_key(object);
357 // ["start_time", "resource", "end_time"]
360 $.each(records, function(i, record) {
361 //var key = manifold.metadata.get_key(query_ext.query.object);
363 var record_key_value = manifold.record_get_value(record, record_key);
364 query_ext.records.put(record_key_value, record);
366 if (!(query_ext.state.get(record_key_value)))
367 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
371 this.get_records = function(query_uuid)
373 var query_ext = this.find_analyzed_query_ext(query_uuid);
374 return query_ext.records.values();
377 this.get_record = function(query_uuid, record_key)
379 var query_ext = this.find_analyzed_query_ext(query_uuid);
380 return query_ext.records.get(record_key);
383 this.del_record = function(query_uuid, record_key)
385 var query_ext = this.find_analyzed_query_ext(query_uuid);
386 return query_ext.records.remove(record_key);
389 this.del_state = function(query_uuid, record_key)
391 var query_ext = this.find_analyzed_query_ext(query_uuid);
392 return query_ext.state.remove(record_key);
395 this.add_record = function(query_uuid, record, new_state)
397 var query_ext, key, record_key;
398 query_ext = this.find_analyzed_query_ext(query_uuid);
400 if (typeof(record) == 'object') {
401 key = manifold.metadata.get_key(query_ext.query.object);
402 record_key = manifold.record_get_value(record, key);
407 var record_entry = query_ext.records.get(record_key);
409 query_ext.records.put(record_key, record);
411 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
414 this.remove_record = function(query_uuid, record, new_state)
416 var query_ext, key, record_key;
417 query_ext = this.find_analyzed_query_ext(query_uuid);
419 if (typeof(record) == 'object') {
420 key = manifold.metadata.get_key(query_ext.query.object);
421 record_key = manifold.record_get_value(record, key);
426 if ((query_ext.query.object == 'lease') && (new_state == STATE_SET_OUT)) {
427 // Leases that are marked out are in fact leases from other slices
428 // We need to _remove_ leases that we mark as OUT
429 manifold.query_store.del_record(query_uuid, record_key);
430 manifold.query_store.del_state(query_uuid, record_key);
432 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
436 this.iter_records = function(query_uuid, callback)
438 var query_ext = this.find_analyzed_query_ext(query_uuid);
439 query_ext.records.each(callback);
440 //callback = function(record_key, record)
443 this.iter_visible_records = function(query_uuid, callback)
445 var query_ext = this.find_analyzed_query_ext(query_uuid);
446 query_ext.records.each(function(record_key, record) {
447 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
448 callback(record_key, record);
450 //callback = function(record_key, record)
456 this.set_record_state = function(query_uuid, result_key, state, value)
458 var query_ext = this.find_analyzed_query_ext(query_uuid);
459 var state_dict = query_ext.state.get(result_key);
461 state_dict = this.state_dict_create();
463 state_dict[state] = value;
465 query_ext.state.put(result_key, state_dict);
468 this.get_record_state = function(query_uuid, result_key, state)
470 var query_ext = this.find_analyzed_query_ext(query_uuid);
471 var state_dict = query_ext.state.get(result_key);
474 return state_dict[state];
479 this.add_filter = function(query_uuid, filter)
481 var query_ext = this.find_analyzed_query_ext(query_uuid);
482 // XXX When we update a filter
483 query_ext.filters.push(filter);
485 this.apply_filters(query_uuid);
489 this.update_filter = function(query_uuid, filter)
493 this.apply_filters(query_uuid);
496 this.remove_filter = function(query_uuid, filter)
498 var query_ext = this.find_analyzed_query_ext(query_uuid);
499 query_ext.filters = $.grep(query_ext.filters, function(x) {
500 return !(x.equals(filter));
503 this.apply_filters(query_uuid);
506 this.get_filters = function(query_uuid)
508 var query_ext = this.find_analyzed_query_ext(query_uuid);
509 return query_ext.filters;
512 this.recount = function(query_uuid)
515 var is_reserved, is_pending, in_set, is_unconfigured;
517 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
518 query_ext.num_pending = 0;
519 query_ext.num_unconfigured = 0;
521 this.iter_records(query_uuid, function(record_key, record) {
522 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
523 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
525 is_reserved = (record_state == STATE_SET_IN)
526 || (record_state == STATE_SET_OUT_PENDING)
527 || (record_state == STATE_SET_IN_SUCCESS)
528 || (record_state == STATE_SET_OUT_FAILURE);
530 is_pending = (record_state == STATE_SET_IN_PENDING)
531 || (record_state == STATE_SET_OUT_PENDING);
533 in_set = (record_state == STATE_SET_IN) // should not have warnings
534 || (record_state == STATE_SET_IN_PENDING)
535 || (record_state == STATE_SET_IN_SUCCESS)
536 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
538 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
540 /* Let's update num_pending and num_unconfigured at this stage */
542 query_ext.num_pending++;
544 query_ext.num_unconfigured++;
549 this.apply_filters = function(query_uuid)
551 var start = new Date().getTime();
553 // Toggle visibility of records according to the different filters.
556 var filters = this.get_filters(query_uuid);
558 /* Let's update num_pending and num_unconfigured at this stage */
560 // Adapted from querytable._querytable_filter()
562 this.iter_records(query_uuid, function(record_key, record) {
563 var is_reserved, is_pending, in_set, is_unconfigured;
565 /* By default, a record is visible unless a filter says the opposite */
568 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
569 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
571 is_reserved = (record_state == STATE_SET_IN)
572 || (record_state == STATE_SET_OUT_PENDING)
573 || (record_state == STATE_SET_IN_SUCCESS)
574 || (record_state == STATE_SET_OUT_FAILURE);
576 is_pending = (record_state == STATE_SET_IN_PENDING)
577 || (record_state == STATE_SET_OUT_PENDING);
579 in_set = (record_state == STATE_SET_IN) // should not have warnings
580 || (record_state == STATE_SET_IN_PENDING)
581 || (record_state == STATE_SET_IN_SUCCESS)
582 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
584 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
586 // We go through each filter and decide whether it affects the visibility of the record
587 $.each(filters, function(index, filter) {
590 var value = filter[2];
593 /* We do some special handling for the manifold:status filter
596 if (key == 'manifold:status') {
597 if (op != '=' && op != '==') {
598 // Unsupported filter, let's ignore it
599 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
600 return true; // ~ continue
605 // true => ~ continue
607 visible = is_reserved;
610 visible = is_unconfigured;
613 visible = is_pending;
616 return false; // ~ break
619 /* Normal filtering behaviour (according to the record content) follows... */
620 col_value = manifold.record_get_value(record, key);
622 // When the filter does not match, we hide the column by default
623 if (col_value === 'undefined') {
625 return false; // ~ break
628 // XXX This should accept pluggable filtering functions.
631 /* Test whether current filter is compatible with the column */
632 if (op == '=' || op == '==') {
633 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
636 }else if (op == 'included') {
637 /* By default, the filter returns false unless the record
638 * field match at least one value of the included statement
641 $.each(value, function(i,x) {
644 return false; // ~ break
647 }else if (op == '!=') {
648 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
651 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
654 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
656 } else if(op=='<=' || op=='≤') {
657 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
659 } else if(op=='>=' || op=='≥') {
660 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
663 // How to break out of a loop ?
664 alert("filter not supported");
665 return false; // break
670 // Set the visibility status in the query store
671 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
674 var end = new Date().getTime();
675 console.log("APPLY FILTERS [", filters, "] took", end - start, "ms");
682 * This namespace holds functions for globally managing query objects
687 /**************************************************************************
689 **************************************************************************/
693 get_type: function(variable) {
694 switch(Object.toType(variable)) {
701 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
702 return TYPE_LIST_OF_RECORDS;
704 return TYPE_LIST_OF_VALUES;
710 * fields: A String instance (field name), or a set of String instances
711 * (field names) # XXX tuple !!
713 * If fields is a String, return the corresponding value.
714 * If fields is a set, return a tuple of corresponding value.
717 * KeyError if at least one of the fields is not found
719 record_get_value: function(record, fields)
721 if (typeof(fields) === 'string') {
722 if (fields.indexOf('.') != -1) {
723 key_subkey = key.split('.', 2);
725 subkey = key_subkey[1];
727 if (record.indexOf(key) == -1) {
730 // Tests if the following is an array (typeof would give object)
731 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
733 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
734 } else if (typeof(record) == 'object') {
736 return manifold.record_get_value(record[key], subkey);
738 console.log('Unknown field');
740 // FIX if the record contains a string instead of a key:value
741 // example: select resource, slice_hrn from slice where slice_hrn=='xxx'
742 // Result will be {slice_hrn:'xxx', resource:'urn+zzz'}
743 // We don't have this resource:{urn:'urn+zzz'}
744 } else if(typeof(record) === 'string'){
747 return record[fields];
750 // see. get_map_entries
751 if (fields.length == 1)
752 return manifold.record_get_value(record, fields[0])
754 // Build a new record
756 $.each(fields, function(i, field) {
757 ret[field] = manifold.record_get_value(record, field);
759 ret.hashCode = record.hashCode;
760 ret.equals = record.equals;
762 // this was an array, we want a dictionary
763 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
768 record_hashcode: function(key_fields)
772 for (var i=0; i < key_fields.length; i++)
773 ret += "@@" + this[key_fields[i]];
778 _record_equals: function(self, other, key_fields)
780 if ((typeof self === "string") && (typeof other === "string")) {
781 return self == other;
783 for (var i=0; i < key_fields.length; i++) {
784 var this_value = self[key_fields[i]];
785 var other_value = other[key_fields[i]];
787 var this_type = manifold.get_type(this_value);
788 var other_type = manifold.get_type(other_value);
789 if (this_type != other_type)
794 case TYPE_LIST_OF_VALUES:
795 case TYPE_LIST_OF_RECORDS:
796 if (this_value != other_value)
800 if (!(_record_equals(this_value, other_value, key_fields)))
804 XXX WARNING = disabled for OpenFlow plugin !!!
806 case TYPE_LIST_OF_RECORDS:
807 if (this_value.length != other_value.length)
809 for (var j = 0; j < this_value.length; j++)
810 if (!(_record_equals(this_value[j], other_value[j], key_fields)))
819 record_equals: function(key_fields)
821 return function(other) {
822 return manifold._record_equals(this, other, key_fields);
826 _in_array: function(element, array, key_fields)
828 if (key_fields.length > 1) {
829 for (var i = 0; i < array.length; i++) {
830 if (manifold._record_equals(element, array[i], key_fields))
835 // XXX TODO If we have a dict, extract the key first
836 return ($.inArray(element, array) != -1);
840 /**************************************************************************
841 * Metadata management
842 **************************************************************************/
846 get_table: function(method) {
847 var table = MANIFOLD_METADATA[method];
848 return (typeof table === 'undefined') ? null : table;
851 get_columns: function(method) {
852 var table = this.get_table(method);
857 return (typeof table.column === 'undefined') ? null : table.column;
860 get_field_names: function(method)
862 var columns = this.get_columns(method);
865 return $.map(columns, function (x) { return x.name });
868 get_key: function(method) {
869 var table = this.get_table(method);
873 return (typeof table.key === 'undefined') ? null : table.key;
877 get_column: function(method, name) {
878 var columns = this.get_columns(method);
882 $.each(columns, function(i, c) {
889 get_type: function(method, name) {
890 var table = this.get_table(method);
894 var match = $.grep(table.column, function(x) { return x.name == name });
895 if (match.length == 0) {
898 return match[0].type;
900 return (typeof table.type === 'undefined') ? null : table.type;
905 /**************************************************************************
907 **************************************************************************/
909 query_store: new QueryStore(),
911 // XXX Remaining functions are deprecated since they are replaced by the query store
914 * Associative array storing the set of queries active on the page
920 * Insert a query in the global hash table associating uuids to queries.
921 * If the query has no been analyzed yet, let's do it.
922 * \fn insert_query(query)
924 * \param ManifoldQuery query Query to be added
926 insert_query : function (query) {
928 manifold.query_store.insert(query);
931 $(document).ready(function() {
932 manifold.run_query(query);
936 if (query.analyzed_query == null) {
937 query.analyze_subqueries();
939 manifold.all_queries[query.query_uuid]=query;
943 * Returns the query associated to a UUID
944 * \fn find_query(query_uuid)
946 * \param string query_uuid The UUID of the query to be returned
948 find_query : function (query_uuid) {
949 return manifold.all_queries[query_uuid];
952 /**************************************************************************
954 **************************************************************************/
956 // trigger a query asynchroneously
957 proxy_url : '/manifold/proxy/json/',
959 // reasonably low-noise, shows manifold requests coming in and out
960 asynchroneous_debug : true,
961 // print our more details on result publication and related callbacks
962 pubsub_debug : false,
965 * \brief We use js function closure to be able to pass the query (array)
966 * to the callback function used when data is received
968 success_closure: function(query, publish_uuid, callback) {
969 return function(data, textStatus) {
970 manifold.asynchroneous_success(data, query, publish_uuid, callback);
974 run_query: function(query, callback)
976 // default value for callback = null
977 if (typeof callback === 'undefined')
980 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
981 query_ext.query_state = QUERY_STATE_INPROGRESS;
984 If the Query object concerns SFA AM objects, iterate on each AM platform
985 Loop per platform, allows a progressive loading per AM platform
986 Update is run on all platforms at the same time to get a final answer, we don't manage partial answers yet...
988 // Removed slice from the per platform query - it's quick enough...
989 if((query.object == 'resource' || query.object == 'lease') && query.action != "update"){
990 var obj = query.object;
991 $.post("/rest/platform/", function( data ) {
992 $.each(data, function(index, p) {
993 query.object = p.platform+":"+obj;
994 var query_json = JSON.stringify(query);
996 // Inform plugins about the progress
997 query.iter_subqueries(function (sq) {
998 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
999 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
1000 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
1003 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
1009 var query_json = JSON.stringify(query);
1011 // Inform plugins about the progress
1012 query.iter_subqueries(function (sq) {
1013 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
1014 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
1015 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
1018 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
1024 // Executes all async. queries - intended for the javascript header to initialize queries
1025 // input queries are specified as a list of {'query_uuid': <query_uuid> }
1026 // each plugin is responsible for managing its spinner through on_query_in_progress
1027 asynchroneous_exec : function (query_exec_tuples) {
1029 // Loop through input array, and use publish_uuid to publish back results
1030 $.each(query_exec_tuples, function(index, tuple) {
1031 var query=manifold.find_query(tuple.query_uuid);
1032 var query_json=JSON.stringify (query);
1033 var publish_uuid=tuple.publish_uuid;
1034 // by default we publish using the same uuid of course
1035 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
1036 if (manifold.pubsub_debug) {
1037 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
1040 query.iter_subqueries(function (sq) {
1041 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
1044 // not quite sure what happens if we send a string directly, as POST data is named..
1045 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
1046 $.post(manifold.proxy_url, {'json':query_json},
1047 manifold.success_closure(query, publish_uuid, tuple.callback));
1052 * \brief Forward a query to the manifold backend
1053 * \param query (dict) the query to be executed asynchronously
1054 * \param callback (function) the function to be called when the query terminates
1056 forward: function(query, callback) {
1057 var query_json = JSON.stringify(query);
1058 $.post(manifold.proxy_url, {'json': query_json} ,
1059 manifold.success_closure(query, query.query_uuid, callback));
1063 * Returns whether a query expects a unique results.
1064 * This is the case when the filters contain a key of the object
1065 * \fn query_expects_unique_result(query)
1066 * \memberof Manifold
1067 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
1069 query_expects_unique_result: function(query) {
1070 /* XXX we need functions to query metadata */
1071 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
1072 /* TODO requires keys in metadata */
1078 * \fn publish_result(query, results)
1079 * \memberof Manifold
1080 * \param ManifoldQuery query Query which has received results
1081 * \param array results results corresponding to query
1083 publish_result: function(query, result) {
1084 if (typeof result === 'undefined')
1088 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
1089 if (manifold.pubsub_debug)
1090 messages.debug(".. publish_result (1) ");
1092 $.each(result, function(i, record) {
1093 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
1096 if (manifold.pubsub_debug)
1097 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
1098 manifold.raise_record_event(query.query_uuid, DONE);
1099 if (manifold.pubsub_debug)
1100 messages.debug(".. publish_result (3) has used NEW API to say DONE");
1102 // OLD PLUGIN API BELOW
1103 /* Publish an update announce */
1104 var channel="/results/" + query.query_uuid + "/changed";
1105 if (manifold.pubsub_debug)
1106 messages.debug(".. publish_result (4) OLD API on channel" + channel);
1108 $.publish(channel, [result, query]);
1110 if (manifold.pubsub_debug)
1111 messages.debug(".. publish_result (5) END q=" + query.__repr());
1114 store_records: function(query, records) {
1116 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1117 if (query_ext.set_query_ext) {
1118 // We have a domain query
1119 // The results are stored in the corresponding set_query
1120 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1122 } else if (query_ext.domain_query_ext) {
1123 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1124 // Has it a domain query, and has it completed ?
1125 $.each(records, function(i, record) {
1126 var key = manifold.metadata.get_key(query.object);
1127 if ( typeof record === "string" ){
1128 var record_key = record;
1130 var record_key = manifold.record_get_value(record, key);
1132 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1136 // We have a normal query
1137 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1142 * Recursively publish result
1143 * \fn publish_result_rec(query, result)
1144 * \memberof Manifold
1145 * \param ManifoldQuery query Query which has received result
1146 * \param array result result corresponding to query
1148 * Note: this function works on the analyzed query
1150 publish_result_rec: function(query, records) {
1151 /* If the result is not unique, only publish the top query;
1152 * otherwise, publish the main object as well as subqueries
1153 * XXX how much recursive are we ?
1155 if (manifold.pubsub_debug)
1156 messages.debug (">>>>> publish_result_rec " + query.object);
1157 if (manifold.query_expects_unique_result(query)) {
1158 /* Also publish subqueries */
1159 $.each(query.subqueries, function(object, subquery) {
1160 manifold.publish_result_rec(subquery, records[0][object]);
1161 /* TODO remove object from result */
1164 if (manifold.pubsub_debug)
1165 messages.debug ("===== publish_result_rec " + query.object);
1167 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1168 query_ext.query_state = QUERY_STATE_DONE;
1170 this.store_records(query, records);
1174 if (query_ext.set_query_ext) {
1175 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1177 pub_query = query_ext.set_query_ext.query;
1178 } else if (query_ext.domain_query_ext) {
1179 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1185 // We can only publish results if the query (and its related domain query) is complete
1186 manifold.publish_result(pub_query, records);
1188 if (manifold.pubsub_debug)
1189 messages.debug ("<<<<< publish_result_rec " + query.object);
1192 setup_update_query: function(query, records)
1194 // We don't prepare an update query if the result has more than 1 entry
1195 if (records.length != 1)
1197 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1199 var record = records[0];
1201 var update_query_ext = query_ext.update_query_ext;
1203 if (!update_query_ext)
1206 var update_query = update_query_ext.query;
1207 var update_query_ext = query_ext.update_query_ext;
1208 var update_query_orig = query_ext.update_query_orig_ext.query;
1210 // Testing whether the result has subqueries (one level deep only)
1211 // iif the query has subqueries
1213 var obj = query.analyzed_query.subqueries;
1214 for (method in obj) {
1215 if (obj.hasOwnProperty(method)) {
1216 var key = manifold.metadata.get_key(method);
1220 var subrecords = record[method];
1223 $.each(subrecords, function (i, subrecord) {
1224 sq_keys.push(manifold.record_get_value(subrecord, key));
1226 update_query.params[method] = sq_keys;
1227 update_query_orig.params[method] = sq_keys.slice();
1233 update_query_ext.disabled = false;
1234 update_query_orig_ext.disabled = false;
1238 process_get_query_records: function(query, records) {
1239 this.setup_update_query(query, records);
1241 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1242 query_ext.query_state = QUERY_STATE_DONE;
1244 /* Publish full results */
1245 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1246 manifold.publish_result_rec(tmp_query, records);
1249 make_records: function(object, records)
1251 $.each(records, function(i, record) {
1252 manifold.make_record(object, record);
1256 make_record: function(object, record)
1258 // To make an object a record, we just add the hash function
1259 var key, new_object;
1261 if (object.indexOf(':') != -1) {
1262 new_object = object.split(':')[1];
1264 new_object = object;
1267 key = manifold.metadata.get_key(new_object);
1269 console.log("object type: " + new_object + " has no key");
1270 console.log(record);
1273 record.hashCode = manifold.record_hashcode(key.sort());
1274 record.equals = manifold.record_equals(key);
1276 // Looking after subrecords
1277 for (var field in record) {
1278 var result_value = record[field];
1280 switch (this.get_type(result_value)) {
1282 var subobject = manifold.metadata.get_type(object, field);
1283 // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1284 if (subobject && subobject != 'string')
1285 manifold.make_record(subobject, result_value);
1287 case TYPE_LIST_OF_RECORDS:
1288 var subobject = manifold.metadata.get_type(object, field);
1290 manifold.make_records(subobject, result_value);
1298 * What we need to do when receiving results from an update query:
1299 * - differences between what we had, what we requested, and what we obtained
1300 * . what we had : update_query_orig (simple fields and set fields managed differently)
1301 * . what we requested : update_query
1302 * . what we received : records
1303 * - raise appropriate events
1305 * The normal process is that results similar to Get will be pushed in the
1306 * pubsub mechanism, thus repopulating everything while we only need
1307 * diff's. This means we need to move the publish functionalities in the
1308 * previous 'process_get_query_records' function.
1310 process_update_query_records: function(query, records) {
1311 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1312 var query_uuid = query.query_uuid;
1313 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1314 var update_query = query_ext.main_query_ext.update_query_ext.query;
1315 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1317 // Since we update objects one at a time, we can get the first record
1318 var record = records[0];
1320 // Let's iterate over the object properties
1321 for (var field in record) {
1322 var result_value = record[field];
1323 switch (this.get_type(result_value)) {
1325 // Did we ask for a change ?
1326 var update_value = update_query[field];
1328 // Not requested, if it has changed: OUT OF SYNC
1329 // How we can know ?
1330 // We assume it won't have changed
1334 throw "Internal error";
1340 value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1342 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1346 throw "Not implemented";
1350 case TYPE_LIST_OF_VALUES:
1351 // Same as list of records, but we don't have to extract keys
1353 // The rest of exactly the same (XXX factorize)
1354 var update_keys = update_query_orig.params[field];
1355 var query_keys = update_query.params[field];
1356 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1357 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1360 $.each(added_keys, function(i, key) {
1361 if ($.inArray(key, result_value) == -1) {
1363 request: FIELD_REQUEST_ADD,
1366 status: FIELD_REQUEST_FAILURE,
1370 request: FIELD_REQUEST_ADD,
1373 status: FIELD_REQUEST_SUCCESS,
1376 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1378 $.each(removed_keys, function(i, key) {
1379 if ($.inArray(key, result_keys) == -1) {
1381 request: FIELD_REQUEST_REMOVE,
1384 status: FIELD_REQUEST_SUCCESS,
1388 request: FIELD_REQUEST_REMOVE,
1391 status: FIELD_REQUEST_FAILURE,
1394 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1400 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1401 case TYPE_LIST_OF_RECORDS:
1402 var key, new_state, cur_query_uuid;
1403 if($.inArray(field,Object.keys(query.analyzed_query.subqueries)) > -1){
1404 cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1407 // example: slice.resource
1408 // - update_query_orig.params.resource = resources in slice before update
1409 // - update_query.params.resource = resource requested in slice
1410 // - keys from field = resources obtained
1412 if (field == 'lease') {
1413 // lease_id has been added to be repeated when
1414 // constructing request rspec. We don't want it for
1416 key = ['start_time', 'end_time', 'resource'];
1418 key = manifold.metadata.get_key(field);
1423 if (key.length > 1) {
1424 throw "Not implemented";
1430 /* XXX should be modified for multiple keys */
1431 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1433 // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1434 // what we had at the begining
1435 var update_keys = update_query_orig.params[field];
1437 var query_keys = update_query.params[field];
1438 // what we added and removed
1439 var added_keys = $.grep(query_keys, function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1440 var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys, key))); });
1442 // Send events related to parent query
1443 $.each(added_keys, function(i, added_key) {
1444 new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1446 // Update record state for children queries
1447 manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1449 // XXX This could be optimized
1450 manifold.query_store.recount(cur_query_uuid);
1452 data = { state: STATE_SET, key : field, op : new_state, value: added_key }
1453 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1455 // Inform subquery also
1457 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1458 // XXX Passing no parameters so that they can redraw everything would
1459 // be more efficient but is currently not supported
1460 // XXX We could also need to inform plugins about nodes IN (not pending) that are no more, etc.
1461 // XXX refactor all this when suppressing update_queries, and relying on state instead !
1463 $.each(removed_keys, function(i, removed_key) {
1464 new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1466 // Update record state for children queries
1467 manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1469 // XXX This could be optimized
1470 manifold.query_store.recount(cur_query_uuid);
1472 data = { state: STATE_SET, key : field, op : new_state, value: removed_key }
1473 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1475 // Inform subquery also
1477 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1484 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1485 this.setup_update_query(query, records);
1487 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1488 query_ext.query_state = QUERY_STATE_DONE;
1490 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1491 manifold.publish_result_rec(tmp_query, records);
1493 // Send DONE message to plugins
1494 query.iter_subqueries(function(sq, data, parent_query) {
1495 manifold.raise_record_event(sq.query_uuid, DONE);
1500 process_query_records: function(query, records) {
1501 if (query.action == 'get') {
1502 this.process_get_query_records(query, records);
1503 } else if (query.action == 'update') {
1504 this.process_update_query_records(query, records);
1508 // if set callback is provided it is called
1509 // most of the time publish_uuid will be query.query_uuid
1510 // however in some cases we wish to publish the result under a different uuid
1511 // e.g. an updater wants to publish its result as if from the original (get) query
1512 asynchroneous_success : function (data, query, publish_uuid, callback) {
1513 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1515 var start = new Date();
1516 if (manifold.asynchroneous_debug)
1517 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1519 if (data.code == 2) { // ERROR
1520 // We need to make sense of error codes here
1521 alert("Your session has expired, please log in again");
1522 localStorage.removeItem('user');
1523 window.location="/logout/";
1524 if (manifold.asynchroneous_debug) {
1525 duration=new Date()-start;
1526 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1530 if (data.code == 1) { // WARNING
1531 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1532 // publish error code and text message on a separate channel for whoever is interested
1534 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1538 // If a callback has been specified, we redirect results to it
1541 if (manifold.asynchroneous_debug) {
1542 duration=new Date()-start;
1543 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1548 if (manifold.asynchroneous_debug)
1549 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1551 // once everything is checked we can use the 'value' part of the manifoldresult
1552 var result=data.value;
1554 /* Eventually update the content of related queries (update, etc) */
1555 manifold.make_records(query.object, result);
1556 this.process_query_records(query, result);
1558 /* Publish results: disabled here, done in the previous call */
1559 //tmp_query = manifold.find_query(query.query_uuid);
1560 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1562 if (manifold.asynchroneous_debug) {
1563 duration=new Date()-start;
1564 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1569 /**************************************************************************
1570 * Plugin API helpers
1571 **************************************************************************/
1573 raise_event_handler: function(type, query_uuid, event_type, value) {
1574 if (manifold.pubsub_debug)
1575 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1576 if ((type != 'query') && (type != 'record'))
1577 throw 'Incorrect type for manifold.raise_event()';
1578 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1579 // this should be fixed upstream in manifold I expect
1580 if (query_uuid === undefined) {
1581 messages.warning("undefined query in raise_event_handler");
1585 // notify the change to objects that either listen to this channel specifically,
1586 // or to the wildcard channel
1587 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1589 $.each(channels, function(i, channel) {
1590 if (value === undefined) {
1591 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1592 $('.pubsub').trigger(channel, [event_type]);
1594 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1595 $('.pubsub').trigger(channel, [event_type, value]);
1600 raise_query_event: function(query_uuid, event_type, value) {
1601 manifold.raise_event_handler('query', query_uuid, event_type, value);
1604 raise_record_event: function(query_uuid, event_type, value) {
1605 manifold.raise_event_handler('record', query_uuid, event_type, value);
1609 * Event handler helpers
1611 _get_next_state_add: function(prev_state)
1613 switch (prev_state) {
1615 case STATE_SET_OUT_SUCCESS:
1616 case STATE_SET_IN_FAILURE:
1617 new_state = STATE_SET_IN_PENDING;
1620 case STATE_SET_OUT_PENDING:
1621 new_state = STATE_SET_IN;
1625 case STATE_SET_IN_PENDING:
1626 case STATE_SET_IN_SUCCESS:
1627 case STATE_SET_OUT_FAILURE:
1628 console.log("Inconsistent state: already in");
1634 _get_next_state_remove: function(prev_state)
1636 switch (prev_state) {
1638 case STATE_SET_IN_SUCCESS:
1639 case STATE_SET_OUT_FAILURE:
1640 new_state = STATE_SET_OUT_PENDING;
1643 case STATE_SET_IN_PENDING:
1644 new_state = STATE_SET_OUT;
1648 case STATE_SET_OUT_PENDING:
1649 case STATE_SET_OUT_SUCCESS:
1650 case STATE_SET_IN_FAILURE:
1651 console.log("Inconsistent state: already out");
1657 _grep_active_lease_callback: function(lease_query, resource_key) {
1658 return function(lease_key_lease) {
1659 var state, lease_key, lease;
1661 lease_key = lease_key_lease[0];
1662 lease = lease_key_lease[1];
1664 if (lease['resource'] != resource_key)
1667 state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1670 case STATE_SET_IN_PENDING:
1671 case STATE_SET_IN_SUCCESS:
1672 case STATE_SET_OUT_FAILURE:
1675 case STATE_SET_OUT_PENDING:
1676 case STATE_SET_OUT_SUCCESS:
1677 case STATE_SET_IN_FAILURE:
1683 _enforce_constraints: function(query_ext, record, record_key, event_type)
1687 query = query_ext.query;
1689 switch(query.object) {
1692 // CONSTRAINT_RESERVABLE_LEASE
1694 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1695 // XXX Not always a resource
1696 var is_reservable = (record.exclusive == true);
1697 if (is_reservable) {
1698 var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1700 if (event_type == STATE_SET_ADD) {
1701 // We should have a lease_query associated
1702 var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in options
1703 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1704 // Do we have lease records (in) with this resource
1705 var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, record_key));
1706 if (lease_records.length == 0) {
1708 // XXX Need for a better function to manage warnings
1709 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1710 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1712 // Lease are defined, delete the warning in case it was set previously
1713 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1716 // Remove warnings attached to this resource
1717 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1720 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1723 /* This was redundant */
1724 // manifold.query_store.recount(query.query_uuid);
1726 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1728 state: STATE_WARNINGS,
1733 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1737 var resource_key = record_key.resource;
1738 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1739 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1741 if (event_type == STATE_SET_ADD) {
1742 // A lease is added, it removes the constraint
1743 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1745 // A lease is removed, it might trigger the warning
1746 var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1747 if (lease_records.length == 0) { // XXX redundant cases
1749 // XXX Need for a better function to manage warnings
1750 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1751 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1753 // Lease are defined, delete the warning in case it was set previously
1754 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1759 manifold.query_store.recount(resource_query.query_uuid);
1761 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1763 state: STATE_WARNINGS,
1768 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1772 // -) When a lease is added, it might remove the warning associated to a reservable node
1774 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1775 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1777 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1778 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1780 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1784 _get_query_path: function(query_ext) {
1787 while (sq.parent_query_ext) {
1790 path = sq.query.object + path;
1791 sq = sq.parent_query_ext;
1798 * Handling events raised by plugins
1800 raise_event: function(query_uuid, event_type, data)
1802 var query, query_ext;
1804 // Query uuid has been updated with the key of a new element
1805 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1806 query = query_ext.query;
1808 switch(event_type) {
1810 // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1811 case FIELD_STATE_CHANGED:
1813 // value is an object (request, key, value, status)
1814 // update is only possible is the query is not pending, etc
1815 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1816 // we should map SET_ADD on this...
1818 // 1. Update internal query store about the change in status
1820 // 2. Update the update query
1821 update_query = query_ext.main_query_ext.update_query_ext.query;
1822 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1824 switch(data.state) {
1829 /* Set parameter data.key in the update_query to VALUE */
1830 if (update_query.params[data.key] === undefined)
1831 update_query.params[data.key] = Array();
1832 update_query.params[data.key] = value.value;
1839 var prev_state, new_state;
1840 var main_query, record, new_data, path;
1842 // We only track state in the analyzed query
1843 prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1844 if (prev_state === null)
1845 prev_state = STATE_SET_OUT;
1849 new_state = this._get_next_state_add(prev_state);
1851 /* data.value containts the resource key */
1852 manifold.query_store.add_record(query_uuid, data.value, new_state);
1853 record = manifold.query_store.get_record(query_uuid, data.value);
1854 this._enforce_constraints(query_ext, record, data.value, STATE_SET_ADD);
1856 /* Process update query in parent */
1857 path = this._get_query_path(query_ext);
1858 if (update_query.params[path] === undefined)
1859 update_query.params[path] = Array();
1860 update_query.params[path].push(data.value);
1864 case STATE_SET_REMOVE:
1865 new_state = this._get_next_state_remove(prev_state);
1867 /* data.value contains the resource key */
1868 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1869 record = manifold.query_store.get_record(query_uuid, data.value);
1870 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1872 /* Process update query in parent */
1873 path = this._get_query_path(query_ext);
1874 arr = update_query.params[path];
1876 var key = manifold.metadata.get_key(query.object);
1877 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1878 if (update_query.params[path] === undefined)
1879 update_query.params[path] = Array();
1880 update_query.params[path] = arr;
1884 /* Inform the parent query: important for update */
1891 main_query = query_ext.main_query_ext.query;
1892 manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1893 /* Propagate the event to other plugins subscribed to the query */
1894 manifold.query_store.recount(query_uuid);
1896 manifold.raise_record_event(query_uuid, event_type, new_data);
1901 // 3. Inform others about the change
1902 // a) the main query...
1903 manifold.raise_record_event(query_uuid, event_type, data);
1905 // b) subqueries eventually (dot in the key)
1908 var cur_query = query;
1909 if (cur_query.analyzed_query)
1910 cur_query = cur_query.analyzed_query;
1913 var path_array = data.key.split('.');
1914 var value_key = data.key.split('.');
1915 $.each(path_array, function(i, method) {
1916 cur_query = cur_query.subqueries[method];
1917 value_key.shift(); // XXX check that method is indeed shifted
1919 data.key = value_key;
1921 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1927 query_ext.main_query_ext.update_query_ext.query.fields = [];
1928 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1931 /* QUERY STATE CHANGED */
1936 console.log("FILTER ADDED", data);
1937 /* Update internal record state */
1938 manifold.query_store.add_filter(query_uuid, data);
1940 /* Propagate the message to plugins */
1941 manifold.raise_query_event(query_uuid, event_type, data);
1945 case FILTER_REMOVED:
1946 console.log("FILTER REMOVED", data);
1947 /* Update internal record state */
1948 manifold.query_store.remove_filter(query_uuid, data);
1950 /* Propagate the message to plugins */
1951 manifold.raise_query_event(query_uuid, event_type, data);
1956 main_query = query_ext.main_query_ext.query;
1957 main_update_query = query_ext.main_query_ext.update_query;
1960 // Here we need the full path through all subqueries
1962 // XXX We might need the query name in the QueryExt structure
1963 main_query.select(data);
1965 // XXX When is an update query associated ?
1966 // XXX main_update_query.select(value);
1968 manifold.raise_query_event(query_uuid, event_type, data);
1972 query = query_ext.query;
1973 main_query = query_ext.main_query_ext.query;
1974 main_update_query = query_ext.main_query_ext.update_query;
1975 query.unselect(data);
1976 main_query.unselect(data);
1978 // We need to inform about changes in these queries to the respective plugins
1979 // Note: query & main_query have the same UUID
1980 manifold.raise_query_event(query_uuid, event_type, data);
1983 // We need to inform about changes in these queries to the respective plugins
1984 // Note: query, main_query & update_query have the same UUID
1986 // http://trac.myslice.info/ticket/32
1987 // Avoid multiple calls to the same event
1988 //manifold.raise_query_event(query_uuid, event_type, value);
1990 // We are targeting the same object with get and update
1991 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1992 // NOTE: Editing a subquery == editing a local view on the destination
1994 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1995 // For the time being, we will collect all columns during the first query
1998 /* Publish/subscribe channels for internal use */
1999 get_channel: function(type, query_uuid) {
2000 if ((type !== 'query') && (type != 'record'))
2002 return '/' + type + '/' + query_uuid;
2005 }; // manifold object
2006 /* ------------------------------------------------------------ */
2010 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
2011 // https://gist.github.com/661855
2013 $.subscribe = function( channel, selector, data, fn) {
2014 /* borrowed from jQuery */
2015 if ( data == null && fn == null ) {
2018 data = selector = undefined;
2019 } else if ( fn == null ) {
2020 if ( typeof selector === "string" ) {
2021 // ( channel, selector, fn )
2025 // ( channel, data, fn )
2028 selector = undefined;
2033 /* We use an indirection function that will clone the object passed in
2034 * parameter to the subscribe callback
2036 * FIXME currently we only clone query objects which are the only ones
2037 * supported and editable, we might have the same issue with results but
2038 * the page load time will be severely affected...
2040 o.on.apply(o, [channel, selector, data, function() {
2041 for(i = 1; i < arguments.length; i++) {
2042 if ( arguments[i].constructor.name == 'ManifoldQuery' )
2043 arguments[i] = arguments[i].clone();
2045 fn.apply(o, arguments);
2049 $.unsubscribe = function() {
2050 o.off.apply(o, arguments);
2053 $.publish = function() {
2054 o.trigger.apply(o, arguments);
2059 /* ------------------------------------------------------------ */
2061 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
2062 //make sure to expose csrf in our outcoming ajax/post requests
2064 beforeSend: function(xhr, settings) {
2065 function getCookie(name) {
2066 var cookieValue = null;
2067 if (document.cookie && document.cookie != '') {
2068 var cookies = document.cookie.split(';');
2069 for (var i = 0; i < cookies.length; i++) {
2070 var cookie = jQuery.trim(cookies[i]);
2071 // Does this cookie string begin with the name we want?
2072 if (cookie.substring(0, name.length + 1) == (name + '=')) {
2073 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
2080 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
2081 // Only send the token to relative URLs i.e. locally.
2082 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));