using query.object with namespaces was causing issues when looking for object type
[myslice.git] / manifoldapi / static / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
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);
18 }
19
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
24     if (!array)
25         return false;
26
27     // compare lengths - can save a lot of time 
28     if (this.length != array.length)
29         return false;
30
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]))
36                 return false;
37         }
38         else if (this[i] != array[i]) {
39             // Warning - two different object instances will never be equal: {x:20} != {x:20}
40             return false;
41         }
42     }
43     return true;
44 }
45
46 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
47 Object.toType = (function toType(global) {
48   return function(obj) {
49     if (obj === global) {
50       return "global";
51     }
52     return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
53   }
54 })(this);
55
56 /* ------------------------------------------------------------ */
57
58 // Constants that should be somehow moved to a plugin.js file
59 var FILTER_ADDED   = 1;
60 var FILTER_REMOVED = 2;
61 var CLEAR_FILTERS  = 3;
62 var FIELD_ADDED    = 4;
63 var FIELD_REMOVED  = 5;
64 var CLEAR_FIELDS   = 6;
65 var NEW_RECORD     = 7;
66 var CLEAR_RECORDS  = 8;
67
68 /**
69  * event: FIELD_STATE_CHANGED
70  *
71  * Parameters:
72  *   dict :
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
77  */
78 var FIELD_STATE_CHANGED = 9;
79
80 var IN_PROGRESS    = 101;
81 var DONE           = 102; //XXX Should be harmonized with query state
82
83 /* Update requests related to subqueries */
84
85 /*
86 var SET_ADD        = 201;
87 var SET_REMOVED    = 202;
88 */
89
90 // request
91 /*
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;
97 */
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;
107
108 /* Requests for query cycle */
109 var RUN_UPDATE     = 601;
110
111 /* MANIFOLD types */
112 var TYPE_VALUE  = 1;
113 var TYPE_RECORD = 2;
114 var TYPE_LIST_OF_VALUES = 3;
115 var TYPE_LIST_OF_RECORDS = 4;
116
117 /******************************************************************************
118  * QUERY STATUS (for manifold events)
119  ******************************************************************************/
120
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;
129
130 /******************************************************************************
131  * QUERY STATE (for query_store)
132  ******************************************************************************/
133
134 // XXX Rendundant with query status ?
135
136 var QUERY_STATE_INIT        = 0;
137 var QUERY_STATE_INPROGRESS  = 1;
138 var QUERY_STATE_DONE        = 2;
139
140 /******************************************************************************
141  * RECORD STATES (for query_store)
142  ******************************************************************************/
143
144 var STATE_SET       = 0;
145 var STATE_VALUE     = 1;
146 var STATE_WARNINGS  = 2;
147 var STATE_VISIBLE   = 3;
148
149 // ACTIONS
150 var STATE_SET_CHANGE = 0;
151 var STATE_SET_ADD    = 1;
152 var STATE_SET_REMOVE = 2;
153 var STATE_SET_CLEAR  = 3;
154
155 // STATE_SET : enum
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;
167
168 // STATE_WARNINGS : dict
169
170 // STATE_VISIBLE : boolean
171
172 /******************************************************************************
173  * CONSTRAINTS
174  ******************************************************************************/
175
176 var CONSTRAINT_RESERVABLE_LEASE     = 0;
177
178 var CONSTRAINT_RESERVABLE_LEASE_MSG = "Configuration required: this resource needs to be scheduled";
179
180 // A structure for storing queries
181
182 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled, domain_query_ext) {
183
184     /* Constructor */
185     if (typeof query == "undefined")
186         throw "Must pass a query in QueryExt constructor";
187     this.query                 = query;
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;
193
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;
198
199     // Set members to buffer until the domain query is completed
200     // A list of keys
201     this.set_members = [];
202
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;
206     
207     this.query_state = QUERY_STATE_INIT;
208
209     // Results from a query consists in a dict that maps keys to records
210     this.records = new Hashtable();
211
212     // Status is a dict that maps keys to record status
213     this.state = new Hashtable();
214
215     // Filters that impact visibility in the local interface
216     this.filters = [];
217
218     // XXX Until we find a better solution
219     this.num_pending = 0;
220     this.num_unconfigured = 0;
221
222     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
223 }
224
225 function QueryStore() {
226
227     this.main_queries     = {};
228     this.analyzed_queries = {};
229
230     /* Insertion */
231
232     this.insert = function(query) {
233         // We expect only main_queries are inserted
234         
235         /* If the query has not been analyzed, then we analyze it */
236         if (query.analyzed_query == null) {
237             query.analyze_subqueries();
238         }
239
240         /* We prepare the update query corresponding to the main query and store both */
241         /* Note: they have the same UUID */
242
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);
249
250         /* We remember the original query to be able to reset it */
251         update_query_orig_ext = new QueryExt(update_query.clone());
252
253
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! */
258
259
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...
266
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;
271             if (parent_query) {
272                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
273             } else {
274                 parent_query_ext = null;
275             }
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)
279
280             if (parent_query) {
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); 
286
287                 console.log("Created domain query", domain_query);
288                 var domain_query_ext = new QueryExt(domain_query);
289
290                 domain_query_ext.set_query_ext = sq_ext;
291                 sq_ext.domain_query_ext = domain_query_ext;
292
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;
296
297                 // XXX This query is run before the plugins are initialized and listening
298                 manifold.run_query(domain_query);
299             }
300
301             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
302         });
303
304         // XXX We have spurious update queries...
305     }
306
307     /* Searching */
308
309     this.find_query_ext = function(query_uuid)
310     {
311         return this.main_queries[query_uuid];
312     }
313
314     this.find_query = function(query_uuid) 
315     {
316         return this.find_query_ext(query_uuid).query;
317     }
318
319     this.find_analyzed_query_ext = function(query_uuid)
320     {
321         return this.analyzed_queries[query_uuid];
322     }
323
324     this.find_analyzed_query = function(query_uuid) 
325     {
326         return this.find_analyzed_query_ext(query_uuid).query;
327     }
328
329     this.state_dict_create = function(default_set)
330     {
331         default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
332         var state_dict = {};
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;
337         return state_dict;
338     }
339
340     // RECORDS
341
342     this.set_records = function(query_uuid, records, default_set)
343     {
344         default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
345
346         var self = this;
347         var key, object, query_ext, record_key;
348
349         query_ext = this.find_analyzed_query_ext(query_uuid);
350         object = query_ext.query.object;
351         if (object.indexOf(':') != -1) {
352             object = object.split(':')[1];
353         }
354         record_key = manifold.metadata.get_key(object);
355
356         // ["start_time", "resource", "end_time"]
357         // ["urn"]
358         
359         $.each(records, function(i, record) {
360             //var key = manifold.metadata.get_key(query_ext.query.object);
361             
362             var record_key_value = manifold.record_get_value(record, record_key);
363             query_ext.records.put(record_key_value, record);
364
365             if (!(query_ext.state.get(record_key_value)))
366                 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
367         });
368     }
369
370     this.get_records = function(query_uuid)
371     {
372         var query_ext = this.find_analyzed_query_ext(query_uuid);
373         return query_ext.records.values();
374     }
375
376     this.get_record = function(query_uuid, record_key)
377     {
378         var query_ext = this.find_analyzed_query_ext(query_uuid);
379         return query_ext.records.get(record_key);
380     }
381
382     this.del_record = function(query_uuid, record_key)
383     {
384         var query_ext = this.find_analyzed_query_ext(query_uuid);
385         return query_ext.records.remove(record_key);
386     }
387
388     this.del_state = function(query_uuid, record_key)
389     {
390         var query_ext = this.find_analyzed_query_ext(query_uuid);
391         return query_ext.state.remove(record_key);
392     }
393
394     this.add_record = function(query_uuid, record, new_state)
395     {
396         var query_ext, key, record_key;
397         query_ext = this.find_analyzed_query_ext(query_uuid);
398         
399         if (typeof(record) == 'object') {
400             key = manifold.metadata.get_key(query_ext.query.object);
401             record_key = manifold.record_get_value(record, key);
402         } else {
403             record_key = record;
404         }
405
406         var record_entry = query_ext.records.get(record_key);
407         if (!record_entry)
408             query_ext.records.put(record_key, record);
409
410         manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
411     }
412
413     this.remove_record = function(query_uuid, record, new_state)
414     {
415         var query_ext, key, record_key;
416         query_ext = this.find_analyzed_query_ext(query_uuid);
417         
418         if (typeof(record) == 'object') {
419             key = manifold.metadata.get_key(query_ext.query.object);
420             record_key = manifold.record_get_value(record, key);
421         } else {
422             record_key = record;
423         }
424         
425         if ((query_ext.query.object == 'lease') && (new_state == STATE_SET_OUT)) {
426             // Leases that are marked out are in fact leases from other slices
427             // We need to _remove_ leases that we mark as OUT
428             manifold.query_store.del_record(query_uuid, record_key);
429             manifold.query_store.del_state(query_uuid, record_key);
430         } else {
431             manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
432         }
433     }
434
435     this.iter_records = function(query_uuid, callback)
436     {
437         var query_ext = this.find_analyzed_query_ext(query_uuid);
438         query_ext.records.each(callback);
439         //callback = function(record_key, record)
440     }
441
442     this.iter_visible_records = function(query_uuid, callback)
443     {
444         var query_ext = this.find_analyzed_query_ext(query_uuid);
445         query_ext.records.each(function(record_key, record) {
446             if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
447                 callback(record_key, record);
448         });
449         //callback = function(record_key, record)
450
451     }
452
453     // STATE
454
455     this.set_record_state = function(query_uuid, result_key, state, value)
456     {
457         var query_ext = this.find_analyzed_query_ext(query_uuid);
458         var state_dict = query_ext.state.get(result_key);
459         if (!state_dict)
460             state_dict = this.state_dict_create();
461
462         state_dict[state] = value;
463
464         query_ext.state.put(result_key, state_dict);
465     }
466
467     this.get_record_state = function(query_uuid, result_key, state)
468     {
469         var query_ext = this.find_analyzed_query_ext(query_uuid);
470         var state_dict = query_ext.state.get(result_key);
471         if (!state_dict)
472             return null;
473         return state_dict[state];
474     }
475
476     // FILTERS
477
478     this.add_filter = function(query_uuid, filter)
479     {
480         var query_ext = this.find_analyzed_query_ext(query_uuid);
481         // XXX When we update a filter
482         query_ext.filters.push(filter);
483
484         this.apply_filters(query_uuid);
485
486     }
487
488     this.update_filter = function(query_uuid, filter)
489     {
490         // XXX
491
492         this.apply_filters(query_uuid);
493     }
494
495     this.remove_filter = function(query_uuid, filter)
496     {
497         var query_ext = this.find_analyzed_query_ext(query_uuid);
498         query_ext.filters = $.grep(query_ext.filters, function(x) {
499             return !(x.equals(filter));
500         });
501
502         this.apply_filters(query_uuid);
503     }
504
505     this.get_filters = function(query_uuid)
506     {
507         var query_ext = this.find_analyzed_query_ext(query_uuid);
508         return query_ext.filters;
509     }
510
511     this.recount = function(query_uuid)
512     {
513         var query_ext;
514         var is_reserved, is_pending, in_set,  is_unconfigured;
515
516         query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
517         query_ext.num_pending = 0;
518         query_ext.num_unconfigured = 0;
519
520         this.iter_records(query_uuid, function(record_key, record) {
521             var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
522             var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
523
524             is_reserved = (record_state == STATE_SET_IN) 
525                        || (record_state == STATE_SET_OUT_PENDING)
526                        || (record_state == STATE_SET_IN_SUCCESS)
527                        || (record_state == STATE_SET_OUT_FAILURE);
528
529             is_pending = (record_state == STATE_SET_IN_PENDING) 
530                       || (record_state == STATE_SET_OUT_PENDING);
531
532             in_set = (record_state == STATE_SET_IN) // should not have warnings
533                   || (record_state == STATE_SET_IN_PENDING)
534                   || (record_state == STATE_SET_IN_SUCCESS)
535                   || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
536
537             is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
538
539             /* Let's update num_pending and num_unconfigured at this stage */
540             if (is_pending)
541                 query_ext.num_pending++;
542             if (is_unconfigured)
543                 query_ext.num_unconfigured++;
544         });
545
546     }
547
548     this.apply_filters = function(query_uuid)
549     {
550         var start = new Date().getTime();
551
552         // Toggle visibility of records according to the different filters.
553
554         var self = this;
555         var filters = this.get_filters(query_uuid);
556         var col_value;
557         /* Let's update num_pending and num_unconfigured at this stage */
558
559         // Adapted from querytable._querytable_filter()
560
561         this.iter_records(query_uuid, function(record_key, record) {
562             var is_reserved, is_pending, in_set,  is_unconfigured;
563             var visible = true;
564
565             var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
566             var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
567
568             is_reserved = (record_state == STATE_SET_IN) 
569                        || (record_state == STATE_SET_OUT_PENDING)
570                        || (record_state == STATE_SET_IN_SUCCESS)
571                        || (record_state == STATE_SET_OUT_FAILURE);
572
573             is_pending = (record_state == STATE_SET_IN_PENDING) 
574                       || (record_state == STATE_SET_OUT_PENDING);
575
576             in_set = (record_state == STATE_SET_IN) // should not have warnings
577                   || (record_state == STATE_SET_IN_PENDING)
578                   || (record_state == STATE_SET_IN_SUCCESS)
579                   || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
580
581             is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
582
583             // We go through each filter and decide whether it affects the visibility of the record
584             $.each(filters, function(index, filter) {
585                 var key = filter[0];
586                 var op = filter[1];
587                 var value = filter[2];
588
589
590                 /* We do some special handling for the manifold:status filter
591                  * predicates. */
592
593                 if (key == 'manifold:status') {
594                     if (op != '=' && op != '==') {
595                         // Unsupported filter, let's ignore it
596                         console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
597                         return true; // ~ continue
598                     }
599
600                     switch (value) {
601                         case 'reserved':
602                             // true  => ~ continue
603                             // false => ~ break
604                             visible = is_reserved;
605                             return visible;
606                         case 'unconfigured':
607                             visible = is_unconfigured;
608                             return visible;
609                         case 'pending':
610                             visible = is_pending;
611                             return visible;
612                     }
613                     return false; // ~ break
614                 }
615
616                 /* Normal filtering behaviour (according to the record content) follows... */
617                 col_value = manifold.record_get_value(record, key);
618
619                 // When the filter does not match, we hide the column by default
620                 if (col_value === 'undefined') {
621                     visible = false;
622                     return false; // ~ break
623                 }
624
625                 // XXX This should accept pluggable filtering functions.
626
627
628                 /* Test whether current filter is compatible with the column */
629                 if (op == '=' || op == '==') {
630                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
631                         visible = false;
632                 }else if (op == 'included') {
633                     $.each(value, function(i,x) {
634                       if(x == col_value){
635                           visible = true;
636                           return false; // ~ break
637                       }else{
638                           visible = false;
639                       }
640                     });
641                 }else if (op == '!=') {
642                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
643                         visible = false;
644                 } else if(op=='<') {
645                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
646                         visible = false;
647                 } else if(op=='>') {
648                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
649                         visible = false;
650                 } else if(op=='<=' || op=='≤') {
651                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
652                         visible = false;
653                 } else if(op=='>=' || op=='≥') {
654                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
655                         visible = false;
656                 }else{
657                     // How to break out of a loop ?
658                     alert("filter not supported");
659                     return false; // break
660                 }
661
662             });
663
664             // Set the visibility status in the query store
665             self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
666         });
667
668         var end = new Date().getTime();
669         console.log("APPLY FILTERS took", end - start, "ms");
670
671     }
672
673 }
674
675 /*!
676  * This namespace holds functions for globally managing query objects
677  * \Class Manifold
678  */
679 var manifold = {
680
681     /************************************************************************** 
682      * Helper functions
683      **************************************************************************/ 
684
685     separator: '__',
686
687     get_type: function(variable) {
688         switch(Object.toType(variable)) {
689             case 'number':
690             case 'string':
691                 return TYPE_VALUE;
692             case 'object':
693                 return TYPE_RECORD;
694             case 'array':
695                 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
696                     return TYPE_LIST_OF_RECORDS;
697                 else
698                     return TYPE_LIST_OF_VALUES;
699         }
700     },
701
702     /**
703      *  Args:
704      *      fields: A String instance (field name), or a set of String instances
705      *          (field names) # XXX tuple !!
706      *  Returns:
707      *      If fields is a String,  return the corresponding value.
708      *      If fields is a set, return a tuple of corresponding value.
709      *
710      *  Raises:
711      *      KeyError if at least one of the fields is not found
712      */
713     record_get_value: function(record, fields) 
714     {
715         if (typeof(fields) === 'string') {
716             if (fields.indexOf('.') != -1) {
717                 key_subkey = key.split('.', 2);
718                 key     = key_subkey[0]; 
719                 subkey  = key_subkey[1];
720
721                 if (record.indexOf(key) == -1) {
722                     return null;
723                 }
724                 // Tests if the following is an array (typeof would give object)
725                 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
726                     // Records
727                     return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
728                 } else if (typeof(record) == 'object') {
729                     // Record
730                     return manifold.record_get_value(record[key], subkey);
731                 } else {
732                     console.log('Unknown field');
733                 }
734             } else {
735                 return record[fields];
736             }
737         } else {
738             // see. get_map_entries
739             if (fields.length == 1)
740                 return manifold.record_get_value(record, fields[0])
741
742             // Build a new record
743             var ret = {};
744             $.each(fields, function(i, field) {
745                 ret[field] = manifold.record_get_value(record, field);
746             });
747             ret.hashCode = record.hashCode;
748             ret.equals = record.equals;
749             return ret;
750             // this was an array, we want a dictionary
751             //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
752                 
753         }
754     },
755
756     record_hashcode: function(key_fields)
757     {
758         return function() {
759             ret = "";
760             for (var i=0; i < key_fields.length; i++)
761                 ret += "@@" + this[key_fields[i]];
762             return ret;
763         };
764     },
765
766     _record_equals: function(self, other, key_fields)
767     {
768         if ((typeof self === "string") && (typeof other === "string")) {
769             return self == other;
770         }
771         for (var i=0; i < key_fields.length; i++) {
772             var this_value  = self[key_fields[i]];
773             var other_value = other[key_fields[i]];
774
775             var this_type = manifold.get_type(this_value);
776             var other_type = manifold.get_type(other_value);
777             if (this_type != other_type)
778                 return false;
779
780             switch (this_type) {
781                 case TYPE_VALUE:
782                 case TYPE_LIST_OF_VALUES:
783                     if (this_value != other_value)
784                         return false;
785                     break;
786                 case TYPE_RECORD:
787                     if (!(_record_equals(this_value, other_value, key_fields)))
788                         return false;
789                     break;
790                 case TYPE_LIST_OF_RECORDS:
791                     if (this_value.length != other_value.length)
792                         return false;
793                     for (var j = 0; j < this_value.length; j++)
794                         if (!(_record_equals(this_value[j], other_value[j], key_fields)))
795                             return false;
796                     break;
797             }
798         }
799         return true;
800     },
801
802     record_equals: function(key_fields)
803     {
804         return function(other) { 
805             return manifold._record_equals(this, other, key_fields); 
806         };
807     },
808
809     _in_array: function(element, array, key_fields)
810     {
811         if (key_fields.length > 1) {
812             for (var i = 0; i < array.length; i++) {
813                 if (manifold._record_equals(element, array[i], key_fields))
814                     return true;
815             }
816             return false;
817         } else {
818             // XXX TODO If we have a dict, extract the key first
819             return ($.inArray(element, array) != -1);
820         }
821     },
822
823     /************************************************************************** 
824      * Metadata management
825      **************************************************************************/ 
826
827      metadata: {
828
829         get_table: function(method) {
830             var table = MANIFOLD_METADATA[method];
831             return (typeof table === 'undefined') ? null : table;
832         },
833
834         get_columns: function(method) {
835             var table = this.get_table(method);
836             if (!table) {
837                 return null;
838             }
839
840             return (typeof table.column === 'undefined') ? null : table.column;
841         },
842
843         get_field_names: function(method)
844         {
845             var columns = this.get_columns(method);
846             if (!columns)
847                 return null;
848             return $.map(columns, function (x) { return x.name });
849         },
850
851         get_key: function(method) {
852             var table = this.get_table(method);
853             if (!table)
854                 return null;
855
856             return (typeof table.key === 'undefined') ? null : table.key;
857         },
858
859
860         get_column: function(method, name) {
861             var columns = this.get_columns(method);
862             if (!columns)
863                 return null;
864
865             $.each(columns, function(i, c) {
866                 if (c.name == name)
867                     return c
868             });
869             return null;
870         },
871
872         get_type: function(method, name) {
873             var table = this.get_table(method);
874             if (!table)
875                 return null;
876
877             var match = $.grep(table.column, function(x) { return x.name == name });
878             if (match.length == 0) {
879                 return undefined;
880             } else {
881                 return match[0].type;
882             }
883             return (typeof table.type === 'undefined') ? null : table.type;
884         }
885
886      },
887
888     /************************************************************************** 
889      * Query management
890      **************************************************************************/ 
891
892     query_store: new QueryStore(),
893
894     // XXX Remaining functions are deprecated since they are replaced by the query store
895
896     /*!
897      * Associative array storing the set of queries active on the page
898      * \memberof Manifold
899      */
900     all_queries: {},
901
902     /*!
903      * Insert a query in the global hash table associating uuids to queries.
904      * If the query has no been analyzed yet, let's do it.
905      * \fn insert_query(query)
906      * \memberof Manifold
907      * \param ManifoldQuery query Query to be added
908      */
909     insert_query : function (query) { 
910         // NEW API
911         manifold.query_store.insert(query);
912
913         // Run
914         $(document).ready(function() {
915         manifold.run_query(query);
916         });
917
918         // FORMER API
919         if (query.analyzed_query == null) {
920             query.analyze_subqueries();
921         }
922         manifold.all_queries[query.query_uuid]=query;
923     },
924
925     /*!
926      * Returns the query associated to a UUID
927      * \fn find_query(query_uuid)
928      * \memberof Manifold
929      * \param string query_uuid The UUID of the query to be returned
930      */
931     find_query : function (query_uuid) { 
932         return manifold.all_queries[query_uuid];
933     },
934
935     /************************************************************************** 
936      * Query execution
937      **************************************************************************/ 
938
939     // trigger a query asynchroneously
940     proxy_url : '/manifold/proxy/json/',
941
942     // reasonably low-noise, shows manifold requests coming in and out
943     asynchroneous_debug : true,
944     // print our more details on result publication and related callbacks
945     pubsub_debug : false,
946
947     /**
948      * \brief We use js function closure to be able to pass the query (array)
949      * to the callback function used when data is received
950      */
951     success_closure: function(query, publish_uuid, callback) {
952         return function(data, textStatus) {
953             manifold.asynchroneous_success(data, query, publish_uuid, callback);
954         }
955     },
956
957     run_query: function(query, callback)
958         {
959         // default value for callback = null
960         if (typeof callback === 'undefined')
961             callback = null; 
962
963         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
964         query_ext.query_state = QUERY_STATE_INPROGRESS;
965
966         var query_json = JSON.stringify(query);
967
968         // Inform plugins about the progress
969         query.iter_subqueries(function (sq) {
970             var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
971             sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
972
973             manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
974         });
975
976
977         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
978     },
979
980     // XXX DEPRECATED
981     // Executes all async. queries - intended for the javascript header to initialize queries
982     // input queries are specified as a list of {'query_uuid': <query_uuid> }
983     // each plugin is responsible for managing its spinner through on_query_in_progress
984     asynchroneous_exec : function (query_exec_tuples) {
985         
986         // Loop through input array, and use publish_uuid to publish back results
987         $.each(query_exec_tuples, function(index, tuple) {
988             var query=manifold.find_query(tuple.query_uuid);
989             var query_json=JSON.stringify (query);
990             var publish_uuid=tuple.publish_uuid;
991             // by default we publish using the same uuid of course
992             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
993             if (manifold.pubsub_debug) {
994                 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
995             }
996
997             query.iter_subqueries(function (sq) {
998                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
999             });
1000
1001             // not quite sure what happens if we send a string directly, as POST data is named..
1002             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
1003             $.post(manifold.proxy_url, {'json':query_json}, 
1004                    manifold.success_closure(query, publish_uuid, tuple.callback));
1005         })
1006     },
1007
1008     /**
1009      * \brief Forward a query to the manifold backend
1010      * \param query (dict) the query to be executed asynchronously
1011      * \param callback (function) the function to be called when the query terminates
1012      */
1013     forward: function(query, callback) {
1014         var query_json = JSON.stringify(query);
1015         $.post(manifold.proxy_url, {'json': query_json} , 
1016                manifold.success_closure(query, query.query_uuid, callback));
1017     },
1018
1019     /*!
1020      * Returns whether a query expects a unique results.
1021      * This is the case when the filters contain a key of the object
1022      * \fn query_expects_unique_result(query)
1023      * \memberof Manifold
1024      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
1025      */
1026     query_expects_unique_result: function(query) {
1027         /* XXX we need functions to query metadata */
1028         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
1029         /* TODO requires keys in metadata */
1030         return true;
1031     },
1032
1033     /*!
1034      * Publish result
1035      * \fn publish_result(query, results)
1036      * \memberof Manifold
1037      * \param ManifoldQuery query Query which has received results
1038      * \param array results results corresponding to query
1039      */
1040     publish_result: function(query, result) {
1041         if (typeof result === 'undefined')
1042             result = [];
1043
1044         // NEW PLUGIN API
1045         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
1046         if (manifold.pubsub_debug)
1047             messages.debug(".. publish_result (1) ");
1048         var count=0;
1049         $.each(result, function(i, record) {
1050             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
1051             count += 1;
1052         });
1053         if (manifold.pubsub_debug) 
1054             messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
1055         manifold.raise_record_event(query.query_uuid, DONE);
1056         if (manifold.pubsub_debug) 
1057             messages.debug(".. publish_result (3) has used NEW API to say DONE");
1058
1059         // OLD PLUGIN API BELOW
1060         /* Publish an update announce */
1061         var channel="/results/" + query.query_uuid + "/changed";
1062         if (manifold.pubsub_debug) 
1063             messages.debug(".. publish_result (4) OLD API on channel" + channel);
1064
1065         $.publish(channel, [result, query]);
1066
1067         if (manifold.pubsub_debug) 
1068             messages.debug(".. publish_result (5) END q=" + query.__repr());
1069     },
1070
1071     store_records: function(query, records) {
1072         // Store records
1073         var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1074         if (query_ext.set_query_ext) {
1075             // We have a domain query
1076             // The results are stored in the corresponding set_query
1077             manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1078             
1079         } else if (query_ext.domain_query_ext) {
1080             // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1081             // Has it a domain query, and has it completed ?
1082             $.each(records, function(i, record) {
1083                 var key = manifold.metadata.get_key(query.object);
1084                 var record_key = manifold.record_get_value(record, key);
1085                 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1086             });
1087
1088         } else {
1089             // We have a normal query
1090             manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1091         }
1092     },
1093
1094     /*!
1095      * Recursively publish result
1096      * \fn publish_result_rec(query, result)
1097      * \memberof Manifold
1098      * \param ManifoldQuery query Query which has received result
1099      * \param array result result corresponding to query
1100      *
1101      * Note: this function works on the analyzed query
1102      */
1103     publish_result_rec: function(query, records) {
1104         /* If the result is not unique, only publish the top query;
1105          * otherwise, publish the main object as well as subqueries
1106          * XXX how much recursive are we ?
1107          */
1108         if (manifold.pubsub_debug)
1109              messages.debug (">>>>> publish_result_rec " + query.object);
1110         if (manifold.query_expects_unique_result(query)) {
1111             /* Also publish subqueries */
1112             $.each(query.subqueries, function(object, subquery) {
1113                 manifold.publish_result_rec(subquery, records[0][object]);
1114                 /* TODO remove object from result */
1115             });
1116         }
1117         if (manifold.pubsub_debug) 
1118             messages.debug ("===== publish_result_rec " + query.object);
1119
1120         var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1121         query_ext.query_state = QUERY_STATE_DONE;
1122
1123         this.store_records(query, records);
1124
1125         var pub_query;
1126
1127         if (query_ext.set_query_ext) {
1128             if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1129                 return;
1130             pub_query = query_ext.set_query_ext.query;
1131         } else if (query_ext.domain_query_ext) {
1132             if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1133                 return;
1134             pub_query = query;
1135         } else {
1136             pub_query = query;
1137         }
1138         // We can only publish results if the query (and its related domain query) is complete
1139         manifold.publish_result(pub_query, records);
1140
1141         if (manifold.pubsub_debug) 
1142             messages.debug ("<<<<< publish_result_rec " + query.object);
1143     },
1144
1145     setup_update_query: function(query, records) 
1146     {
1147         // We don't prepare an update query if the result has more than 1 entry
1148         if (records.length != 1)
1149             return;
1150         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1151
1152         var record = records[0];
1153
1154         var update_query_ext = query_ext.update_query_ext;
1155
1156         if (!update_query_ext)
1157             return;
1158
1159         var update_query = update_query_ext.query;
1160         var update_query_ext = query_ext.update_query_ext;
1161         var update_query_orig = query_ext.update_query_orig_ext.query;
1162
1163         // Testing whether the result has subqueries (one level deep only)
1164         // iif the query has subqueries
1165         var count = 0;
1166         var obj = query.analyzed_query.subqueries;
1167         for (method in obj) {
1168             if (obj.hasOwnProperty(method)) {
1169                 var key = manifold.metadata.get_key(method);
1170                 if (!key)
1171                     continue;
1172                 var sq_keys = [];
1173                 var subrecords = record[method];
1174                 if (!subrecords)
1175                     continue
1176                 $.each(subrecords, function (i, subrecord) {
1177                     sq_keys.push(manifold.record_get_value(subrecord, key));
1178                 });
1179                 update_query.params[method] = sq_keys;
1180                 update_query_orig.params[method] = sq_keys.slice();
1181                 count++;
1182             }
1183         }
1184
1185         if (count > 0) {
1186             update_query_ext.disabled = false;
1187             update_query_orig_ext.disabled = false;
1188         }
1189     },
1190
1191     process_get_query_records: function(query, records) {
1192         this.setup_update_query(query, records);
1193         
1194         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1195         query_ext.query_state = QUERY_STATE_DONE;
1196
1197         /* Publish full results */
1198         var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1199         manifold.publish_result_rec(tmp_query, records);
1200     },
1201
1202     make_records: function(object, records)
1203     {
1204         $.each(records, function(i, record) {
1205             manifold.make_record(object, record);
1206         });
1207     },
1208
1209     make_record: function(object, record)
1210     {
1211         // To make an object a record, we just add the hash function
1212         var key, new_object;
1213
1214         if (object.indexOf(':') != -1) {
1215             new_object = object.split(':')[1];
1216         } else {
1217             new_object = object;
1218         }
1219
1220         key = manifold.metadata.get_key(new_object);
1221         record.hashCode = manifold.record_hashcode(key.sort());
1222         record.equals   = manifold.record_equals(key);
1223
1224         // Looking after subrecords
1225         for (var field in record) {
1226             var result_value = record[field];
1227
1228             switch (this.get_type(result_value)) {
1229                 case TYPE_RECORD:
1230                     var subobject = manifold.metadata.get_type(object, field);
1231                     // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1232                     if (subobject && subobject != 'string')
1233                         manifold.make_record(subobject, result_value);
1234                     break;
1235                 case TYPE_LIST_OF_RECORDS:
1236                     var subobject = manifold.metadata.get_type(object, field);
1237                     if (subobject)
1238                         manifold.make_records(subobject, result_value);
1239                     break;
1240             }
1241         }
1242     },
1243
1244     /**
1245      * 
1246      * What we need to do when receiving results from an update query:
1247      * - differences between what we had, what we requested, and what we obtained
1248      *    . what we had : update_query_orig (simple fields and set fields managed differently)
1249      *    . what we requested : update_query
1250      *    . what we received : records
1251      * - raise appropriate events
1252      *
1253      * The normal process is that results similar to Get will be pushed in the
1254      * pubsub mechanism, thus repopulating everything while we only need
1255      * diff's. This means we need to move the publish functionalities in the
1256      * previous 'process_get_query_records' function.
1257      */
1258     process_update_query_records: function(query, records) {
1259         // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1260         var query_uuid        = query.query_uuid;
1261         var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
1262         var update_query      = query_ext.main_query_ext.update_query_ext.query;
1263         var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1264         
1265         // Since we update objects one at a time, we can get the first record
1266         var record = records[0];
1267
1268         // Let's iterate over the object properties
1269         for (var field in record) {
1270             var result_value = record[field];
1271             switch (this.get_type(result_value)) {
1272                 case TYPE_VALUE:
1273                     // Did we ask for a change ?
1274                     var update_value = update_query[field];
1275                     if (!update_value)
1276                         // Not requested, if it has changed: OUT OF SYNC
1277                         // How we can know ?
1278                         // We assume it won't have changed
1279                         continue;
1280
1281                     if (!result_value)
1282                         throw "Internal error";
1283
1284                     data = {
1285                         state : STATE_SET,
1286                         key   : field,
1287                         op    : update_value,
1288                         value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1289                     }
1290                     manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1291
1292                     break;
1293                 case TYPE_RECORD:
1294                     throw "Not implemented";
1295                     break;
1296
1297                 /*
1298 case TYPE_LIST_OF_VALUES:
1299                     // Same as list of records, but we don't have to extract keys
1300                     
1301                     // The rest of exactly the same (XXX factorize)
1302                     var update_keys  = update_query_orig.params[field];
1303                     var query_keys   = update_query.params[field];
1304                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1305                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1306
1307
1308                     $.each(added_keys, function(i, key) {
1309                         if ($.inArray(key, result_value) == -1) {
1310                             data = {
1311                                 request: FIELD_REQUEST_ADD,
1312                                 key   : field,
1313                                 value : key,
1314                                 status: FIELD_REQUEST_FAILURE,
1315                             }
1316                         } else {
1317                             data = {
1318                                 request: FIELD_REQUEST_ADD,
1319                                 key   : field,
1320                                 value : key,
1321                                 status: FIELD_REQUEST_SUCCESS,
1322                             }
1323                         }
1324                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1325                     });
1326                     $.each(removed_keys, function(i, key) {
1327                         if ($.inArray(key, result_keys) == -1) {
1328                             data = {
1329                                 request: FIELD_REQUEST_REMOVE,
1330                                 key   : field,
1331                                 value : key,
1332                                 status: FIELD_REQUEST_SUCCESS,
1333                             }
1334                         } else {
1335                             data = {
1336                                 request: FIELD_REQUEST_REMOVE,
1337                                 key   : field,
1338                                 value : key,
1339                                 status: FIELD_REQUEST_FAILURE,
1340                             }
1341                         }
1342                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1343                     });
1344
1345
1346                     break;
1347                 */
1348                 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1349                 case TYPE_LIST_OF_RECORDS:
1350                     var key, new_state, cur_query_uuid;
1351
1352                     cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1353
1354                     // example: slice.resource
1355                     //  - update_query_orig.params.resource = resources in slice before update
1356                     //  - update_query.params.resource = resource requested in slice
1357                     //  - keys from field = resources obtained
1358                 
1359                     if (field == 'lease') {
1360                          // lease_id has been added to be repeated when
1361                          // constructing request rspec. We don't want it for
1362                          // comparisons
1363                         key = ['start_time', 'end_time', 'resource'];
1364                     } else {
1365                         key = manifold.metadata.get_key(field);
1366                     }
1367                     if (!key)
1368                         continue;
1369                     /*
1370                     if (key.length > 1) {
1371                         throw "Not implemented";
1372                         continue;
1373                     }
1374                     key = key[0];
1375                     */
1376
1377                     /* XXX should be modified for multiple keys */
1378                     var result_keys  = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1379
1380                     // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1381                     // what we had at the begining
1382                     var update_keys  = update_query_orig.params[field];
1383                     // what we asked
1384                     var query_keys   = update_query.params[field];
1385                     // what we added and removed
1386                     var added_keys   = $.grep(query_keys,  function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1387                     var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys,  key))); });
1388
1389                     // Send events related to parent query
1390                     $.each(added_keys, function(i, added_key) {
1391                         new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1392
1393                         // Update record state for children queries
1394                         manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1395
1396                         // XXX This could be optimized
1397                         manifold.query_store.recount(cur_query_uuid); 
1398
1399                         data = { state: STATE_SET, key  : field, op   : new_state, value: added_key }
1400                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1401
1402                         // Inform subquery also
1403                         data.key = '';
1404                         manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1405                         // XXX Passing no parameters so that they can redraw everything would
1406                         // be more efficient but is currently not supported
1407                         // XXX We could also need to inform plugins about nodes IN (not pending) that are no more, etc.
1408                         // XXX refactor all this when suppressing update_queries, and relying on state instead !
1409                     });
1410                     $.each(removed_keys, function(i, removed_key) {
1411                         new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1412
1413                         // Update record state for children queries
1414                         manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1415
1416                         // XXX This could be optimized
1417                         manifold.query_store.recount(cur_query_uuid); 
1418
1419                         data = { state: STATE_SET, key  : field, op   : new_state, value: removed_key }
1420                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1421
1422                         // Inform subquery also
1423                         data.key = '';
1424                         manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1425                     });
1426
1427                     break;
1428             }
1429         }
1430         
1431         // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1432         this.setup_update_query(query, records);
1433
1434         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1435         query_ext.query_state = QUERY_STATE_DONE;
1436
1437
1438         // Send DONE message to plugins
1439         query.iter_subqueries(function(sq, data, parent_query) {
1440             manifold.raise_record_event(sq.query_uuid, DONE);
1441         });
1442
1443     },
1444
1445     process_query_records: function(query, records) {
1446         if (query.action == 'get') {
1447             this.process_get_query_records(query, records);
1448         } else if (query.action == 'update') {
1449             this.process_update_query_records(query, records);
1450         }
1451     },
1452
1453     // if set callback is provided it is called
1454     // most of the time publish_uuid will be query.query_uuid
1455     // however in some cases we wish to publish the result under a different uuid
1456     // e.g. an updater wants to publish its result as if from the original (get) query
1457     asynchroneous_success : function (data, query, publish_uuid, callback) {
1458         // xxx should have a nicer declaration of that enum in sync with the python code somehow
1459         
1460         var start = new Date();
1461         if (manifold.asynchroneous_debug)
1462             messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1463
1464         if (data.code == 2) { // ERROR
1465             // We need to make sense of error codes here
1466             alert("Your session has expired, please log in again");
1467             localStorage.removeItem('user');
1468             window.location="/logout/";
1469             if (manifold.asynchroneous_debug) {
1470                 duration=new Date()-start;
1471                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1472             }
1473             return;
1474         }
1475         if (data.code == 1) { // WARNING
1476             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1477             // publish error code and text message on a separate channel for whoever is interested
1478             if (publish_uuid)
1479                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1480
1481         }
1482
1483         // If a callback has been specified, we redirect results to it 
1484         if (!!callback) { 
1485             callback(data); 
1486             if (manifold.asynchroneous_debug) {
1487                 duration=new Date()-start;
1488                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1489             }
1490             return; 
1491         }
1492
1493         if (manifold.asynchroneous_debug) 
1494             messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1495
1496         // once everything is checked we can use the 'value' part of the manifoldresult
1497         var result=data.value;
1498         if (result) {
1499             /* Eventually update the content of related queries (update, etc) */
1500             manifold.make_records(query.object, result);
1501             this.process_query_records(query, result);
1502
1503             /* Publish results: disabled here, done in the previous call */
1504             //tmp_query = manifold.find_query(query.query_uuid);
1505             //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1506         }
1507         if (manifold.asynchroneous_debug) {
1508             duration=new Date()-start;
1509             messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1510         }
1511
1512     },
1513
1514     /************************************************************************** 
1515      * Plugin API helpers
1516      **************************************************************************/ 
1517
1518     raise_event_handler: function(type, query_uuid, event_type, value) {
1519         if (manifold.pubsub_debug)
1520             messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1521         if ((type != 'query') && (type != 'record'))
1522             throw 'Incorrect type for manifold.raise_event()';
1523         // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1524         // this should be fixed upstream in manifold I expect
1525         if (query_uuid === undefined) {
1526             messages.warning("undefined query in raise_event_handler");
1527             return;
1528         }
1529
1530         // notify the change to objects that either listen to this channel specifically,
1531         // or to the wildcard channel
1532         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1533
1534         $.each(channels, function(i, channel) {
1535             if (value === undefined) {
1536                 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1537                 $('.pubsub').trigger(channel, [event_type]);
1538             } else {
1539                 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1540                 $('.pubsub').trigger(channel, [event_type, value]);
1541             }
1542         });
1543     },
1544
1545     raise_query_event: function(query_uuid, event_type, value) {
1546         manifold.raise_event_handler('query', query_uuid, event_type, value);
1547     },
1548
1549     raise_record_event: function(query_uuid, event_type, value) {
1550         manifold.raise_event_handler('record', query_uuid, event_type, value);
1551     },
1552
1553     /**
1554      * Event handler helpers
1555      */
1556     _get_next_state_add: function(prev_state)
1557     {
1558         switch (prev_state) {
1559             case STATE_SET_OUT:
1560             case STATE_SET_OUT_SUCCESS:
1561             case STATE_SET_IN_FAILURE:
1562                 new_state = STATE_SET_IN_PENDING;
1563                 break;
1564
1565             case STATE_SET_OUT_PENDING:
1566                 new_state = STATE_SET_IN;
1567                 break;
1568
1569             case STATE_SET_IN:
1570             case STATE_SET_IN_PENDING:
1571             case STATE_SET_IN_SUCCESS:
1572             case STATE_SET_OUT_FAILURE:
1573                 console.log("Inconsistent state: already in");
1574                 return;
1575         }
1576         return new_state;
1577     },
1578
1579     _get_next_state_remove: function(prev_state)
1580     {
1581         switch (prev_state) {
1582             case STATE_SET_IN:
1583             case STATE_SET_IN_SUCCESS:
1584             case STATE_SET_OUT_FAILURE:
1585                 new_state = STATE_SET_OUT_PENDING;
1586                 break;
1587
1588             case STATE_SET_IN_PENDING:
1589                 new_state = STATE_SET_OUT;
1590                 break;  
1591
1592             case STATE_SET_OUT:
1593             case STATE_SET_OUT_PENDING:
1594             case STATE_SET_OUT_SUCCESS:
1595             case STATE_SET_IN_FAILURE:
1596                 console.log("Inconsistent state: already out");
1597                 return;
1598         }
1599         return new_state;
1600     },
1601
1602     _grep_active_lease_callback: function(lease_query, resource_key) {
1603         return function(lease_key_lease) {
1604             var state, lease_key, lease;
1605
1606             lease_key = lease_key_lease[0];
1607             lease = lease_key_lease[1];
1608
1609             if (lease['resource'] != resource_key)
1610                 return false;
1611
1612             state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1613             switch(state) {
1614                 case STATE_SET_IN:
1615                 case STATE_SET_IN_PENDING:
1616                 case STATE_SET_IN_SUCCESS:
1617                 case STATE_SET_OUT_FAILURE:
1618                     return true;
1619                 case STATE_SET_OUT:
1620                 case STATE_SET_OUT_PENDING:
1621                 case STATE_SET_OUT_SUCCESS:
1622                 case STATE_SET_IN_FAILURE:
1623                     return false;
1624             }
1625         }
1626     },
1627
1628     _enforce_constraints: function(query_ext, record, record_key, event_type)
1629     {
1630         var query, data;
1631
1632         query = query_ext.query;
1633
1634         switch(query.object) {
1635
1636             case 'resource':
1637                 // CONSTRAINT_RESERVABLE_LEASE
1638                 // 
1639                 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1640                 // XXX Not always a resource
1641                 var is_reservable = (record.exclusive == true);
1642                 if (is_reservable) {
1643                     var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1644
1645                     if (event_type == STATE_SET_ADD) {
1646                         // We should have a lease_query associated
1647                         var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in  options
1648                         var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1649                         // Do we have lease records (in) with this resource
1650                         var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, record_key));
1651                         if (lease_records.length == 0) {
1652                             // Sets a warning
1653                             // XXX Need for a better function to manage warnings
1654                             var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1655                             warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1656                         } else {
1657                             // Lease are defined, delete the warning in case it was set previously
1658                             delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1659                         }
1660                     } else {
1661                         // Remove warnings attached to this resource
1662                         delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1663                     }
1664
1665                     manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1666                 }
1667
1668                 /* This was redundant */
1669                 // manifold.query_store.recount(query.query_uuid); 
1670
1671                 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1672                 data = {
1673                     state:  STATE_WARNINGS,
1674                     key   : record_key,
1675                     op    : null,
1676                     value : warnings
1677                 }
1678                 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1679                 break;
1680
1681             case 'lease':
1682                 var resource_key = record_key.resource;
1683                 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1684                 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1685
1686                 if (event_type == STATE_SET_ADD) {
1687                      // A lease is added, it removes the constraint
1688                     delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1689                 } else {
1690                     // A lease is removed, it might trigger the warning
1691                     var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1692                     if (lease_records.length == 0) { // XXX redundant cases
1693                         // Sets a warning
1694                         // XXX Need for a better function to manage warnings
1695                         var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1696                         warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1697                     } else {
1698                         // Lease are defined, delete the warning in case it was set previously
1699                         delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1700                     }
1701                     
1702                 }
1703
1704                 manifold.query_store.recount(resource_query.query_uuid); 
1705
1706                 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1707                 data = {
1708                     state:  STATE_WARNINGS,
1709                     key   : resource_key,
1710                     op    : null,
1711                     value : warnings
1712                 }
1713                 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1714                 break;
1715         }
1716
1717         // -) When a lease is added, it might remove the warning associated to a reservable node
1718
1719         // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1720         // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1721
1722         // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1723         // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1724
1725         // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1726
1727     },
1728
1729     _get_query_path: function(query_ext) {
1730         var path = "";
1731         var sq = query_ext;
1732         while (sq.parent_query_ext) {
1733             if (path != "")
1734                 path = '.' + path;
1735             path = sq.query.object + path;
1736             sq = sq.parent_query_ext;
1737         }
1738         return path;
1739     },
1740
1741
1742     /**
1743      * Handling events raised by plugins
1744      */
1745     raise_event: function(query_uuid, event_type, data) 
1746     {
1747         var query, query_ext;
1748
1749         // Query uuid has been updated with the key of a new element
1750         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
1751         query = query_ext.query;
1752
1753         switch(event_type) {
1754
1755             // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1756             case FIELD_STATE_CHANGED:
1757
1758                 // value is an object (request, key, value, status)
1759                 // update is only possible is the query is not pending, etc
1760                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1761                 // we should map SET_ADD on this...
1762
1763                 // 1. Update internal query store about the change in status
1764
1765                 // 2. Update the update query
1766                 update_query      = query_ext.main_query_ext.update_query_ext.query;
1767                 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1768
1769                 switch(data.state) {
1770             
1771                     case STATE_VALUE:
1772                         switch(data.op) {
1773                             case STATE_CHANGE:
1774                                 /* Set parameter data.key in the update_query to VALUE */
1775                                 if (update_query.params[data.key] === undefined)
1776                                     update_query.params[data.key] = Array();
1777                                 update_query.params[data.key] = value.value;
1778                                 break;
1779
1780                         }
1781                         break;
1782
1783                     case STATE_SET:
1784                         var prev_state, new_state;
1785                         var main_query, record, new_data, path;
1786         
1787                         // We only track state in the analyzed query
1788                         prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1789                         if (prev_state === null)
1790                             prev_state = STATE_SET_OUT;
1791
1792                         switch(data.op) {
1793                             case STATE_SET_ADD:
1794                                 new_state = this._get_next_state_add(prev_state);
1795
1796                                 /* data.value containts the resource key */
1797                                 manifold.query_store.add_record(query_uuid, data.value, new_state);
1798                                 record = manifold.query_store.get_record(query_uuid, data.value);
1799                                 this._enforce_constraints(query_ext, record, data.value, STATE_SET_ADD);
1800                 
1801                                 /* Process update query in parent */
1802                                 path =  this._get_query_path(query_ext);
1803                                 if (update_query.params[path] === undefined)
1804                                     update_query.params[path] = Array();
1805                                 update_query.params[path].push(data.value);
1806
1807                                 break;
1808
1809                             case STATE_SET_REMOVE:
1810                                 new_state = this._get_next_state_remove(prev_state);
1811
1812                                 /* data.value contains the resource key */
1813                                 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1814                                 record = manifold.query_store.get_record(query_uuid, data.value);
1815                                 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1816                     
1817                                 /* Process update query in parent */
1818                                 path =  this._get_query_path(query_ext);
1819                                 arr = update_query.params[path];
1820                                 
1821                                 var key = manifold.metadata.get_key(query.object);
1822                                 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1823                                 if (update_query.params[path] === undefined)
1824                                     update_query.params[path] = Array();
1825                                 update_query.params[path] = arr;
1826                                 break;
1827                         }
1828
1829                         /* Inform the parent query: important for update */
1830                         new_data = {
1831                             state : STATE_SET,
1832                             key   : path,
1833                             op    : new_state,
1834                             value : data.value,
1835                         };
1836                         main_query = query_ext.main_query_ext.query;
1837                         manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1838                         /* Propagate the event to other plugins subscribed to the query */
1839                         manifold.query_store.recount(query_uuid);
1840                         new_data.key = ''
1841                         manifold.raise_record_event(query_uuid, event_type, new_data);
1842
1843                         break;
1844                 }
1845 /*
1846                 // 3. Inform others about the change
1847                 // a) the main query...
1848                 manifold.raise_record_event(query_uuid, event_type, data);
1849
1850                 // b) subqueries eventually (dot in the key)
1851                 // Let's unfold 
1852
1853                 var cur_query = query;
1854                 if (cur_query.analyzed_query)
1855                     cur_query = cur_query.analyzed_query;
1856
1857                 if (data.key) {
1858                     var path_array = data.key.split('.');
1859                     var value_key = data.key.split('.');
1860                     $.each(path_array, function(i, method) {
1861                         cur_query = cur_query.subqueries[method];
1862                         value_key.shift(); // XXX check that method is indeed shifted
1863                     });
1864                     data.key = value_key;
1865                 }
1866                 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1867 */
1868
1869                 break;
1870
1871             case RUN_UPDATE:
1872                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1873                 break;
1874
1875             /* QUERY STATE CHANGED */
1876             
1877             // FILTERS
1878
1879             case FILTER_ADDED: 
1880                 console.log("FILTER ADDED", data);
1881                 /* Update internal record state */
1882                 manifold.query_store.add_filter(query_uuid, data);
1883
1884                 /* Propagate the message to plugins */
1885                 manifold.raise_query_event(query_uuid, event_type, data);
1886
1887                 break;
1888
1889             case FILTER_REMOVED:
1890                 console.log("FILTER REMOVED", data);
1891                 /* Update internal record state */
1892                 manifold.query_store.remove_filter(query_uuid, data);
1893
1894                 /* Propagate the message to plugins */
1895                 manifold.raise_query_event(query_uuid, event_type, data);
1896
1897                 break;
1898
1899             case FIELD_ADDED:
1900                 main_query = query_ext.main_query_ext.query;
1901                 main_update_query = query_ext.main_query_ext.update_query;
1902                 query.select(data);
1903
1904                 // Here we need the full path through all subqueries
1905                 path = ""
1906                 // XXX We might need the query name in the QueryExt structure
1907                 main_query.select(data);
1908
1909                 // XXX When is an update query associated ?
1910                 // XXX main_update_query.select(value);
1911
1912                 manifold.raise_query_event(query_uuid, event_type, data);
1913                 break;
1914
1915             case FIELD_REMOVED:
1916                 query = query_ext.query;
1917                 main_query = query_ext.main_query_ext.query;
1918                 main_update_query = query_ext.main_query_ext.update_query;
1919                 query.unselect(data);
1920                 main_query.unselect(data);
1921
1922                 // We need to inform about changes in these queries to the respective plugins
1923                 // Note: query & main_query have the same UUID
1924                 manifold.raise_query_event(query_uuid, event_type, data);
1925                 break;
1926         }
1927         // We need to inform about changes in these queries to the respective plugins
1928         // Note: query, main_query & update_query have the same UUID
1929
1930         // http://trac.myslice.info/ticket/32
1931         // Avoid multiple calls to the same event
1932         //manifold.raise_query_event(query_uuid, event_type, value);
1933
1934         // We are targeting the same object with get and update
1935         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1936         // NOTE: Editing a subquery == editing a local view on the destination
1937
1938         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1939         // For the time being, we will collect all columns during the first query
1940     },
1941
1942     /* Publish/subscribe channels for internal use */
1943     get_channel: function(type, query_uuid) {
1944         if ((type !== 'query') && (type != 'record'))
1945             return null;
1946         return '/' + type + '/' + query_uuid;
1947     },
1948
1949 }; // manifold object
1950 /* ------------------------------------------------------------ */
1951
1952 (function($) {
1953
1954     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1955     // https://gist.github.com/661855
1956     var o = $({});
1957     $.subscribe = function( channel, selector, data, fn) {
1958       /* borrowed from jQuery */
1959       if ( data == null && fn == null ) {
1960           // ( channel, fn )
1961           fn = selector;
1962           data = selector = undefined;
1963       } else if ( fn == null ) {
1964           if ( typeof selector === "string" ) {
1965               // ( channel, selector, fn )
1966               fn = data;
1967               data = undefined;
1968           } else {
1969               // ( channel, data, fn )
1970               fn = data;
1971               data = selector;
1972               selector = undefined;
1973           }
1974       }
1975       /* </ugly> */
1976   
1977       /* We use an indirection function that will clone the object passed in
1978        * parameter to the subscribe callback 
1979        * 
1980        * FIXME currently we only clone query objects which are the only ones
1981        * supported and editable, we might have the same issue with results but
1982        * the page load time will be severely affected...
1983        */
1984       o.on.apply(o, [channel, selector, data, function() { 
1985           for(i = 1; i < arguments.length; i++) {
1986               if ( arguments[i].constructor.name == 'ManifoldQuery' )
1987                   arguments[i] = arguments[i].clone();
1988           }
1989           fn.apply(o, arguments);
1990       }]);
1991     };
1992   
1993     $.unsubscribe = function() {
1994       o.off.apply(o, arguments);
1995     };
1996   
1997     $.publish = function() {
1998       o.trigger.apply(o, arguments);
1999     };
2000   
2001 }(jQuery));
2002
2003 /* ------------------------------------------------------------ */
2004
2005 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
2006 //make sure to expose csrf in our outcoming ajax/post requests
2007 $.ajaxSetup({ 
2008      beforeSend: function(xhr, settings) {
2009          function getCookie(name) {
2010              var cookieValue = null;
2011              if (document.cookie && document.cookie != '') {
2012                  var cookies = document.cookie.split(';');
2013                  for (var i = 0; i < cookies.length; i++) {
2014                      var cookie = jQuery.trim(cookies[i]);
2015                      // Does this cookie string begin with the name we want?
2016                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
2017                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
2018                      break;
2019                  }
2020              }
2021          }
2022          return cookieValue;
2023          }
2024          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
2025              // Only send the token to relative URLs i.e. locally.
2026              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
2027          }
2028      } 
2029 });