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