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