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