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