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