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